Serving Information Simply

Sunday 4 November 2012

Basic information about C sharp -Dot Net



Some of the questions that always need to know a c# learner before going for the programming in C#. So from today I will write only about c# basics and ahead I will try to bring good articles for the beginners so keep visiting...
let’s start now ......

1. What is .NET?
   It is a platform or technology from Microsoft based on .NET Framework
2. How languages differ from technology?
   In a language things get created from scratch while in a technology things are already available but need to assembled.
What is a framework?
-          A software that provides a set of libraries, a set of tools and some rules
-          Examples
o   MVC (Model-View-Controller) framework
o   Struts
o   Hibernate
o   spring
o   .NET Framework
o   Mono Framework
What are different frameworks for .NET Technology?
-          There are two frameworks available for .NET technology
o   .NET Framework from Microsoft
§  Proprietary
§  Works with Windows Only
§  Supports all possible language under .NET
o   Mono Framework from Novell
§  Open Source
§  Works with all operating systems
§  Supports few languages like C# and Ruby
Is C# Platform Independent?
-          No
-          Since Mono which runs C# on all platform is not from Microsoft
Why .NET?
-         Actually .Net provide cross-Language interoperability among many languages of choice
o   C#
o   VB
o   J#
o   C++
o   F#
o   Pythen.NET
o   Ruby.NET
o   Pascal.NET
o   COBOL.Net
o   Etc.
-          All languages get compiled into a common format called as MSIL (Microsoft Intermediate Language)
-          Only on software is enough to run application written in any .NET based language called as CLR (Common Language Runtime)
-          To make the interoperable programs they must follow CLS (Common Language Specifications) compliancy rules
-          All language share the common libraries and tools provided by special software called .NET Framework
o   .NET Framework software provides different versions of libraries
§  1.0
§  1.1
§  2.0
§  3.0
§  3.5
§  4.0
-          All languages share the Common Type System (CTS). It is set of classes and structures that get mapped by different language based on their size
o   System.Byte
o   System.Int16
o   System.Int32 à C# (int), VB (Integer)
o   System.Int64
o   System.Single à C# (float), VB(Single)
o   System.Double
o   System.Boolean
o   System.String
o   System.Object
-          Single IDE called Visual Studio for any kind of development using any language of choice
o   Versions of Visual Studio
§  2001
§  2003
§  2005
§  2008
§  2010
-          Any kind of development using language of choice
o   Console Application
o   Window Based
o   Web Base
o   Mobile Applications
o   Window Service
o   Web Service
-          Integration other third party technologies
o   AJAX
o   Web Service
o   Web 2.0
-          No more “DLL Hell”
-          All .NET language is Object Oriented
What is the location of frameworks?
C:\Windows\Microsoft.NET\Framework

C# as Programming Language
-          A programming language based on .NET Framework based on C and C++, with the power of Java and simplicity of Visual Basic
-          It is an object Oriented Language
-          Every program should have a class
-          Every executable program  (.exe) must have an entry point
o   public static void Main()
o   public static int Main()
o   public static void Main(string []args)
o   public static int Main(string []args)
-          File must be saved as .cs
Syntactical Rules of C#
-          All keywords must be lower case
-          All other items should start with capital letter
o   It is called as Pascal case
Hierarchy in .NET
Assembly or Dynamic Link Library (DLL) à Namespaces à Classes/Structures àField/Method etc.
Example
MSCorlib.dll à System namespace à Console class à Write(),WriteLine()
Test Case
System.Console.WriteLine("Hello to C#");
Writing First C# (C-Sharp) Program
Class First
{
                public static void Main()
                {
                                System.Console.WriteLine("Hello to C#");
                }
}

Compile the program
-          Use compiler as CSC.EXE
o   CSC <programname>
CSC First.cs à First.exe
Running an executable file
First
Note: If CSC is not working then set the PATH
Look for your framework folder, copy the path, now the set path using DOS
SET PATH=%PATH%; C:\WINDOWS\Microsoft.NET\Framework\v3.5
Setting Path using My Computer à Properties à Advanced à Environmental Variables à System Variables à Path à Edit à Add your path after a semicolon
View contents of an MSIL file
      Use ILDASM (Intermediate Language De-Assembler) tool to view contents of an MSIL file
ILDASM <filename>
Example
ILDASM First.exe
How C# programs execute
.cs à CSC à .exeà CLR à Code Verifier à Just-in-time (JIT) compiler à Native code à Execution

