Saturday, December 3, 2016

How to Upload and Publish Visual Studio 2012 Project to GitHub

Hello,
In this tutorial, I will demonstrate on how to upload and publish a Visual Studio 2012 project to GitHub. Steps 1 and 2 are needed because editions of Visual Studio (2013 and 2015) has built-in extension for Git. So to start with, perform the detailed steps below.

1. Close all instance of Visual Studio. Download and Install Visual Studio 2012 Update 4 (Latest Update)
2. Download and Install Visual Studio Tools for Git. (Search in marketplace.visualstudio.com)
3. Create a sample Repository. (Uncheck Initialize this repository with a README)
4. Copy the url generated by the repository with .git extension. This will be used when you publish the project.
5. Open Sample project to be committed. Right click on the solution and choose Git instead of Team Foundation Version Control.
6. Open Team Explorer via View Menu (View-> Team Explorer).
7. Click Home (Home icon) and then choose Changes. This will open up the project in which you can select files to be Included or Excluded to be checked-in/committed. Add your commit message and then click Commit.
8. This will show a success commit message with the Commit ID.
9. Next Click Sync to share changes with the server.
10. When prompted with Publish to Remote Repository, just enter the Git url generated when creating the repository. Then click Publish.
11. Refresh the newly created repository in Github. You should be able to view the solution file including the project.


That's it.. :-)

Friday, December 2, 2016

Github Repository (DotNetGenetics)

Hi!
Today, I just created a repository account in GitHub .NET Genetics. I'll be adding some snippets and projects posted in this blog or in the .NET Community VBForums.
Cheers! :-)

AllowUsersToAddRows in DataGridView not working if DataSource is List<T>

Greetings!
Going back to a previous project of mine, I found out that some DataGridView control's DataSource where set using List<T> and as a result, prevented the users to add new data to the DataGridView.
private void List()
{
 List<Item> list = new List<Item>();
 for (int i = 0; i < 100; i++)
 {
  list.Add(new Item() { ID = i, Name = String.Format("{0}:{1}", "Test", i.ToString()) });
 }

 DataGridView1.DataSource = list;
}
The common solution is to use DataTable as the DataSource but if we want to use a List type object, we could use BindingList<T> or BindingSource. Both of these have AllowNew property which indicates that you can add items to the list using the AddNew() method. It is stated in DataGridView.AllowUsersToAddRows that "If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.".Well, List<T> does not implement IBindingList while BindingSource and BindingList implements this interface.
private void BindingList()
{
 BindingList<Item> list = new BindingList<Item>();
 for (int i = 0; i < 100; i++)
 {
  list.Add(new Item() { ID = i, Name = String.Format("{0}:{1}", "Test", i.ToString()) });
 }

 DataGridView1.DataSource = list;
}

Monday, November 28, 2016

Unexpected character encountered while parsing value: C. Path '', line 0, position 0. (Deserialize JSON string error)

Hi,
A common issue when deserializing a JSON object is to pass the filepath of the JSON file to the Deserialize() method instead of the string content of that file such as the code below.
var obj = JsonConvert.DeserializeObject<Employee>(@"D:\Data\Employee.json")
When calling the Deserialize() method, you need to make sure that the parameter passed is a JSON string value instead of the file path. Use StreamReader class or File.ReadAllText() to get the content of the JSON file.
using (StreamReader reader = new StreamReader(@"D:\Data\Employee.json")) 
{
 string json = reader.ReadToEnd();
 var obj = JsonConvert.DeserializeObject<Employee>(json);
}

Exclude property mapping in Entity Framework Code First Approach

Hi all,
Given a database table such as User with fields Id, UserName and Password that will be mapped to a class using Entity Framework called User with an additional field of ConfirmPassword.
public class User 
{
 public int Id { get; set; }

 public string UserName { get; set; }

 public string Password { get; set; }
 
 public string ConfirmPassword { get; set; }
}
I would like to exclude the ConfirmPassword field from being mapped to the User table. So, after doing some searching, the solution is to decorate the property with [NotMapped] attribute and make sure to reference the DataAnnotations namespace (System.ComponentModel.DataAnnotations.Schema).
using System.ComponentModel.DataAnnotations.Schema;
public class User : IEntity
{
 public int Id { get; set; }

 public string UserName { get; set; }

 public string Password { get; set; }

 [NotMapped] 
 public string ConfirmPassword { get; set; }
}

Thursday, November 24, 2016

Update DataTable values using LINQ

Hello,
Here's how to update DataTable value(s) using Method or Query syntax in LINQ.
C# Code
private void Form1_Load(object sender, EventArgs e)
{
 DataTable dt = new DataTable("tblEntTable");
 dt.Columns.Add("ID", typeof(string));
 dt.Columns.Add("Amount", typeof(decimal));
 dt.Rows.Add(new object[] {"1", 100.51});
 dt.Rows.Add(new object[] {"2", 200.52});
 dt.Rows.Add(new object[] {"3", 500.24});
 dt.Rows.Add(new object[] {"4", 400.31});
 dt.Rows.Add(new object[] {"5", 600.88});
 dt.Rows.Add(new object[] {"6", 700.11});

 //QuerySyntax(dt);
 MethodSyntax(dt);
}

