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 :)

Thursday, September 9, 2010

Typed and Untyped Views

Hey Guys,
Howz  u doing ?
Now Lets Move Further...
In an ASP.NET MVC application, you pass data from a controller to a view by using view data and you have learnt about that in the last post of asp.net mvc..
you learned how to add items to the view data dictionary. There are two ways that you can use view data. First, you can use view data as an untyped dictionary. For example, the controller in Listing 1  returns a collection of products in its Index() action. And, the view in Listing 2 displays the collection by iterating through each item in the collection.
Listing 1 – Controllers\ProductController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
// Create list of products
var products = new List<Product>();
products.Add(new Product("Laptop computer", 344.78m));
products.Add(new Product("Bubble gum", 2.00m));
products.Add(new Product("Toothpaste", 6.99m));
// Add products to view data
ViewData["products"] = products;
// Return view
return View();
}
}
}

Listing 2 – Views\Product\Index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="MvcApplication1.Models" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var item in (List<Product>)ViewData["products"])
{ %>
<li> <%= item.Name %> </li>
<% } %>
</asp:Content>

The view in Listing 2 is an untyped view. Notice that the products item from view data must be cast to a collection of product items before you can do anything with it.
Instead of using an untyped view, you can use a strongly-typed view. The controller in Listing 3 also returns a collection of products. However, in this case, the collection is assigned to the ViewData.Model property.
Listing 3 – Controllers\Product2Controller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class Product2Controller : Controller
{
//
// GET: /Product2/
public ActionResult Index()
{
// Create list of products
var products = new List<Product>();
products.Add(new Product("Laptop computer", 344.78m));
products.Add(new Product("Bubble gum", 2.00m));
products.Add(new Product("Toothpaste", 6.99m));
// Add products to view data
ViewData.Model = products;
// Return view
return View();
}
}
}

Listing 4 – Views\Product2\Index.aspx


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var item in Model)
{ %>
<li> <%= item.Name %> </li>
<% } %>
</asp:Content>

In Listing 3, the products are assigned to the ViewData.Model property. As an alternative to explicitly assigning data to the ViewData.Model property, you can pass the data to the View() method. In other words, the following two code blocks are equivalent :

// Assign products to Model
ViewData.Model = products;
return View();
// Assign products to Model
return View(products);

The view in Listing 4 is a typed view. In Listing 4, the Model property represents the collection of products as a collection of products. In other words, you don’t need to cast the view data to a collection of product items before you use the Model property.
The advantage of assigning a value to the ViewData. Model property is that you can cast the Model property automatically in a view. In a view, you can specify the type of object that the Model represents with the <%@ Page %> directive Inherits attribute.
This Inherits attribute casts the ViewData. Model property to an IEnumerable of Product.For this reason, in the body of the view, you do not need to cast the ViewData. Model property before looping through its items.

Creating Strongly Typed Views

Providing the proper value for the Inherits attribute for a typed view can be tricky.Because you don’t get any Intellisense for the Inherits attribute, you can easily make amistake, and your view generates an error.
Instead of creating a strongly typed view by hand, you can take advantage of the Visual Studio Add View dialog to create a strongly typed view automatically (see below Figure). You open this dialog by right-clicking a controller action and selecting the menu option Add View. Alternatively, you can right-click a folder located in the Views folder and select the menu option Add, View.
The Add View dialog includes a check box labeled Create a Strongly Typed View. If you check this check box, you can specify the view data class and the view content.
Note : The View Data Class drop-down list will be empty until you successfully build your application. It is a good idea to select the menu option Build, Build Solution before openingthe Add View dialog.
The View Data Class drop-down list enables you to pick a class from your project. The Inherits directive uses this class. For example, you can pick the Product class.
The View Content drop-down list enables you to pick the type of view that you want to create. Your options are Create, Details, Edit, Empty, and List. If you pick List, your viewdata model is cast to an IEnumerable of Products. Otherwise, if you pick any of the other options, your view data model is cast to a Product.
So We are done with the Typed and untyped Views....You Got the concept ?
If you have any Queries , Let us know...we would try our best to clarify it..
Hope this helps..
Enhanced by Zemanta

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