Showing posts with label .NET. Show all posts
Showing posts with label .NET. Show all posts

Thursday, September 30, 2010

Google Search for .NET application

image

Today we are going to talk about building a software that search throgh google right from your desktop. There can be many application of such software like:

  • for making search engine for searching books in your ebook reader
  • for pdf reader you can give a search engine for direct download and reading purposes
  • for image download
  • for searching and downloading videos

Now let’s come to the point “HOW TO CODE”

well for making such application is very simple

you’ll need an API(Application platform installer) for fetching results from Google. here’s the link to get API

http://code.google.com/p/google-api-for-dotnet/downloads/detail?name=GoogleSearchAPI_0.3.1.zip&can=2&q=

The application needs framework 3.5

Now for searching make click event of search button as

private void button1_Click(object sender, EventArgs e)
    {
        flowLayoutPanel1.Focus();
        flowLayoutPanel1.Controls.Clear();
        web = new GwebSearchClient(referrer);           
        w_result= web.Search(textBox1.Text, 20, "en-us");
        flowLayoutPanel1.Height = this.Height - panel1.Height - panel2.Height-5;
        for (int i = 0; i < w_result.Count; i++)
        {
            Label lblR = new Label();
            lblR.Text = w_result[i].Title;
            lblR.Width = flowLayoutPanel1.Width;
            Label lblCon = new Label();
            lblCon.Width = flowLayoutPanel1.Width;
            lblCon.Text = w_result[i].Content;
            lblCon.Top = lblR.Top + 10;
            LinkLabel lnkUrl = new LinkLabel();
            lnkUrl.Text = w_result[i].Url;
            lnkUrl.Top=lblCon.Top+10;
            lnkUrl.Width=flowLayoutPanel1.Width;               
            flowLayoutPanel1.Controls.Add(lblR);
            flowLayoutPanel1.Controls.Add(lblCon);
            flowLayoutPanel1.Controls.Add(lnkUrl);
        }
    }

I have taken flowlayout control for binding results

web is object of class “Google.API.Search.GwebSearchClient” provided with the API.

as you can see this is object of GwebSearchclient so it fetches the web results. in the same fashion you can extract image results by using GimageSearchClient, book results with GbookSearchClient etc

that’s all for today’s tips.

Happy coding :)

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

Wednesday, August 25, 2010

Accessing Rss Feeds

RSS is a format for an XML document that describes a list of items, such as blog entries or news headlines. The document may just be a stream of XML created on the fly rather than a static file. In this post, we’ll tell you to put an RSS document (using Version 2.0) on a page by using the XmlDataSource and DataList controls.

Well what you need for this are as given below

  • URL to a valid rss file it could be .xml,.rss,.aspx.,.php etc
  • kind of schema of that rss file we call Xpath, to reach upto the content you are interested in.

A typical Rss file is like this.

A typical schema is like this

<rss>
<channel>
<item>
<title></title>
<description></description>
<link></link>
<pubDate></pubDate>
<!--...-->
</item>
</channel>
</rss>

XPath rss/channel/Item tell that this is Item from where you want to start fetching from.

Now i guess enough theoretical content has been described.

let’s start working.

Create a web site,

in default page or wherever you want to display the feeds put xmldatasource.