private void QuerySyntax(DataTable dt)
{
 var result = from row in dt.AsEnumerable()
     select new
     {
      ID = row.Field<string>("ID"),
      Amount = 900.23
     };

 DataGridView1.DataSource = result.ToList();
}

private void MethodSyntax(DataTable dt)
{
 Array.ForEach(dt.AsEnumerable().ToArray(), (row)=>{
  row["Amount"] = 800;
 });

 DataGridView1.DataSource = dt;
}
VB.NET
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 Dim dt As New DataTable("tblEntTable")
 dt.Columns.Add("ID", GetType(String))
 dt.Columns.Add("Amount", GetType(Decimal))
 dt.Rows.Add(New Object() {"1", 100.51})
 dt.Rows.Add(New Object() {"2", 200.52})
 dt.Rows.Add(New Object() {"3", 500.24})
 dt.Rows.Add(New Object() {"4", 400.31})
 dt.Rows.Add(New Object() {"5", 600.88})
 dt.Rows.Add(New Object() {"6", 700.11})

 MethodSyntax(dt)
 'QuerySyntax(dt)
End Sub

Sub MethodSyntax(ByVal dt As DataTable)
 Array.ForEach(dt.AsEnumerable().ToArray(), Sub(row) row("Amount") = 900.23)
 DataGridView1.DataSource = dt
End Sub

Sub QuerySyntax(ByVal dt As DataTable)
 Dim result = From row In dt.AsEnumerable()
     Select New With { _
     .ID = row.Field(Of String)("ID"), _
     .Amount = 800
     }

 DataGridView1.DataSource = result.ToList()
End Sub
Output

Wednesday, November 23, 2016

String was not recognized as a valid DateTime (Assign date value with dd-MM-yyyy format to DateTimePicker control)

Good day!
A question was raised on how to assign a date value with format dd-MM-yyyy (05-11-2016) to a DateTimePicker control Text property. Using Convert.ToDateTime() to assign the given value will cause an exception String was not recognized as a valid DateTime. So, a workaround for this is to parse the date value using DateTime.ParseExact() as presented below. The default format of the DateTimePicker control is long.
var dateObj = DateTime.ParseExact("05-11-2016", "dd-MM-yyyy", CultureInfo.InvariantCulture);
DateAttendancePicker.Text = dateObj.ToString();
Make sure that the second parameter of the function is the correct format of the input value.

Monday, November 21, 2016

DataGridView ComboBox Cascade

Good day to all!
Here's an example of how to perform a combobox lookup or cascade using two DataGridViewComboBoxColumns inside a DataGridView control Combo Lookup in DGV. The solution presented is in VB.NET, so I decided to create a C# equivalent for this. In form load event, populate two DataTables for Roles and Employees. Each employee is assigned to a specific role.
private void Form1_Load(object sender, EventArgs e)
{
 DataGridView1.Rows.Add();

 dtRole.Columns.Add("RoleID");
 dtRole.Columns.Add("RoleName");
 dtRole.Rows.Add(1, "Admin");
 dtRole.Rows.Add(2, "Instructor");
 dtRole.Rows.Add(3, "Utility");

 dtEmployee.Columns.Add("RoleID");
 dtEmployee.Columns.Add("EmployeeID");
 dtEmployee.Columns.Add("EmployeeName");
 dtEmployee.Rows.Add(1, 1, "Sam");
 dtEmployee.Rows.Add(1, 2, "Nicole");
 dtEmployee.Rows.Add(2, 3, "Donald");
 dtEmployee.Rows.Add(2, 4, "Brenda");
 dtEmployee.Rows.Add(3, 5, "Jenny");
 dtEmployee.Rows.Add(3, 6, "Michael");

 Role.ValueMember = dtRole.Columns[0].ColumnName;
 Role.ValueType = typeof(string);
 Role.DisplayMember = dtRole.Columns[1].ColumnName;
 Role.DataSource = dtRole;
}
The cascade code is performed in CellValueChanged event of the DataGridView.
private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{            
 if (e.RowIndex >= 0 && ((DataGridView)sender).Columns[e.ColumnIndex].GetType() == typeof(DataGridViewComboBoxColumn))
 {
  if (e.ColumnIndex == ((DataGridView)sender).Columns["Role"].Index)
  {
   if (((DataGridView)sender).Rows[e.RowIndex].Cells["Role"].Value != null)
   {
    DataView employeesDV = new DataView(dtEmployee);
    employeesDV.RowFilter = "RoleID = " + ((DataGridViewComboBoxCell)DataGridView1.Rows[e.RowIndex].Cells["Role"]).Value; //DataGridView1.CurrentCell.Value;
    employeesDV.RowStateFilter = DataViewRowState.CurrentRows;

    if (employeesDV.Count > 0)
    {
     DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)DataGridView1.Rows[e.RowIndex].Cells["Employee"];
     cell.ValueMember = "EmployeeID";
     Role.ValueType = typeof(int);
     cell.DisplayMember = "EmployeeName";
     cell.DataSource = employeesDV;
    }
   }
  }
 }           
}
Role Selection Employees under Instructor Role

Saturday, November 19, 2016

DataGridViewComboBoxColumn show Dropdown in single click instead of double click

