Thursday, 21 May 2015

Import MS Excel data to SQL Server table using C#

If you already have data in MS Excel file, and want to migrate your MS Excel data to SQL Server table, follow the below steps:

Step 1: Let’s take an example to import data to SQL Server table. I am going to import student information data from an MS Excel sheet to the tStudent SQL table:

Step 2: Now design a tStudent table in SQL Server

CREATE TABLE
(
STUDENT VARCHAR(64),
ROLLNO VARCHAR(16),
COURSE VARCHAR(32),
)
Your MS Excel sheet and SQL table are ready, now it’s time to write C# code to import the Excel sheet into the tStudent table.

Step 3: Add these two namespaces in your class file:
USING SYSTEM.DATA.OLEDB;
USING SYSTEM.DATA.SQLCLIENT;
 
Step 4: Add below method in your class file, you can call this method from any other class and pass the Excel file path:
public void importdatafromexcel(string excelfilepath)
{
    //declare variables - edit these based on your particular situation
    string ssqltable = "tdatamigrationtable";
    // make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have
    different
    string myexceldataquery = "select student,rollno,course from [sheet1$]";
    try
    {
        //create our connection strings
        string sexcelconnectionstring = @"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath +
        ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
        string ssqlconnectionstring = "server=mydatabaseservername;user
        id=dbuserid;password=dbuserpassword;database=databasename;connection reset=false";
        //execute a query to erase any previous data from our destination table
        string sclearsql = "delete from " + ssqltable;
        sqlconnection sqlconn = new sqlconnection(ssqlconnectionstring);
        sqlcommand sqlcmd = new sqlcommand(sclearsql, sqlconn);
        sqlconn.open();
        sqlcmd.executenonquery();
        sqlconn.close();
        //series of commands to bulk copy data from the excel file into our sql table
        oledbconnection oledbconn = new oledbconnection(sexcelconnectionstring);
        oledbcommand oledbcmd = new oledbcommand(myexceldataquery, oledbconn);
        oledbconn.open();
        oledbdatareader dr = oledbcmd.executereader();
        sqlbulkcopy bulkcopy = new sqlbulkcopy(ssqlconnectionstring);
        bulkcopy.destinationtablename = ssqltable;
        while (dr.read())
        {
            bulkcopy.writetoserver(dr);
        }
     
        oledbconn.close();
    }
    catch (exception ex)
    {
        //handle exception
    }
}
 
In the above function you have to pass the MS Excel file path as a parameter. If you want to import your data by providing the client access to select the Excel file and import, then you might have to use the ASP.NET File control and upload the Excel file on the server in some temp folder, then use the file path of the uploaded Excel file and pass the path in the above function. Once data import is complete then you can delete the temporary file.
The above method first deletes the existing data from the destination table, then imports the Excel data into the same table.

Wednesday, 20 May 2015

Console application using C# to Convert Excel file data into xml file with adding own tag element like attributes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web;
using System.Data;
using System.Xml;