in navigationurl put the url of the rsss file. one example is (http://www.spaces.msn.com/members/mauliksoni/feed.rss). if you are choosing this Rss then put XPath=”rss/channel/item”.

take a data list and set its DataSourceID to the id of XmlDataSource you have taken.

in datalist set enableViewState to false.

Item template would be like this.

<ItemTemplate>
              Title:<%# XPath("title") %><br /><br />
              Description:<%# XPath("description")%>
              <hr />
           </ItemTemplate>

 

XPath(“Tiitle”) will print content of the Title tag and Xpath(“description”) will print content inside Description tag.

complete markup code is like this

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:XmlDataSource ID="XmlDataSource1" runat="server"
            DataFile="http://www.spaces.msn.com/members/mauliksoni/feed.rss"
            XPath="rss/channel/item"></asp:XmlDataSource>
        <asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1" EnableViewState="False">
            <ItemTemplate>
               Title:<%# XPath("title") %><br /><br />
               Description:<%# XPath("description")%>
               <hr />
            </ItemTemplate>
        </asp:DataList>
    </div>
    </form>
</body>
</html>

Run the project and see the feeds from your favorite site. Enjoy.

Tuesday, July 27, 2010

Chat Server and Chat Client

logo_300
Hi. Today we gonna show you how you can make your own chat application using TCP and UDP protocols.
This will be based on server client architecture. The basic work flow will be as given below
imageThe basic working of this model is as given below
  1. Client sent a message to server that contains two information,  Address of destination and the message to send.
  2. Client send this message to server on the port 8080 (shown here you can take any one which is available to use)
  3. Server looks for destination address and forward message to destination on port 8085(shown here you can take any one which is available to use).
  4. Destination which is another client get this message as it keep on listening to the port num 8085
So hope by now you have learnt the basic processing of the program. So here are the resources to be used

  • .Net Framework 2.0
  • Language c#
  • Development Platform Visual Studio 2008
So let’s start from Designing Windows.
SERVER:
  • Create a new project, name it Chat Server
  • Drop a ListBox into the Form created by Default.
  • Drop a Lable and set Text property to, Connected Member.
  • From the properties bar choose Form1( or whatever you named the first form)
  • Go to Event Double click on Load event.
  • This is How it should Look Like image

Now we can start the game “Coding”.
Using statements are as
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading;
Define Following Variables as Class variables ie out side any function.
delegate void connect(object obj); /* This is delegate for adding connection to our List Box*/ UdpClient up_send = new UdpClient(1024);/* this is our Udp Client For sending Texts string word; bool showcon = true;/* this bool variable to show whether Connection is needed*/ static int recieveport; /* this is the Port number of Client which is sending message*/ string msg = "";/* this is the receive message from Client*/ int senderport; /* this is port num of client which will receive message*/
recieveport and senderport is not as such required, this will become necessary when you will make two client for the same pc mean for testing the project on your pc only not on LAN.
In the Constructor add following Codes
InitializeComponent();// this method will initialize all controls used Thread serverthread = new Thread(new ThreadStart(server)); /* this is our server thread which will keep on running continuously*/ serverthread.Start();  //Here we started our server thread
Server thread is an Object of a thread that takes a method “server” as a parameter of Threadstart, When this thread will start running the method “server” will start executing
here’s the methode “Server”( make sure the return type of parameter of thread it should be void only)
private void server() { UdpClient up_recieve = new UdpClient(8080);/* this is udp client for Listening to client’s message*/ while (true)/* an infinite while loop for keep on checking for new message*/ { IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0);/* this will give u the connection which is established*? byte[] recievebyte = up_recieve.Receive(ref remoteipendpoint);/* here' we re getting the message in Bytes*/ word = Encoding.ASCII.GetString(recievebyte);/* here we converted our message into string, ready to send to destination client*/ recieveport =Convert.ToInt32(word.Substring(0,4));/* here we get  the port number of destination Client, This is for only if you are testing two client on the same pc, you can send Ip address and port number of client instead of just port number*/ if (lstbxMsg.InvokeRequired&& showcon)/* here we are checking whether current thread can access list box or not. it won’t as lstBox is not defined under scope of this thread*/ { connect con = new connect(connectmem);/* here we made an object of our delegate*/ lstbxMsg.BeginInvoke(con, remoteipendpoint);/*connectmem method will be able to access llistbox as we have given object of delegate of this method as a object of begine invoke method*/ showcon=false;/* we made the connection so make it false*/ } if(!string.IsNullOrEmpty(word))/* checking whether the received message is empty*/ { Thread thrdsend = new Thread(new ThreadStart(send)); thrdsend.Start();/* if not then this thread will send the message*/ } } }
Here’s the method to insert connected member into List Box
void connectmem(object obj) { IPEndPoint remote = (IPEndPoint)obj; lstbxMsg.Items.Add(remote.ToString()+" Connected"); }
Here’s our Send method
private void send() { byte[] sendbyte = Encoding.ASCII.GetBytes(word); up_send.Connect("localhost", recieveport); up_send.Send(sendbyte, sendbyte.Length); }
In first line we taken the message as Byte which will be sent to another client.
In second line we made connection to another client. In our case we have run server and two client on the same pc hence instead of giving any IP address we have taken “localhost”. If you are testing it on LAN then you will have to send message from Client that include destination’s IP address and use the IP address to connect from this statement.
In Third statement we are sending message using the UDP client defined as class variable.
So by now we are Completed with our server that is able to send and receive texts.
Now we will create Our Chat Client. I’ll explain you you file sharing Module of this project in later Blog.
Client:
Let’s start With designing.
  • Create a New Project name it Chat Client
  • Drag and drop a list box, a textbox and a Button into form
  • This should Look Like
Chat Client
Let start game again “Coding”
Using statements are as
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading;
Define following as Server variables
UdpClient up = new UdpClient(8582); delegate void connect(object obj); Thread thrd;
up is our UDP Client for sending data, hence we will send data from port number 8582
The form Load event should be like this
private void Form1_Load(object sender, EventArgs e) { thrd = new Thread(new ThreadStart(recieve)); thrd.Start(); }
Here we started our thread for receiving message. this thread will be like receiving thread of server.
Here’s our Receive method
void recieve() { UdpClient up = new UdpClient(8085); while (true) { IPEndPoint remoteipendpoint = new IPEndPoint(IPAddress.Any, 0); byte[] recievebyte = up.Receive(ref remoteipendpoint); string word = Encoding.ASCII.GetString(recievebyte); if (lstbxMsg.InvokeRequired) { connect con = new connect(connectmem); lstbxMsg.BeginInvoke(con,remoteipendpoint.ToString()+" "+word); } } }
this method is exactly same as the one of server. remoteipendpoint is IP address of the pc from where the message is coming from. In our Case server.
In server we were inserting connected member into listBox, here will add message.
for adding message the method is as given below
void connectmem(object obj) { lstbxMsg.Items.Add(obj.ToString()); }
This is quite understandable
On click event of Button we will send our message to server
the click event will be like this
private void btnSend_Click(object sender, EventArgs e) { byte[] sendbyte = Encoding.ASCII.GetBytes("8086"+textBox1.Text); up.Connect("localhost", 8080); up.Send(sendbyte, sendbyte.Length); lstbxMsg.Items.Add(textBox1.Text); textBox1.Text = ""; }
This quite same as the sending method of server
1st converting message to byte and connecting to server(in server we were connecting to client) and then sending the message and adding that message to list box as well so that the user will be able to see his/ her own message. the thing to notice here is that we are adding 8086 port number here, You should add IP address of the client to whom user is going to send the message (if you are using LAN).
Here we are completed our Chat client and chat Server.
Isn’t it easy????
Hope you liked it. In next post we will describe File Sharing using TCP.

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.