Hi,
When adding DataGridViewComboBoxColumn control to a DataGridView control, the dropdown shows when you double click instead of single click. The common fix to this is to set the EditMode property to EditOnEnter. Given that you don't want to alter the default settings of the DataGrid control and you want to handle it through code,I found the solution in this website DATAGRIDVIEWCOMBOBOXCOLUMN REQUIRES MULTIPLE CLICKS TO SELECT AN ITEM from a comment made by a developer. However, there's a slight issue in the code provided since a column index returned might have a -1 index and this will cause an Unhandled Exception. The revision made is to add a condition that will check if the ColumnIndex of the DataGridView cell is greater than or equal to 0.
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
 DataGridView grid = (DataGridView)sender;
 if (e.ColumnIndex >= 0)
 {
  if (grid.Columns[e.ColumnIndex].Name == "Role" || grid.Columns[e.ColumnIndex].Name == "Employee")
  {
   grid.BeginEdit(true);
   ((ComboBox)grid.EditingControl).DroppedDown = true;
  } 
 }
}                
That's it. :-)

Tuesday, November 8, 2016

Login to Facebook account using Webbrowser and LINQ

Hi,
Here's how to login to your facebook account using Webbrowser control and LINQ in Windows Forms. The input elements are checked through their attributes like "email" for email fields, "password" for password fields and "submit" for submission control. These codes are inside the DocumentCompleted event.
C# code
WebBrowser1.Document.GetElementsByTagName("input").Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute("type") == "email").SetAttribute("value", "your email address");
WebBrowser1.Document.GetElementsByTagName("input").Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute("type") == "password").SetAttribute("value", "your user name");
WebBrowser1.Document.GetElementsByTagName("input").Cast<HtmlElement>().FirstOrDefault(t => t.GetAttribute("type") == "submit").InvokeMember("click");       
VB.NET Code
WebBrowser1.Document.GetElementsByTagName("input").Cast(Of HtmlElement)().FirstOrDefault(Function(t) t.GetAttribute("type") = "email").SetAttribute("value", "your email address")
WebBrowser1.Document.GetElementsByTagName("input").Cast(Of HtmlElement)().FirstOrDefault(Function(t) t.GetAttribute("type") = "password").SetAttribute("value", "your user name")
WebBrowser1.Document.GetElementsByTagName("input").Cast(Of HtmlElement)().FirstOrDefault(Function(t) t.GetAttribute("type") = "submit").InvokeMember("click")

Inline-Block elements not filling up the entire width of container (div) using width percentage

Hello,
I encountered this issue several weeks ago and decided to put the solution here. This pertains to inline-block elements not occupying the entire width of the container. Each element's width is set using percentage instead of pixels. After doing some research, I found a solution here: Display Inline-Block with Widths as Percent with the solution to set the font-size of the container element to 0 and add style box-sizing to border-box. For the child elements, set the default font size.
CSS Code
.container {
            margin: 0 0 1em 0;
            border: 2px solid black;
            padding: 1em;
            font-size: 0; 
            box-sizing: border-box; 
        }

        nav {
            vertical-align: top;
            display: inline-block;
            width: 25%;
            word-wrap: break-word;
            background-color: lightgray;
            font-size: 16px; 
        }

        .column {
            vertical-align: top;
            display: inline-block;
            width: 75%;
            background-color: blueviolet;
            font-size: 16px; 
        }

        section {           
            background-color: orchid;
        }
HTML Code
<div class="container">
 <nav>
  <ul>
   <li><a href="#">Home</a></li>
   <li><a href="#">Solutions</a></li>
   <li><a href="#">Products</a></li>
   <li><a href="#">FAQ</a></li>
   <li><a href="#">About Us</a></li>
   <li><a href="#">Contact Us</a></li>
  </ul>
 </nav>
 <div class="column">
  <section>
   <p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
   </p>
  </section>
  <section>
   <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit.
   </p>
  </section>
 </div>
</div>
Fiddle inline-block issue

Sunday, November 6, 2016

WPF DataGrid set RowBackground using AlternationCount and DataTriggers

Hi,
There was a question raised on how to set the WPF DataGrid RowBackground with AlternationCount (alternating row colors) and DataTriggers without overriding the Alternation count. The fix is to declare a DataGrid.Style that contains settings for RowBackGround and AlternationCount. And in your DataGrid.RowStyle, define the DataTriggers to highlight RowBackground based on a given Value.
<DataGrid x:Name="dgEmployees" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Height="346" 
                  RowHeaderWidth="0" AutoGenerateColumns="False" CanUserAddRows="False" CanUserResizeColumns="False" 
                  CanUserDeleteRows="False" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" 
                  HeadersVisibility="Column" IsReadOnly="True" >
 <DataGrid.Resources>
  <SolidColorBrush x:Key="ConrolLightColorKey" Color="{DynamicResource {x:Static SystemColors.ControlLightColorKey}}"/>
 </DataGrid.Resources>
 <DataGrid.Style>                
  <Style TargetType="{x:Type DataGrid}">
   <Setter Property="RowBackground" Value="{StaticResource ConrolLightColorKey}"/>
   <Setter Property="AlternationCount" Value="2" />
  </Style>
 </DataGrid.Style>
 <DataGrid.RowStyle>
  <Style TargetType="DataGridRow">
   <Style.Triggers>
    <DataTrigger  Binding="{Binding Department}" Value="1">
     <Setter Property="Background" Value="Red"></Setter>
    </DataTrigger>
    <DataTrigger Binding="{Binding Department}" Value="2">
     <Setter Property="Background" Value="Green"></Setter>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </DataGrid.RowStyle>
 <DataGrid.Columns>
  <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="50*" />
  <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" Width="120*" />
  <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" Width="120*" />
  <DataGridTextColumn Header="Department" Binding="{Binding Department}" Width="120*" />
 </DataGrid.Columns>
