Responsive Ads Here
Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Friday, March 30, 2018

Exporting data from SQL Server to CSV file in ASP.Net using C# 

Namespaces

You will need to import the following namespaces.


  • using System.Data;
  • using System.Configuration;
  • using System.Data.SqlClient;

Code For Export DataTable to CSV


protected void ExportCSV(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    //Build the CSV file data as a Comma separated string.
                    string csv = string.Empty;
                    foreach (DataColumn column in dt.Columns)
                    {
                        //Add the Header row for CSV file.
                        csv += column.ColumnName + ',';
                    }
                    //Add new line.
                    csv += "\r\n";
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn column in dt.Columns)
                        {
                            //Add the Data rows.
                            csv += row[column.ColumnName].ToString().Replace(","";") + ',';
                        }
                        //Add new line.
                        csv += "\r\n";
                    }
                    //Download the CSV file.
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition""attachment;filename=SqlExport.csv");
                    Response.Charset = "";
                    Response.ContentType = "application/text";
                    Response.Output.Write(csv);
                    Response.Flush();
                    Response.End();
                }
            }
        }
    }
}

Saturday, November 18, 2017

Hi friends, today I will explain how to create and configure a linked server to retrieve data from an Azure SQL database.


Few points are describe in this article for configure link server with SSMS

  1. How to configure link server step by step in SSMS
  2. Solve some common Problem/Issue  when create link server
  3. Using the Query/Script base to create link server
How to configure link server step by step in SSMS

        To create link server via SSMS, go to Object Explorer under the Server Objects folder, right click on the Linked Servers folder and from the context menu choose the New Linked Server Command:

Fig 1.1

The New Lined Server window will be opened:

Fig 1.1

Put your Linked Server Name, then
Select data source: Microsoft OLE DB Provider for SQL Server
Then click on security tab on left side

Under the Security tab, select the Be made using this security context radio button and enter user credentials this exist on Azure server
Fig 1.2

Under the Security tab, use the same setting that we used in the previous example and press the OK button.
This will create a linked server to an Azure SQL Database(Azure Database). And when the plus(+) sign next to the table folder is pressed, the Tables folder will expand and show all tables for the selected Azure database:

Fig 1.3
To retrieve data from the SQL Azure table (e.g [dbo].[Actions]), type the following code:
SELECT Top 10 * FROM [LinkedServerName].[AzureDataBaseName].[dbo].[TableName]
      

Solve some common Problem/Issue  when create link server

When we create linked server we facing some common issue like Linked server is showing created but we can’t able to access the linked database. It’s given error which is mention below image:

Fig 2.1


Above mention error, Fail to retrive data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

          ADDITIONAL INFORMATION:
                         An exception occurred while executing a Transact-SQL statement or batch.  (Microsoft SQL Server, Error: 40515)

Using the Query/Script base to create link server

How to create linked server for SQL Database on Azure from local SQL Server
Step by step Azure SQL Database Linked Server
Step 1: Go to SQL Server Management Studio
Step 2: Run the below scripts. This script using a stored procedure "SP_addlinkedserver".
EXEC sp_addlinkedserver
@server='Azure', -–Provide Linked Server Name
@srvproduct='',    
@provider='sqlncli',
@datasrc='AzureDataServerName', -–provide Azure SQl Server name
@location='',
@provstr='',
@catalog='AzureDatabaseName' -–Provide azure database name

Step 3: Run the below script to provide the SQL Server login for the above created linked server.
Exec sp_addlinkedsrvlogin 'Azure', 'FALSE', NULL, '[azure sql server login]', '[sql server password]';
Step 4: Verify the created linked server, under the Databases -> Server Objects -> Linked Servers -> Your Linked Server Name

Step 5: Access the azure SQL database table. You need to use 4 part query. [linked server name].[database name].[schema name].[table name]

SELECT Top 10 * 
FROM [linked server name].[database name].[schema name].[table name]

Friday, October 6, 2017

Data Table to XML Genrate


 ///





      /// Write out XML to a DataTable to a file in a controlled manner.
      /// Use a XmlWriterSettings to control the output formatting.
      ///
      public static string DataTableToXML(DataTable table)
      {
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.CheckCharacters = true;
         settings.CloseOutput = true;
         settings.ConformanceLevel = ConformanceLevel.Document;
         settings.Encoding = Encoding.UTF8;
         settings.Indent = false;
         settings.NewLineHandling = NewLineHandling.Replace;
         settings.NewLineOnAttributes = true;
         settings.OmitXmlDeclaration = true;

         using (var sw = new StringWriter())
         {
            using (var writer = XmlWriter.Create(sw))
            {
               // Build Xml with xw.
               writer.WriteStartDocument(true);
               WriteTable(writer, table);
               writer.WriteEndDocument();
            }
            return sw.ToString();
         }
      }

      private static void WriteTable(XmlWriter writer, DataTable table)
      {
         //     
         writer.WriteStartElement("DocumentElement");

         foreach (DataRow row in table.Rows)
         {
            //

            writer.WriteStartElement(table.TableName);

            foreach (DataColumn column in table.Columns)
            {
               writer.WriteStartElement(column.ColumnName);
               writer.WriteValue(row[column].ToString());
               writer.WriteEndElement();
            }
            //
            writer.WriteEndElement();

         }

         //
             writer.WriteEndElement();
      }

Tuesday, September 26, 2017

XML Helper for convert class object/List to xml and xml to class object/List conversion


Hi friend's, today we are going to understand ubout XMl Helper for convert class object/List to xml and xml to class object/List convertion.

let's start with example,

Create class for EmployeeDetail


public class EmployeeDetails
    {
        [XmlAttribute]
        public int EmployeeID { get; set; }
        [XmlAttribute]
        public string EmployeeName { get; set; }
        [XmlAttribute]
        public string EmailID { get; set; }
        [XmlAttribute]
        public List lstEmployeeDetails { get; set; }
    }
Now, we have one class XMLHandler that contains two methods that make our work easy and clean.
  • Method ConvertToXML for Generic code to convert Xml to class object or list.
  • Method Convert for Generic code to convert class object or list to Xml.
public static class XMLHandler
    {
        public static T Convert(string inputString)
        {
              XmlSerializer serializer = new XmlSerializer(typeof(T), string.Empty);
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString));
              T resultingMessage = (T)(serializer.Deserialize(memStream));
              return resultingMessage;
        }
        public static string ConvertToXML(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringWriter sww = new StringWriter();
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                serializer.Serialize(writer, obj);
                return sww.ToString().Replace("", "").Replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", ""); // Your XML
            }
        }
    }

To convert List to xml:
Now we will create instance for EmployeeDetails
EmployeeDetails objEmployeeDetails = new EmployeeDetails();
string xml = XMLHandler>.ConvertToXML(objEmployeeDetails. lstEmployeeDetails);
It will return xml as below Figure,



So, that's all guys i hope these will help you to create xml using object/class.
please share this blog if this helpful you. https://dotnetupdatedtechnology.blogspot.com/

{ "@context": "http://schema.org", "@type": "Organization", "url": "http://c-sharpnets.blogspot.com/", "logo": "http://c-sharpnets.blogspot.com/images/logo.png" }