Showing posts with label Xml. Show all posts
Showing posts with label Xml. Show all posts

Wednesday, September 8, 2010

MDF TO XML Converter

In now a days for data processing one need to use XML instead of any other relational data source.Because the targeted customer may not have relational compatible software. And if they include needful files then the package becomes heavy so its better to use xml file.The presented software solves this problem.

here’s the look of the software that we are going to design

image

The working is very simple. Following are the steps for processing

  • Building Connectionstring of choosen database
  • Extracting table names of the database
  • Generating XML file of the tables data with the same schema

Connection String:

A typical connection string consist of following values

  • Server’s name
  • Database’s name
  • Username and Password (in case of SQL authentication)

All the values has been taken using UI then the user will be required to press a button to extract all the table names inside chosen Database.

The click event of that button is like this

private void btnTables_Click(object sender, EventArgs e)
     {
         string con = "Data Source=";
         con = con + txtServerName.Text + ";";
         con = con + "Initial Catalog=" + txtDbName.Text + ";";

         if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
         {
             con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
         }
         else
         {
             con = con + "Integrated Security=True;User Instance=True;";
         }
         SqlConnection connect = new SqlConnection(con);
         try
         {
             connect.Open();
             string cmd = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME";
             SqlDataReader dst = SqlHelper.ExecuteReader(connect, CommandType.Text, cmd);
             comboBox1.Text = "Select Table";
             while (dst.Read())
             {
                 comboBox1.Items.Add(dst["TABLE_NAME"].ToString());
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }

     }

con is our connection string.

in the try block we have given code for extracting tables name.

the querry for extracting all the table names is

“SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME”

SqlHelper is a class which is available on internet, it increases the speed of processing.

If you don’t want to do this then you can implement it using the very conventional way that’s by creating SQLConnction and SQlcommand. here’s the code for that

private void btnTables_Click(object sender, EventArgs e)
     {
         string con = "Data Source=";
         con = con + txtServerName.Text + ";";
         con = con + "Initial Catalog=" + txtDbName.Text + ";";

         if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
         {
             con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
         }
         else
         {
             con = con + "Integrated Security=True;User Instance=True;";
         }
         SqlConnection connect = new SqlConnection(con);
         try
         {
             string cmd = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME";            

             SqlCommand Scmd = new SqlCommand(cmd, connect);

             connect.Open();

             SqlDataReader dst = Scmd.ExecuteReader();
             comboBox1.Text = "Select Table";
             while (dst.Read())
             {
                 comboBox1.Items.Add(dst["TABLE_NAME"].ToString());
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }

     }

 

So by now we are done with extracting Tables name.

now user will choose the table, and the path where he want XML file to be saved.

here’s click event of the button for generating XML file

private void btnConvert_Click(object sender, EventArgs e)
        {
            string con = "Data Source=";
            con = con + txtServerName.Text+";";
            con = con + "Initial Catalog=" + txtDbName.Text + ";";

            if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
            {
                con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
            }
            else
            {
                con = con + "Integrated Security=True;User Instance=True;";
            }
            SqlConnection connect = new SqlConnection(con);
            try
            {
                string filename;
                connect.Open();           

                string strcmd = "Select * from " + comboBox1.Text;
                DataSet dst = SqlHelper.ExecuteDataset(connect, CommandType.Text, strcmd);
                if(string.IsNullOrEmpty(txtLocation.Text))
                {
                    filename= "Xml_"+comboBox1.Text+".xml";
                }
                else
                {
                    filename = txtLocation.Text + "Xml_" + comboBox1.Text + ".xml";
                }
                FileStream stream = new FileStream(filename,FileMode.Create);
                dst.WriteXml(stream);
                connect.Close();
                MessageBox.Show("File Created");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

Here we again built our Connection string and executed command for extracting all the data from chosen table.

we have taken that data as dataset.

We took a filestream to write xml file.

then we wrote the file using

dst.WriteXml(stream);

dst is object of our dataset after creating file close connection to databse and prompt for creation of file.

We have generated Xml file in the same way you can generate Binary File too. for that be with us and wait for next post.

Thank you.

Happy Coding.

P.S: Yu may download the project from here

Tuesday, July 27, 2010

Sample XML Project

,logo_300
Hello readers.
This is our first post that matches our intention.
Here i'm describing you all how to
  • use an XML file in our project.
  • Why we should use XML file.
  • Any better option.
I'm taking an example of a browser that extract categorized link from an XML files. All link are taken from My friend's Blog (SAM's BLOG)
So here we go.
The framework used is .NET Framework 2.0 Language used is c#
This is how it gonna look like.
[caption id="attachment_14" align="aligncenter" width="300" caption="A link Collection with browser"]Sam's link collection[/caption]
So Let's start from designing. Follow the steps
  1. Open Visual studio or Visual c# express edition whatever you use for development purpose.
  2. Create a new project by going file->new-> create project
  3. Choose language c# and windows application as project.
  4. It'll open a tab with a blank windows form Now go to toolbox and drop following items into your window form web browser, two combo box, button, menustrip,progressbar.
  5. To use our code the names of various controls must be same.. Name them as follows
  6. WebBrowser-webBrowser1
  7. Longer combobox used for link selection-cmbLink
  8. Smaller Combobox used for Catagoy Collection-cmbCatagory
  9. Button-btnGo.
  10. progressbar-progressBar1
  11. IN menu strip make following menus, Go HOme, Forward, Backward
  12. You can assign shortcut keys for them (i haven't )
  13. In text Propert of Button Write Go.
So enough Designing Let's start some Coding now.
double click any where in form but outside any control.
you should be redirected to a .cs page and inside the funtion
private void Form1_Load(object sender, EventArgs e)
{
}
This is an event which get triggered when the form start loading.
This way you actually create a class named Form1 you can see a constructor of this class  Form1() in the same .cs page.
Now let's start adding code
following code you can add in both Constructor(but after function call initalizeComponent() ), or in the Load event of the form.
string strpathxml = "xmltest.xml"; // this is a path o our XML file
DataSet ds = new DataSet();/* we have Taken a Dataset object to store information that we are going to extract from XML doc.*/'
//You can read more about Data Set by clicking here
ds.ReadXml(strpathxml); /* here we read the xml file*/
string home = "http://sanketdhingra.blogspot.com/"; /* this is the link to sam's blog. I have made this Home page of this project*/
XmlDataDocument xmldatadoc = new XmlDataDocument(ds);  /* here we have taken object of XmlDataDocument it allows structured data to be stored, retrived and manipulated through Dataset*/
XmlNode[] nodeno = new XmlNode[19]; /* this is object of  XmlNode that actually contains 19 nodes these are for the categories of our links*/
for (int i = 0; i < 19; i++)
{
string pathquerry = "/NewDataSet/Browser[Id=" + (i + 1).ToString() + "]";/* this is the query that will give us the categories from XmlDataDocument.*/
nodeno[i] = xmldatadoc.SelectSingleNode(pathquerry);/* here we are getting Categories in our XmlNode Object*/
cmbCatagory.Items.Add(nodeno[i].ChildNodes[1].InnerText.ToString()); /* Here i'm inserting catagories in my ComboBox of category ie in cmbCatagory.*/
}
ds.WriteXml(strpathxml, XmlWriteMode.WriteSchema);/* this actually writes the schema of xml in my xml file*/
webBrowser1.Navigate(new Uri(home));/* now we are navigating to the home page which is Sam's Blog.*/
This event get triggered when we select any index from combo box in our case any catagory.
So by now we just loaded our window which opens a webpage and load a combobox with cataories of link.
Now what we have to do is to when i choose any category from cmbCatagory corresponding links should be filled into cmbLink( combobox of links). for this do following
  1. click on cmbCatagory for selecting it and go to properties bar there are option for proerty or even go to event and double click on the event selected index changed.
  2. You'll be redirected to .cs page with function  private void cmbCatagory_SelectedIndexChanged(object sender, EventArgs e){}
  3. add following codes
int id = cmbCatagory.SelectedIndex;/* int that tells which catagory number is seleted (it is on the '0' base)*/
cmbLink.Text = "Seelect a link";/*We are adding text in our combox of link "Select a link"*/
string strpathxml = "xmltest.xml";/*path to our Xml Doc*/
DataSet ds = new DataSet();/* taking dataset as before*/
ds.ReadXml(strpathxml);/*reading xml file*/
XmlDataDocument xmldatadoc = new XmlDataDocument(ds);
XmlNode xnd;
string querry = "/NewDataSet/Link[Linkid=" + (id+1).ToString() + "]";/* this is query to select links against selected category*/
xnd = xmldatadoc.SelectSingleNode(querry);/*filling our Xml Node*/
int lnkid = Convert.ToInt32(xnd.ChildNodes[2].InnerText.ToString());/* here we get an Id from where the link o selected category starts*/
string querry1 = "/NewDataSet/Link[Linkid=" + (id+2).ToString() + "]";
xnd = xmldatadoc.SelectSingleNode(querry1);
int temp = Convert.ToInt32(xnd.ChildNodes[2].InnerText.ToString());/* here we get where links to next category starts*/
XmlNode[] nodeno = new XmlNode[80];//*here i'm taking aray of xmlnode of size 80, it is just because in future i'll be able to extend links, you can                                                                                                             choose list too that'll be dynamic but as a basic application i have chosen this*/
for (int i = 0; i < 81; i++) /* in this loop i'm clearing all the items that are currently inside cmbLink. ie cleaning our link combobox*/
{
try
{
cmbLink.Items.RemoveAt(i);
--i;
}
catch(Exception x){}
}
for (int i = lnkid; i < temp; i++)/* here i'm filling my Combobox with Links*/
{
querry = "/NewDataSet/Link[id=" + i.ToString()+"]";
nodeno[i] = xmldatadoc.SelectSingleNode(querry);
if (nodeno[i]!=null)
{
cmbLink.Items.Add(nodeno[i].ChildNodes[0].InnerText.ToString());
}
}
So by now we are done with inserting specific links that matches the categories. The project is almost complete We are just left with some finishing.
  • go to form1 design view select web browser
  • go to property bar
  • events
  • double click on event named document completed and progress changed.
  • add following code
  • in DocumntCompleted event add following codes
cmbLink.Text = webBrowser1.Url.ToString(); /* writing link of the current web page into link combobox*/
progressBar1.Visible = false;/* setting visibility of progres bar to fales*/
  • in progresschanged event add following codes
progressBar1.Visible = true;/*setting visibilty of progressbar to true to show the progress*/
progressBar1.Maximum = Convert.ToInt32(e.MaximumProgress);//*these are progress bar parameters*/
progressBar1.Value = Convert.ToInt32(e.CurrentProgress);
Now we are left with coding of various buttons
Double click on go button, You'll be redirected to a function which is a click event of Button
add following codes
string link = cmbLink.Text.ToString();
int q = link.Length;
string temp = link.Remove(7, q - 7);
if (temp != "http://" && temp != "Http://" && temp != "Http:///" && temp != "http:///")
{
link = "http://" + link;
webBrowser1.Navigate(new Uri(link));
}
else
{
webBrowser1.Navigate(new Uri(link));
}
This is the for browsing to the link which is inside cmbLink
Double click on menustrip Home add following codes in its click event
string home = "http://sanketdhingra.blogspot.com/";
webBrowser1.Navigate(new Uri(home));
Double click on menustrip Forward add following codes in its click event
webBrowser1.GoForward();
Double click on menustrip Backward add following codes in its click event
webBrowser1.GoBack();
Namespace used are (using statemens)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
So here we are done with our project. press f5, If you are did exactly as written here you will not get any kind of error and your project will run easily.
This project you can refer s to get start with .Net windows programming. Hope u liked it.
thanks keep browsing for more.
If  this is useful then please subscribe. Your suggestions and questions are respectfully invited.
Thank You
Hope to see you soon.