</DataGrid>

Cheers!

Thursday, November 3, 2016

Read SQL Server XML Data Type Column in C#.NET

Hi all,
In this demo, I have dummy XML files saved to an XML column in a table. The files have the same structure of nodes, except that some files have altered price value of 104.95. The is the structure of the dummy XML file.
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>
      After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.
    </description>
  </book>
  <book id="bk104">
    <author>Corets, Eva</author>
    <title>Oberon's Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>
      In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.
    </description>
  </book>
  <book id="bk105">
    <author>Corets, Eva</author>
    <title>The Sundered Grail</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-09-10</publish_date>
    <description>
      The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.
    </description>
  </book>
  <book id="bk106">
    <author>Randall, Cynthia</author>
    <title>Lover Birds</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-09-02</publish_date>
    <description>
      When Carla meets Paul at an ornithology
      conference, tempers fly as feathers get ruffled.
    </description>
  </book>
  <book id="bk107">
    <author>Thurman, Paula</author>
    <title>Splish Splash</title>
    <genre>Romance</genre>
    <price>4.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      A deep sea diver finds true love twenty
      thousand leagues beneath the sea.
    </description>
  </book>
  <book id="bk108">
    <author>Knorr, Stefan</author>
    <title>Creepy Crawlies</title>
    <genre>Horror</genre>
    <price>104.95</price>
    <publish_date>2000-12-06</publish_date>
    <description>
      An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects.
    </description>
  </book>
  <book id="bk109">
    <author>Kress, Peter</author>
    <title>Paradox Lost</title>
    <genre>Science Fiction</genre>
    <price>6.95</price>
    <publish_date>2000-11-02</publish_date>
    <description>
      After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems
      of being quantum.
    </description>
  </book>
  <book id="bk110">
    <author>O'Brien, Tim</author>
    <title>Microsoft .NET: The Programming Bible</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-09</publish_date>
    <description>
      Microsoft's .NET initiative is explored in
      detail in this deep programmer's reference.
    </description>
  </book>
  <book id="bk111">
    <author>O'Brien, Tim</author>
    <title>MSXML3: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>36.95</price>
    <publish_date>2000-12-01</publish_date>
    <description>
      The Microsoft MSXML3 parser is covered in
      detail, with attention to XML DOM interfaces, XSLT processing,
      SAX and more.
    </description>
  </book>
  <book id="bk112">
    <author>Galos, Mike</author>
    <title>Visual Studio 7: A Comprehensive Guide</title>
    <genre>Computer</genre>
    <price>49.95</price>
    <publish_date>2001-04-16</publish_date>
    <description>
      Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.
    </description>
  </book>
</catalog>
These files are saved in a table with XML column. Such XML files BOM1.xml and BOM3.xml have price value of 104.95. In order to read the XML column using C# code,you can use Cross Apply query in the command text and as a good practice, use SQLParameter when passing data to the query.
private static void ReadXMLColumn()
{            
 double price = 104.95;
 DataTable table = new DataTable();
 using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
 {
  string query = "SET ANSI_NULLS, QUOTED_IDENTIFIER, CONCAT_NULL_YIELDS_NULL, ANSI_WARNINGS, ANSI_PADDING ON;"
      + " select * from "
      + " (select id, name, pref.value('(text())[1]', 'varchar(max)') as price "
      + " from "
      + " XMLBooks CROSS APPLY "
      + " bookXML.nodes('(/catalog/book/price)') AS bookXML(pref) "
      + " )  as Result where price = @price;";

  SqlCommand command = new SqlCommand(query, con);
  con.Open();
  command.Parameters.Add("@price", SqlDbType.Float).Value = price;
  using (SqlDataAdapter da = new SqlDataAdapter(command))
  {
   da.Fill(table);
   if (table.Rows.Count > 0)
   {
    foreach (DataRow row in table.Rows)
    {
     Console.WriteLine("ID Number {0} of XML File {1} with XML Price value of {2}", 
           row["id"].ToString(), 
           row["name"].ToString(), price);
    }
   }
  }
 }
}
The code above produces the output such as below.

Saturday, October 29, 2016

XML parsing: line 1, character 38, unable to switch the encoding

