Posts

Showing posts from 2016

Donate

How To Upload And Publish Visual Studio 2012 Project To GitHub

Image
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 o

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, Lis

Unexpected character encountered while parsing value: C. Path '', line 0, position 0. (Deserialize JSON String Error In C#)

Hi, A common issue when deserializing a JSON object in C# 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 ; } }

Update DataTable Values Using LINQ In C# And VB.NET

Image
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(DataTa

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.

DataGridView ComboBox Cascade In Windows Forms

Image
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(

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.

Login To Facebook Account Using C#, 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" ).I

Inline-Block Elements Not Filling Up The Entire Width Of Div Container Using Width Percentage

Image
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 ;

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.Res

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

Image
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 ev

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 (StreamWrite

Seed Roles And Users To An Existing Database In ASP.NET MVC 5 Using Identity

Image
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 referenc

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! :)

How To Set WPF DataGridCell And DataGridRow Background Color Using Triggers

Hi, There was a question on the forums on how to set the background 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>

@Html.EnumDropDownListFor() Helper With Html Attributes In ASP.NET MVC

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<SelectListIte

Model Binding With ASP.NET MVC @Html.ListBoxFor()

Image
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", "T

Read Or Parse Or Deserialize JSON Using JavaScriptSerializer Class In C#

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": &q

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 {

Method Line Separator in Visual Studio 2013

Image
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

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); } } } }

Donate