Posts

Showing posts with the label C#

Donate

How To Read XML File Using DataTable.ReadXml() In C#

Image
Good afternoon friends! In this tutorial, I will demonstrate how to read an XML file using DataTable's ReadXml() method. While reading a file using DataSet's ReadXml() method is straightforward, using the DataTable's method might cause run-time or logical bugs. One example is that when using the DataTable's ReadXml() function, the DataTable object does not contain any records or nothing at all given that fact that the method has successfully executed. To proceed, we will read an XML file below called books.xml taken from MSDN page using DataTable's ReadXml() method. <?xml version="1.0" encoding="utf-8" ?> <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&g

How To Compute DataTable With Running Total Per Group In C#

Image
Good Evening! There was a question raised by a developer if it's possible to compute the running total of a specific DataTable column per grouping or category. The solution is to mark the category as a flag variable that indicates the group to be calculated. The sample code below creates a DataTable object with fictitious information of hardware materials that belong to a particular group specifically PartyCode column. If a column belongs to that group, it will perform calculations. If not, reset the flag variable and total so as to perform new calculations. When computing totals for large number of records, make sure to sort the DataTable using it's category. DataTable dt = new DataTable(); dt.Columns.AddRange( new DataColumn[ 5 ] { new DataColumn( "SrNo" , typeof ( int )), new DataColumn ( "PartyName" , typeof ( string )), new DataColumn ( "ItemName" , typeof ( string )), new DataColumn ( "ChqAmt" , typeof ( int

Invalid nested tag div found, expected closing tag input

Hello all, I've been experimenting on how to print html document using the said 3rd party software called iTextSharp . iTextSharp is a popular tool and has several examples on the internet regarding integration to the project and occurring issues. One of the issue I encountered is Invalid nested div tag and is expecting a closing tag input . As I trace back my html source, the tags are well-formed except that they are self closing tags such as <input>, <hr>, <img>, <br> or the like. These tags when passed to an action method as string are not properly closed and thus an issue is thrown by iTextSharp's XMLWorkerHelper's ParseXHtml() method. <img src= "~/Images/success.png" /> <input type= "hidden" name= "OrderStatusHTML" /> <input type= "submit" id= "btnSubmit" value= "Export to PDF" class= "btn btn-success" /> The solution I came up with is to fi

Read .NET Configuration Files Using NameValueSectionHandler And AppSettingsSection Types In C#

Hello all, I've read from a tutorial NameValueCollection and .NET Configuration Files which targets .NET 1.0/1.1 on how to read config files using type NameValueSectionHandler. I intend to explore more on applying this concept to recent versions of .NET frameworks. Upon doing some diggings, I came up with two options. First is using NameValueSectionHandler type and the other one is AppSettingsSections. To begin with, I have this App.config file with XML elements scriptsfiles and docfiles all registered in configSections. <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name= "scriptfiles" type= "System.Configuration.NameValueSectionHandler" /> <section name= "docfiles" type= "System.Configuration.AppSettingsSection" /> </configSections> <scriptfiles> <add key= "C:\batchfiles\2017" value= "*.bat" />

Cannot convert type 'System.Configuration.ConfigurationSection' to 'System.Collections.Specialized.NameValueCollection'

Image
Good evening! I've tried casting the config object to NameValueCollection using .NET Framework 4.5.2 of Visual Studio 2015 which I read from a tutorial on how to read config files using type NameValueSectionHandler . However, as I use the code below to cast the ConfigurationSection object to NameValueCollection, C# Code Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); NameValueCollection scriptFiles = (NameValueCollection)config.GetSection( "scriptfiles" ); I get an error which is the title of this post. It seems that the code was applicable to older versions of .NET Framework and not the recent ones. After doing some research, I found out that the workaround is to use ConfigurationManager.GetSection() in which the parameter passed is the SectionName of the config object instead of directly casting the ConfigurationSection object returned by the config.GetSection() method. C# Code Configuration config = Configurati

Call Stored Procedures from Entity Framework 6 In C# (Part 2)

Hello, In this second part of the series on how to call stored procedures from Entity Framework 6, I will demonstrate on executing them using context.Database methods. To accomplish this, you need to perform steps 1 through 3 from this article Call Stored Procedures from Entity Framework 6 in C#. If you're done, the codes for the CRUD(Create, Update and Delete) functionalities are presented below. private static CustomerEntities ce = new CustomerEntities(); private static void InsertCustomer() { try { var result = ce.Database.ExecuteSqlCommand( "EXEC dbo.InsertCustomer @CompanyName,@ContactName,@Address,@Country,@Phone" , new SqlParameter( "CompanyName" , "TNT Bookstore" ), new SqlParameter( "ContactName" , "Mr T." ), new SqlParameter( "Address" , "Lincoln Village" ), new SqlParameter( "Country" , "UK" ), new SqlParameter( "Phone" , "42333&qu

Call Stored Procedures from Entity Framework 6 In C# (Part 1)

Image
Hello, Here's a tutorial on how to call stored procedures from Entity Framework 6.0 through the context object using the stored procedure name. In the second part of the series, I'll demonstrate how to call the stored procedures using methods like ExecuteSqlCommand() and SqlQuery() from context.Database class. To start with here are the steps to complete this example. Step 1 Add a Customers table in your database with fields. => CustomerID (int and identity set to true) => CompanyName(nvarchar) => ContactName(nvarchar) => Address(nvarchar) => Country(nvarchar) => Phone(nvarchar) Step 2 Create stored procedures that will perform insert, update, delete and get all records operations. Insert ALTER Procedure [dbo].[InsertCustomer]( @ CompanyName nvarchar( 40 ), @ ContactName nvarchar( 30 ), @ Address nvarchar( 60 ), @ Country nvarchar( 15 ), @ Phone nvarchar( 24 )) As Begin Insert Into dbo.Customers (CompanyName, ContactName, [Address

Pivot DataTable Using LINQ In C# And VB.NET

Hello, A question was brought up in the forums on how to Pivot a DataTable object here. The OP has already a solution with reference to this link Cross Tab / Pivot from Data Table . An alternative solution is to utilize the features of LINQ using group by statement to achieve the desired output. This solution consists of few lines of code compared with the solution from the forum post. C# Code var query = ( from students in dt.AsEnumerable() group students by students.Field< string >( "StudID" ) into g select new { StudID = g.Key, Eng = g.Where(c => c.Field< string >( "SubSht" ) == "Eng" ).Sum(c => c.Field< double >( "Score" )), Fre = g.Where(c => c.Field< string >( "SubSht" ) == "Fre" ).Sum(c => c.Field< double >( "Score" )), Mat = g.Where(c => c.Field< string >( "SubSht" ) == "Mat" ).Sum(c => c.Field< double &

Function <Anonymous Method> Doesn't Return A Value On All Code Paths (Action Statement)

Hello, Given the code statement below, the code throws an exception such as anonymous method does not return a value on all code paths. If txtEmployeeHireDate.IsHandleCreated Then If txtEmployeeHireDate.InvokeRequired Then BeginInvoke( New Action(Function() txtEmployeeHireDate.Text = objEmployee.HireDate End Function )) End If End If The code that's inside the BeginInvoke() statement does not necessarily returns a value since I only assigned an object's property value to the textbox control. In order to resolve this, either return a null value or a false value inside the Action delegate. If txtEmployeeHireDate.IsHandleCreated Then If txtEmployeeHireDate.InvokeRequired Then BeginInvoke( New Action(Function() txtEmployeeHireDate.Text = objEmployee.HireDate Return Nothing 'added this statement to fix issue End Function )) End If End If Another solution is to use Sub() which does not return a value instead of Function(

Load Images in a Windows Form Custom Control

Image
Good day! Often times when developing custom controls you will add images or icons to enhance the UI through the Bitmap class. But when getting the image from file using Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"\calendar.png") you may encounter issues such as "path is null" since the path pointed by the BaseDirectory isn't the executable path. A simple workaround is to set the path of the image using hardcoded like Image.FromFile(@"C:\Images\ProjectX\calendar.png") . While this is acceptable, it is ugly to look at and may cause potential issues once the image has been transferred to another location. An accepted solution is to add the image as a project resource then reference it in the custom control code. To accomplish that, here are the steps. * Right Click on the Project -> Properties * In Resources, select Add Resource Dropdown -> Add Existing File - Choose the image or icon to be used as resource. Once done, it wil

ASP.NET MVC CRUD(Create/Update/Delete) With Dapper ORM

Image
Hi All, Here's an ASP.NET MVC CRUD(Create/Update/Delete) project with Dapper ORM. The model classes and interface are based from this post Using Dapper ORM in ASP.NET Web Forms with few modifications in Customer class. The updates are adding Display attribute and DisplayFormat attribute to CreditLimit and IntroDate properties. using System; using System.ComponentModel.DataAnnotations; namespace ASPMVCDapper.Models { public class Customer { public int CustomerID { get ; set ; } [Display(Name="Company Name")] public string CompanyName { get ; set ; } [Display(Name = "Address")] public string Address { get ; set ; } [Display(Name = "City")] public string City { get ; set ; } [Display(Name = "State")] public string State { get ; set ; } [Display(Name = "Intro Date")] [DisplayFormat(DataFormatString = "{0:yyyy-MM

Unable to cast object of type 'DapperRow' to return Type

Aloha, Given the following code which generates an exception "Unable to cast object of type 'DapperRow", the cause for this is that the return type of FirstOrDefault() dynamic. public Customer FindById( int Id) { return this ._db.Query( "SELECT * FROM Customer WHERE CustomerID=@Id" , new { Id = Id }).FirstOrDefault(); } In order to solve this error, you have several options. One is to use Query.<TReturn>() instead of Query() wherein you can explicity specify the type. public Customer FindById(int Id) { return this._db.Query<Customer>( "SELECT * FROM Customer WHERE CustomerID=@Id" , new { Id = Id }).FirstOrDefault(); } Another option is to modify the code with issue, that is to store the result of the query in a dynamic variable and then assign the dynamic properties value to the class properties. public Customer FindById( int Id) { dynamic customerRecord = this ._db.Query( "SELECT * FROM Customer WHERE CustomerID=@Id&qu

Using Dapper ORM In ASP.NET Web Forms

Image
Hello, This is a simple tutorial of using Dapper Micro ORM in an ASP.NET Webform application. According to Wikipedia, Dapper is an object-relational mapping (ORM) product for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks. The key feature of Dapper is performance as presented in Dapper website (github). It is second to Hand coded SQLDataReader class when querying specific number of records. To get started with, create an Empty ASP.NET WebForm project and then add the Dapper to our project via NuGet. Make sure to alter the connection string in Web.Config to point to your database. Then we need to add one interface and three classes in our Models folder which applies the idea of Repository. Customer.cs public class Customer { public int CustomerID { get ; set ; } publ

Donate