Hello all,
Given the task at hand that your going to insert XML data into an XML column in SQL Server and you encounter this error "XML parsing: line 1, character 38, unable to switch the encoding", it seems the insertion of XML data failed due to this line here: <?xml version="1.0" encoding="utf-8" ?>. After doing some research, I found a tutorial on how to avoid unicode issues when inserting XML data into an XML column in SQL Server which is the basis of the solution. I just change the Encoding of the stream to UTF8 to match the encoding of the XML file.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
 SqlCommand command = new SqlCommand("Insert into XMLTable(name, xmlData) values (@name, @xmlData)", con);
 con.Open();

 string xmlFile = File.ReadAllText(location);

 using (MemoryStream stream = new MemoryStream())
 {
  using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) 
  {
   writer.Write(xmlFile);
   writer.Flush();
   stream.Position = 0;

   SqlParameter parameter = new SqlParameter("@xmlData", SqlDbType.Text);
   parameter.Value = new SqlXml(stream);
   command.Parameters.Add("@name", SqlDbType.VarChar).Value = "Products.xml";
   command.Parameters.Add(parameter);
   command.ExecuteNonQuery();
  }
 }
}
Reference: Avoiding Unicode issues when inserting XML into a SQL Database

Wednesday, October 26, 2016

Seed Roles and Users to an existing database in ASP.NET MVC 5 using Identity

Hello,

In this tutorial, I will demonstrate seeding roles and users to an existing database in an ASP.NET MVC 5 application using Identity framework. For simplicity, I will use a Northwind. This database doesn't have membership tables at all.
To begin with, accomplish the steps below:
1. Create an ASP.NET MVC application and then change web.config connectionStrings element to connect to an existing database (Northwind as my example).
2. Under Package Manager Console type
PM> Enable-Migrations
3. Under Package Manager Console type
PM> Add-Migration ASPMembership
* This will create a file Timespan_ASPMembership.cs inside Migrations folder with scripts to create Membership Tables such as AspNetUsers, AspNetRoles and etc.
4. Under Package Manager Console type
PM> Update-Database
* This will add membership tables to Northwind database.
5. To seed Roles and Users, create a class SeedRolesAndUsers.cs inside Models folder. This class references Microsoft.AspNet.Identity and Microsoft.AspNet.Identity.EntityFramework namespaces. The code below adds Customer or Manager role if they didn't exist. And then the remaining part of the code, creates a user assigned to a specific role.
public class SeedRolesAndUsers
    {        
        protected static void Seed(ApplicationDbContext context)
        {
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

            if (!roleManager.RoleExists("Customer"))
            {
                var roleresult = roleManager.Create(new IdentityRole("Customer"));
            }
            if (!roleManager.RoleExists("Manager"))
            {
                var roleresult = roleManager.Create(new IdentityRole("Manager"));
            }

            string userName = "jimmymgr01";
            string password = "jimmymgr01";
            ApplicationUser user = userManager.FindByName(userName);
            if (user == null)
            {
                user = new ApplicationUser()
                {
                    UserName = userName
                };

                IdentityResult userResult = userManager.Create(user, password);
                if (userResult.Succeeded)
                {
                    var result = userManager.AddToRole(user.Id, "Manager");
                }
            }
        }
    }
6. In Global.asax.cs, call the seed method and then pass an ApplicationDBContext object to it's parameter.
 protected void Application_Start()
    {
         AreaRegistration.RegisterAllAreas();
         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
         RouteConfig.RegisterRoutes(RouteTable.Routes);
         BundleConfig.RegisterBundles(BundleTable.Bundles);
   
   //call seed method
         ApplicationDbContext context = new ApplicationDbContext();
         SeedRolesAndUsers.Seed(context);
    }
7. Run the application. You should see the tables AspNetRoles, AspNetUsers, AspNetUserRoles populated with data.
VB.NET Version of this tutorial: Seed Roles and Users to an existing database in ASP.NET MVC 5 using Identity

Monday, October 24, 2016

The term 'Enable-Migrations' is not recognized as the name of a cmdlet

Hello,

When I started creating an ASP.NET MVC application in VB.NET and decided to add Membership tables using the Enable-Migrations command in Package Manager Console, I encountered this error 'The term 'Enable-Migrations' is not recognized as the name of a cmdlet'. In C#, I haven't encountered this issue. So, what I did was to Rebuild the project, and then restart Visual Studio IDE.
Eureka,the problem was fixed. :-)
Cheers! :)

Set WPF DataGridCell and DataGridRow color using Triggers

Hi,

There was a question on the forums on how to set the color of DataGridCell or DataGridRow using XAML without code. I always thought that the solution will be to use code using IValueConverter. After doing some searching on MSDN and google, the answer is straightforward using Triggers. To set the color of DataGridRow, you set the DataGrid.CellStyle just below the DataGrid markup.
<DataGrid Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False"  Name="dgStudents">
 <DataGrid.CellStyle>
  <Style TargetType="{x:Type DataGridCell}">
   <Style.Triggers>
    <DataTrigger Binding="{Binding Age}" Value="28">
     <Setter Property="Background" Value="Gray"></Setter>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </DataGrid.CellStyle>
 <DataGrid.Columns>               
  <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />
  <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True" />
  <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />
  <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />
 </DataGrid.Columns>