Importing the Namespaces
-          Use using keyword
using <namespacename>;
Example
using System;
class First
{
        public static void Main()
        {
                        Console.WriteLine("Hello to Using");
        }

Creating Aliases to namespace and classes
-          Use the using keyword again
using <aliasname>=<namespace or class>;
Example
//Creating an alias
using c=System.Console;
class First
{
                public static void Main()
                {
                                c.WriteLine("Hello to Alias");
                }
}

Using Visual Studio.NET IDE as RAD (Rapid Application Development) tool
-          Start the Visual Studio.NET 2008
-          Create a new project using Visual C# as language and Console Application as Template
-          Select the location and Type the Project Name as Sample
-          Use Ctrl+F5 to run the programs


Monday 15 October 2012

Difference between Application, Session, View State, Cookies & Query String.

I am introducing the main difference between Application, Session, View State, and Cookies & Query String.


The Application Object: The Application object stores data that is shared across the application and not for a specific user. Whereas every page request gets its own Request and Response objects, all requests for ASP pages in a Web application share the same Application object. This object is created the first time an ASP page is requested from the application after the Web server starts up, and is destroyed when the Web server shuts down, or when the Web application is unloaded manually in the IIS management console. Because this object persists from one page request to another, it can be used to store data that you want to share with all other pages in your application.
Syntax: Application(“varName”) = value
 
The Session Object: The Session object is very similar to the Application object, as it allows you to store values that are shared between all the pages of your site. The main difference between the two is that,     where a single Application object is shared by all pages and all clients that access your site, each client (browser) is assigned its own Session object. Thus, a Session object must be created for each user session that occurs on your Website.
Syntax: Session(“username”) = “Abhinav bajpai”

The View State: The ViewState allows ASP.NET to repopulate form fields on each postback to the server, making sure that a form is not automatically cleared when the user hits the submit button. All this happens automatically, unless you turn it off, but you can actually use the ViewState for your own purposes as well. Please keep in mind though, that while cookies and sessions can be accessed from all your pages on your website, ViewState values are not carried between pages. StateBag implements the view state and manages the information that ASP.NET pages and embedded controls persist across successive posts of the same page instance.
Syntax: ViewState(“FontSize”) = value

Cookie: Cookie is one of several ways to store data about web site visitors during the time when web server and browser are not connected. Common use of cookies is to remember users between visits. Practically, cookie is a small text file sent by web server and saved by web browser on client machine.
Syntax: Response.Cookies["MyCookieName"].Value=“MyCookieValue”;

Querystring: Query string is used to pass the values or information form one page to another page.
Syntax: Request.QueryString(variable)[(index)|.Count]

Thank you ! keep visiting guys....

Friday 31 August 2012

SQL SERVER – Union vs. Union All – Which is better for performance?



 
UNION

The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.

UNION ALL

The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values.
The difference between Union and Union all is that Union all will not eliminate duplicate rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table.

A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it gives faster results.
Example:

Table1:First,Second,Third,Fourth,Fifth
Table 2 : First,Second,Fifth,Sixth

ResultSet:

UNION: First,Second,Third,Fourth,Fifth,Sixth (This will remove duplicate values)

UNION ALL: First,First,Second,Second,Third,Fourth,Fifth,Fifth,Sixth,Sixth (This will repeat values) 

Thanks Your 
Keep visiting guys.............

Thursday 16 August 2012

Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice in asp.net or how to create webservice and how to use webservice in asp.net

Description:
Today I am writing article to explain about webservices. First we will see what is webservice is and uses of webservice and then we will see how to use webservice in our applications.

What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Examples for Web Service

Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.

Stock Quote: You can display latest update of Share market with Stock Quote on your web site.

News Headline: You can display latest news update by using News Headline Web Service in your website.

In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Frequently used word with web services

What is SOAP?

SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

What is WSDL? 

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.

What is Discovery or .Disco Files?

Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose

Column Name
Data Type
Allow Nulls
UserId
Int(Set Identity=true)
No
UserName
Varchar(50)
Yes
FirstName
Varchar(50)
Yes
LastName
Varchar(50)
Yes
Location
Varchar(50)
Yes

Now we will see how to create new web service application in asp.net

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service



Now our new web service ready our webservice website like this



Now open your Service.cs file in web service website to write the code to get the user details from database

Before writing the WebMethod in Service.cs first add following namespaces


using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page

[WebMethod]
public XmlElement GetUserDetails(string userName)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Abhinav-Db"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like @userName+'%'", con);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
// Return the DataSet as an XmlElement.
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
return xmlElement;
}

Here we need to remember one point that is adding [WebMethod] before method definition because we need to access web method pulically otherwise it’s not possible to access method publically. If you observe above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.

Here we need to set the database connection in web.config because here I am getting database connection from web.config


<connectionStrings>
<add name="Abhinav-Db" connectionString="Data Source=SQLSERVER2008R2;Integrated Security=true;Initial Catalog=EXAMPLEDATEBASE"/>
</connectionStrings>
Now run your web service it would be like this


Our web service is working fine now we need to know how we can use webservice in our application?

How to Use Web service in web application?

By using this webservice we can get the user details based on username. For that first create one new web application

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Site


After creation of new website right click on solution explorer and choose “Add web reference” that would be like this


After select Add Web reference option one window will open like this 



Now enter your locally deployed web service link and click Go button after that your web service will found and window will looks like this


 

Now click on Add Reference button web service will add successfully. Now open your Default.aspx page and design like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
Now in code behind add following namespaces

using System.Data;
using System.Xml;


After adding namespaces write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUserDetails("");
}
}
protected void BindUserDetails(string userName)
{
localhost.Service objUserDetails = new localhost.Service();
DataSet dsresult = new DataSet();
XmlElement exelement = objUserDetails.GetUserDetails(userName);
if(exelement!=null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);
dsresult.ReadXml(nodereader, XmlReadMode.Auto);
gvUserDetails.DataSource = dsresult;
gvUserDetails.DataBind();
}
else
{
gvUserDetails.DataSource = null;
gvUserDetails.DataBind();   
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindUserDetails(txtUserName.Text);
}
Now run your application and check output