namespace ConvertExceltoXMLConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            string Exfilepath = @"D:\Verification.xlsx";
            DataTable dt = new DataTable();
            DataRow dr = null;
            string fetch = null;
            System.Data.OleDb.OleDbConnection MyConnection = null;
            System.Data.DataSet DtSet = null;
            System.Data.OleDb.OleDbDataAdapter MyCommand = null;
            // MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + Exfilepath + "';Extended Properties=Excel 8.0;");

            //If you MS Excel 2007 then use below lin instead of above line
            MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Exfilepath + "';Extended Properties=Excel 12.0;");

            MyCommand = new System.Data.OleDb.OleDbDataAdapter("select ApplicantFirstName,VoterId,ExternalApplicationId,DateOfBirth,Gender,Address1Line from [VoterID$]", MyConnection);
            DtSet = new System.Data.DataSet();
            MyCommand.Fill(DtSet, "[VoterID$]");


            XmlDocument xmlDoc = new XmlDocument();
            XmlNode docNode = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(docNode);
            XmlNode rootNode = xmlDoc.CreateElement("DCRequest");
            XmlAttribute attribute1 = xmlDoc.CreateAttribute("xmlns");
          
            attribute1.Value = "http://swapnilmahangare.blogspot.in";
            rootNode.Attributes.Append(attribute1);
            xmlDoc.AppendChild(rootNode);

            XmlNode AuthenticationNode = xmlDoc.CreateElement("Authentication");
            XmlAttribute AuthenticationAttribute = xmlDoc.CreateAttribute("type");
            AuthenticationAttribute.Value = "OnDemand";
            AuthenticationNode.Attributes.Append(AuthenticationAttribute);
            rootNode.AppendChild(AuthenticationNode);

            XmlNode UserIdNode = xmlDoc.CreateElement("UserId");
            UserIdNode.AppendChild(xmlDoc.CreateTextNode("swapnil"));
            AuthenticationNode.AppendChild(UserIdNode);
            XmlNode PasswordNode = xmlDoc.CreateElement("Password");
            PasswordNode.AppendChild(xmlDoc.CreateTextNode("*******"));
            AuthenticationNode.AppendChild(PasswordNode);

            XmlNode RequestInfoNode = xmlDoc.CreateElement("RequestInfo");
            rootNode.AppendChild(RequestInfoNode);

            XmlNode SolutionSetNode = xmlDoc.CreateElement("SolutionSetId");
            SolutionSetNode.AppendChild(xmlDoc.CreateTextNode("665"));
            RequestInfoNode.AppendChild(SolutionSetNode);
            XmlNode SolutionSetVersionNode = xmlDoc.CreateElement("SolutionSetVersion");
            SolutionSetVersionNode.AppendChild(xmlDoc.CreateTextNode("V2"));
            RequestInfoNode.AppendChild(SolutionSetVersionNode);
            XmlNode ExecutionNode = xmlDoc.CreateElement("ExecutionMode");
            ExecutionNode.AppendChild(xmlDoc.CreateTextNode("NewWithContext"));
            RequestInfoNode.AppendChild(ExecutionNode);


            DataTable dt1 = DtSet.Tables[0];
            for (int i = 0; i < dt1.Rows.Count; i++)
            {

                if (!string.IsNullOrWhiteSpace(dt1.Rows[i][1].ToString()))
                {
                    XmlNode FieldsNode = xmlDoc.CreateElement("Fields");
                    rootNode.AppendChild(FieldsNode);
                    XmlNode userNode = xmlDoc.CreateElement("Field");
                    XmlAttribute attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "ApplicantFirstName";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][0].ToString();
                    FieldsNode.AppendChild(userNode);

                    userNode = xmlDoc.CreateElement("Field");
                    attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "VoterId";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][1].ToString();
                    FieldsNode.AppendChild(userNode);


                    userNode = xmlDoc.CreateElement("Field");
                    attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "ExternalApplicationId";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][2].ToString();
                    FieldsNode.AppendChild(userNode);

                    userNode = xmlDoc.CreateElement("Field");
                    attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "DateOfBirth";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][3].ToString();
                    FieldsNode.AppendChild(userNode);

                    userNode = xmlDoc.CreateElement("Field");
                    attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "Gender";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][4].ToString();
                    FieldsNode.AppendChild(userNode);

                    userNode = xmlDoc.CreateElement("Field");
                    attribute = xmlDoc.CreateAttribute("Key");
                    attribute.Value = "Address1Line";
                    userNode.Attributes.Append(attribute);
                    userNode.InnerText = dt1.Rows[i][5].ToString();
                    FieldsNode.AppendChild(userNode);
                }
            }

            xmlDoc.Save("D:\\Verification.xml");

     
        }
    }
}



Output:-

 <?xml version="1.0" encoding="UTF-8" ?>
 <DCRequest xmlns="http://swapnilmahangare.blogspot.in">
 <Authentication type="OnDemand">
  <UserId>swapnil</UserId>
  <Password>*******</Password>
  </Authentication>
 <RequestInfo>
  <SolutionSetId>33</SolutionSetId>
  <SolutionSetVersion>rr</SolutionSetVersion>
  <ExecutionMode>NewWithContext</ExecutionMode>
  </RequestInfo>
 <Fields>
  <Field Key="ApplicantFirstName">REJITHA M</Field>
  <Field Key="VoterId">232323</Field>
  <Field Key="ExternalApplicationId">2323</Field>
  <Field Key="DateOfBirth">08.10.1991</Field>
  <Field Key="Gender">FEMALE</Field>
  <Field Key="Address1Line">rrrrrrr</Field>
  </Fields>
 <Fields>
  <Field Key="ApplicantFirstName">RAKESH T</Field>
  <Field Key="VoterId">343434</Field>
  <Field Key="ExternalApplicationId">55555</Field>
  <Field Key="DateOfBirth">04.07.1991</Field>
  <Field Key="Gender">MALE</Field>
  <Field Key="Address1Line">gggggg</Field>
  </Fields>
</DCRequest>

Monday, 18 May 2015

Could not find default endpoint element that references contract ‘Your Service’ in the ServiceModel client configuration section.

When I consume the WCF in a class library project by adding the  service reference , I got the following  exception message :
Your search - Could not find default endpoint element that references contract 'yourService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. - did not match any documents.

In order to solve this , you will need copy the System.ServiceModel section of the generated app.config file to the executing assembly project’s .config file (web.config for web application project, app.config for windows or console project) . Then it run like a charm. This is because the app.config file in the class library project  is not used by the WCF ,instead the executing assembly project’s .config file will be used.