</DataGrid>
To set the DataGridCell color, you need to apply the Style of a specific column such as DataGridTextColumn.
<DataGrid Grid.Row="0" Grid.Column="0" AutoGenerateColumns="False" CanUserAddRows="False"  Name="dgStudents">
 <DataGrid.Columns>               
  <DataGridTextColumn Header="ID" Binding="{Binding Path=ID}" Width="120" IsReadOnly="True" />
  <DataGridTextColumn Header="Age" Binding="{Binding Path=Age}" MinWidth="100" IsReadOnly="True">
   <DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
     <Style.Triggers>
      <DataTrigger Binding="{Binding Path=Age}" Value="28">
       <Setter Property="Background" Value="Gray"/>
      </DataTrigger>
     </Style.Triggers>
    </Style>
   </DataGridTextColumn.CellStyle>
  </DataGridTextColumn>
  <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" MinWidth="150" IsReadOnly="True" />
  <DataGridTextColumn Header="Address" Binding="{Binding Path=Address}" MinWidth="150" IsReadOnly="True" />
 </DataGrid.Columns>
</DataGrid>
Note: Both markups will set the color of the row and cell based from the value of Age which is 28.

Thursday, October 20, 2016

@Html.EnumDropDownListFor() with Html Attributes

Hello,
I did some research on how to use enums as model for DropDownListFor() for a current application and will format it with Bootstrap classes. For ASP.NET MVC 4, it does not have that kind of helper yet. Luckily, I found an article here Creating a DropDownList helper for enums which supports enums as data source. However, it does not have an argument where in you can pass a boostrap class such as form-control. To achieve the desired output, all you need to do is modify the helper and add another parameter for html attributes which will then be used by the DropDownListFor().
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, 
 Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
 ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
 IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

 IEnumerable<SelectListItem> items = values.Select(value => new SelectListItem
          {
           Text = value.ToString(),
           Value = value.ToString(),
           Selected = value.Equals(metadata.Model)
          });

 return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}

Thanks to the author of this extension. :-)

Monday, October 17, 2016

Model binding with ASP.NET MVC @Html.ListBoxFor().

Hi,

In this tutorial, I will present three ways on model binding with the @Html.ListBoxFor() helper using a ViewModel class and a simple model class. The Index view below has three @Html.ListBoxFor() controls inside a form that will be populated with different ways using MultiSelectList class, List<SelectListItem>, and IEnumerable<CountryInfo>.
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
 <div class="form-group">
  <div class="form-group">
   @Html.ListBoxFor(x => x.SelectedPhoneNumbers, Model.phoneNumbers, new { @class = "form-control " })
  </div>
  <div class="form-group">
   @Html.ListBoxFor(x => x.SelectedItemIds, Model.Items, new { @class = "form-control " })
  </div>
  <div class="form-group">
   @Html.ListBoxFor(x => x.Country.SelectedCountry, new MultiSelectList(Model.Country.Countries, "Code", "Text"), new { @class = "form-control " })

  </div>
 </div>
 <button id="btnRegisterSubmit" type="submit" class="btn btn-primary">Register</button>
}
Given the model (Country.cs) and ViewModel (MyViewModel.cs) classes below:
public class Country
{
     public IEnumerable<CountryInfo> Countries { get; set; }
     public IEnumerable<string> SelectedCountry { get; set; }
}

public struct CountryInfo
{
 public int Code { get; set; }
 public string Text { get; set; }
}

public class MyViewModel
{
 public int[] SelectedItemIds { get; set; }
 public MultiSelectList Items { get; set; }
 public string[] SelectedPhoneNumbers { get; set; }
 public List<SelectListItem> phoneNumbers { get; set; }
 public Country Country { get; set; }
}
In the controller method, populate the ViewModel properties with dummy records. Make sure to reference the Models folder so you can access the ViewModel class. I also added comments to each property with their associated ListBox control.
public ActionResult Index()
{
 var model = new MyViewModel
 {
                // @Html.ListBoxFor(x => x.SelectedItemIds, Model.Items, new { @class = "form-control " })
  Items = new MultiSelectList(new[] {    
    new { Id = 1, Name = "item 1" },
    new { Id = 2, Name = "item 2" },
    new { Id = 3, Name = "item 3" },
   }, "Id", "Name", null     
  ),
                // @Html.ListBoxFor(x => x.SelectedPhoneNumbers, Model.phoneNumbers, new { @class = "form-control " })
  phoneNumbers = new List<SelectListItem>()
  {
   new SelectListItem(){ Text ="312-4455", Value="1", Selected= false},
   new SelectListItem(){ Text ="255-5035", Value="2", Selected= false},
   new SelectListItem(){ Text ="253-3441", Value="3", Selected= true},
   new SelectListItem(){ Text ="262-1111", Value="4", Selected= false}
  },
                // @Html.ListBoxFor(x => x.Country.SelectedCountry, new MultiSelectList(Model.Country.Countries, "Code", "Text"), new { @class = "form-control " })
  Country = new Country()
  {
   Countries = new List<CountryInfo>(){
      new CountryInfo{ Code = 1001, Text = "USA"},
      new CountryInfo{ Code = 1002, Text = "United Kingdom"}
    },
   SelectedCountry = new List<string>()
  }
 };

 return View(model);
}

Screenshot

Friday, October 14, 2016

Read or Parse JSON using JavaScriptSerializer class

Hello,
Here's a simple demonstration on how to parse JSON data using .NET's JavaScriptSerializer class. Given the sample JSON data below:
{
  "catalog": {
    "book": [
      {
        "id": "bk101",
        "author": "Gambardella, Matthew",
        "title": "XML Developer's Guide",
        "genre": "Computer",
        "price": "44.95",
        "publish_date": "2000-10-01",
        "description": "An in-depth look at creating applications 
      with XML."
      },
      {
        "id": "bk102",
        "author": "Ralls, Kim",
        "title": "Midnight Rain",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-12-16",
        "description": "A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world."
      },
      {
        "id": "bk103",
        "author": "Corets, Eva",
        "title": "Maeve Ascendant",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2000-11-17",
        "description": "After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society."
      },
      {
        "id": "bk104",
        "author": "Corets, Eva",
        "title": "Oberon's Legacy",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2001-03-10",
        "description": "In post-apocalypse England, the mysterious 
      agent known only as Oberon helps to create a new life 
      for the inhabitants of London. Sequel to Maeve 
      Ascendant."
      },
      {
        "id": "bk105",
        "author": "Corets, Eva",
        "title": "The Sundered Grail",
        "genre": "Fantasy",
        "price": "5.95",
        "publish_date": "2001-09-10",
        "description": "The two daughters of Maeve, half-sisters, 
      battle one another for control of England. Sequel to 
      Oberon's Legacy."
      },
      {
        "id": "bk106",
        "author": "Randall, Cynthia",
        "title": "Lover Birds",
        "genre": "Romance",
        "price": "4.95",
        "publish_date": "2000-09-02",
        "description": "When Carla meets Paul at an ornithology 
      conference, tempers fly as feathers get ruffled."
      },
      {
        "id": "bk107",
        "author": "Thurman, Paula",
        "title": "Splish Splash",
        "genre": "Romance",
        "price": "4.95",
        "publish_date": "2000-11-02",
        "description": "A deep sea diver finds true love twenty 
      thousand leagues beneath the sea."
      },
      {
        "id": "bk108",
        "author": "Knorr, Stefan",
        "title": "Creepy Crawlies",
        "genre": "Horror",
        "price": "4.95",
        "publish_date": "2000-12-06",
        "description": "An anthology of horror stories about roaches,
      centipedes, scorpions  and other insects."
      },
      {
        "id": "bk109",
        "author": "Kress, Peter",
        "title": "Paradox Lost",
        "genre": "Science Fiction",
        "price": "6.95",
        "publish_date": "2000-11-02",
        "description": "After an inadvertant trip through a Heisenberg
      Uncertainty Device, James Salway discovers the problems 
      of being quantum."
      },
      {
        "id": "bk110",
        "author": "O'Brien, Tim",
        "title": "Microsoft .NET: The Programming Bible",
        "genre": "Computer",
        "price": "36.95",
        "publish_date": "2000-12-09",
        "description": "Microsoft's .NET initiative is explored in 
      detail in this deep programmer's reference."
      },
      {
        "id": "bk111",
        "author": "O'Brien, Tim",
        "title": "MSXML3: A Comprehensive Guide",
        "genre": "Computer",
        "price": "36.95",
        "publish_date": "2000-12-01",
        "description": "The Microsoft MSXML3 parser is covered in 
      detail, with attention to XML DOM interfaces, XSLT processing, 
      SAX and more."
      },
      {
        "id": "bk112",
        "author": "Galos, Mike",
        "title": "Visual Studio 7: A Comprehensive Guide",
        "genre": "Computer",
        "price": "49.95",
        "publish_date": "2001-04-16",
        "description": "Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are 
      integrated into a comprehensive development 
      environment."
      }
    ]
  }
}
I have created a model class that handles the deserialization of the JSON data into a C# object.
public class Book
{
 public string id { get; set; }
 public string author { get; set; }
 public string title { get; set; }
 public string genre { get; set; }
 public string price { get; set; }
 public string publish_date { get; set; }
 public string description { get; set; }
}

public class Catalog
{
 public List<Book> book { get; set; }
}

public class RootObject
{
 public Catalog catalog { get; set; }
}
Given the model class and the JSON data, the function below will read the JSON using StreamReader and will deserialize it using the Deserialize() method of the JavaScriptSerializer object.
private static void ReadBooks()
{
 string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
 string xslLocation = Path.Combine(executableLocation, "books.json");
 RootObject objBooks = new RootObject();

 using (var reader = new StreamReader(xslLocation))
 {
  var responseBody = reader.ReadToEnd();
  var deserializer = new JavaScriptSerializer();
  objBooks = deserializer.Deserialize<RootObject>(responseBody);
 }

 foreach (var item in objBooks.catalog.book)
 {
  Console.WriteLine("id: {0} \nauthor: {1} \ntitle: {2} \ngenre:{3} \nprice:{4} \npublish date: {5} \ndescription:{6}",
      item.id, item.author, item.title, item.genre, item.price, item.publish_date, item.description);
  Console.WriteLine("================================");
 }
}

Thursday, October 13, 2016

Return View() statement not redirecting to View in ASP.NET MVC using $.ajax() post.

Hello,
Normally, you submit client-side data to a controller action via @Html.BeginForm(), then perform processing statements and lastly invoke the return View(); statement inside the controller action which will redirect you to the view which basically works.

However, in a scenario where-in you will post data to a controller action using jQuery Control Event such as Button Click, the return View() statement in the controller action won't redirect to the specified view given the sample controller action below.
[HttpPost]
public ActionResult UpdatedEmpTrainings(string empId)
{
 _context = new EmployeeEntities();
 model = new List<EmployeeTrainingsViewModel>();
 model = (from emp_trainings in _context.EmployeeTrainings.AsEnumerable()
    join training in _context.Trainings.AsEnumerable()
     on emp_trainings.TrainingID equals training.TrainingID
    where emp_trainings.EmployeeID == Convert.ToInt32(empId)
    select new EmployeeTrainingsViewModel
    {
     TrainingID = emp_trainings.TrainingID.GetValueOrDefault(),
     TrainingTitle = training.TrainingTitle,
     EmployeeID = emp_trainings.EmployeeID.GetValueOrDefault()
    }).OrderBy(t => t.TrainingID).ToList();

 return View(model);
}
So, to resolve the issue in order for the return View() statement to redirect to the said view. In your jQuery $.ajax() success property, set the window.location.href value with the url data returned from the action method.
 $("#tblEmployee").on("click", "#save", function () {
 if (ids.length > 0) {
  $.ajax({
   type: "POST",
   dataType: "json",
   traditional: true,
   data: { courseID: ids, empId: JSON.stringify($('#empTextBox').val()) },
   url: "/Employee/DeleteEmpTrainings",
   success: function (dataUrl) {
    window.location.href = dataUrl;
   }
  });
 }
});
In your action result method, pass the url of the controller action with the return View() statement. Make sure to include the necessary query strings that matches the parameter list of the controller action. This action method below will call the UpdatedEmpTrainings controller action above.
public JsonResult DeleteEmpTrainings(List<string> courseID, string empId)
{
 _context = new EmployeeEntities();
 if(courseID != null)
 {
  foreach (var item in courseID)
  {
   EmployeeTraining emp_training = _context.EmployeeTrainings.AsEnumerable()
    .FirstOrDefault(t => t.TrainingID.GetValueOrDefault() == Convert.ToInt32(item) && t.EmployeeID == Convert.ToInt32(empId));
   _context.EmployeeTrainings.Remove(emp_training);
  }

  _context.SaveChanges();                
 }
 
 return Json(Url.Action("UpdatedEmpTrainings", "Employee", new { empId = empId }), JsonRequestBehavior.AllowGet); 
}
 

Wednesday, October 12, 2016

Method Line Separator in Visual Studio 2013

Hello,

There was a question in the forums on how to add a line separator in every method written in Visual Studio 2013 C# IDE. Well, there's a plugin for Visual Studio called Productivity Power Tools 2013 which you can download and install. After installing it, then proceed to making changes to your IDE.

To show line separator in your Visual Studio 2013 IDE, perform the steps below:
Click on Tools Menu -> Options -> Productivity Power Tools -> Other Extensions -> Show a separator between methods in the Editor
Screenshot:
Note: Make sure to restart Visual Studio to affect those changes.
Reference: Visual Studio 2013 Goodies

Wednesday, September 28, 2016

Change DataGridViewRow FontStyle to Bold in CellFormatting event

Hello,
There was a question raised in the forums on how to change the FontStyle of a DataGridViewRow to Bold in the CellFormatting event. A solution is to set the Font property of a row with a Font object setting it's second parameter to FontStyle.Bold.
private void EmployeeDTRDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
 if (EmployeeDTRDataGridView.Columns[e.ColumnIndex].Name == "OnLeave")
 {
  if (e.Value != System.DBNull.Value)
  {
   if (Convert.ToBoolean(e.Value) == true)
   {
    EmployeeDTRDataGridView.Rows[e.RowIndex].DefaultCellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
   }
  }
 }
}

Friday, September 23, 2016

Rounded Corner Button Example in WPF

In WPF, you can alter the corner radius of a button using Style class. In Setter class, set the Property value to Template. Inside the Setter class, add a ControlTemplate class that will target the Button control. After that, you can add a Border class and then setting it's CornerRadius property with an integer value of the desired radius. The example below is a user control that has a Button and a Style resource that will alter the Button's corner radius.
User Control
<UserControl x:Class="WPFButtonCornerRadiusXAMLVBForums.UCRoundedButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" d:DesignHeight="45" d:DesignWidth="100">
    <UserControl.Resources>
        <Style x:Key="ButtonRoundedCorner" TargetType="Button">
            <Setter Property="Background" Value="Silver"/>
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="25" Background="{TemplateBinding Background}" BorderThickness="2">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center">
                            </ContentPresenter>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
    <Grid>
        <Button Style="{StaticResource ButtonRoundedCorner}" Grid.Column="2" Grid.Row="2" Content="Hello World" 
            Width="100" Height="45" Margin="0,0,0,0" HorizontalAlignment="Center" BorderBrush="#FFF" Name="PasswordButton">
        </Button>
    </Grid>
</UserControl>
To use that user control, simply declare a xml namespace that will reference that object.
<Window x:Class="WPFButtonCornerRadius.RoundedCornerButtonDemo"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ucButton="clr-namespace:WPFButtonCornerRadius"
        Title="RoundedCornerButtonDemo" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <ucButton:UCRoundedButton Grid.Column="2" Grid.Row="2"></ucButton:UCRoundedButton>
    </Grid>
</Window>
Output