Thursday, 17 April 2014

c#- Numeric Data Types

Strong and Weak Typed Languages

C# is a strongly typed language. All variables in a program must be declared as being of a specific type. The variable's behaviour is defined by the chosen type. For example, an integer variable can only contain whole numbers. If a number in an integer variable needs a fractional part, it must first be converted to a different type, possibly being stored in a new variable as a part of the translation.
The alternative to a strongly typed language is a weakly typed language. An example would be VBScript used by many classic ASP developers. In VBScript, the type of the variable is not declared and the behaviour of the variable may appear to change from one line of code to the next.

Variable Declaration and Assignment

A variable can be declared with one line of code, specifying the variable type and its name. In the following code, an integer variable is declared using the data type int.
 int numberofArticles;
A variable can be given a value using the assignment operator, (=). The variable to the left of the operator is assigned the value to the right. The following code shows a variable being declared and assigned a value.
int numberofArticles;
numberofArticles=3;
You do not need to assign a value to a new variable immediately. There may be many lines of code between the declaring a variable and giving it a value. However, if you do wish to declare a variable and assign a value at the same time, this can be achieved in a single statement. For example:
int numberofArticles=3; 
It is possible to declare multiple variables of the same type in a single line of code. You can also assign the same value to multiple variables in one statement. To complicate things further (or to show the elegance of C#, depending on your viewpoint), these operations can be combined. The following code shows three examples.
NB: Multiple variables can be assigned the same value in this manner because the assignment operation returns the value that has been assigned.

Assignment Problems

Definite Assignment

The C# compiler enforces a rule known as definite assignment. This states that a variable may not be read until a value has been assigned. This prevents you from writing code that reads a variable with an undefined value, as this could give unpredictable results.
The following code fails to compile, displaying the error "Use of unassigned variable numberOfArticles".


  











 

 

 

   

Numeric Data Type Reference

I will end this article with a quick reference to the numeric data types. For integer types, the declaration keyword, a description of the type, the range of possible values and the number of bits used to represent the value are given. For non-integers, the scale and the number of digits of accuracy are given, rather than minimum and maximum. This allows you to determine which data type should be used for any numeric variable.
The Boolean type is included, which although not technically numeric, fits well in this table. The Boolean type can hold either true or false. It is named after the mathematician, George Boole.

c# comment

How to Comment
Now that we have investigated why and what to comment, we need to know how to comment. There are three types of comment that C# can include. They are single line, trailing and multi-line comments.
Single Line Comments
The simplest form of comment in C# is the single line comment. The line is started with a double forward slash, (//). Any text or code following the double slash is ignored during compilation.

Hello world


Console vs Windows vs Web Application
The .NET framework, combined with C#, allows you to develop several types of software. These include Windows-based programs, web-based applications and even console applications for execution from the command prompt. In this article, we will create a console application similar to the original Hello World program. A console application requires little supporting code and gives the clearest opportunity for understanding the language.
Creating the Program
Step 1 - Create a Console Application
Console Application IconI will assume that you are using Microsoft Visual Studio or Microsoft C# Express Edition to develop the program. Launch your chosen development environment and create a new project of the type, "Console Application". Name the application, "HelloWorld".
Step 2 - Add the Functionality
The development environment should have created all of the template code needed for a console application. This includes a "Main" function that is similar though not identical to the original K&R application. All that is left is for you to do is to add the code that actually prints "hello, world".
C# is derived from C but does not share all of its commands. We cannot use the printf command to output text, as this command is not supported. Instead we use the Console.WriteLine function. Add the following code between the braces {} of the Main function, ending the second line with a semicolon (;).

 

Step 3 - Test the Program

You can execute your program directly from Visual Studio or C# Express Edition by selecting "Start Without Debugging" from the Debug menu or by hitting Ctrl-F5. You should see the words, "Hello World" in a console window and an instruction to press a key to continue.
Note: You would usually start programs with debugging enabled by pressing F5. In the case of a console application, the application may close before the results are seen. Using Ctrl-F5 adds the requirement to press a key when the application stops.

Wednesday, 9 April 2014

How to Display Image in Gridview from Database

Display image in gridview 

In this article we will see how to display image in a gridview  from database (SQL Server).
In this case we need a Template column in a gridview and add html image (img) tag in it. you can also take asp.net image control but it will generate view state so we have taken html img tag.
if you are using asp.net image control than i would suggest that make the EnableViewState property of image control to false.
Lets see the scenario

Display Picture in a GridView from Database

let's 1st create a table and call it as Image_Table to create sample table below is the code. Here I am using Image data type of SQL server to save image into it. As we all know that SQL Server store Image as binary data in a column of datatype IMAGE.


CREATE TABLE [dbo].[Image_Table](

 [id] [int] IDENTITY(1,1) NOT NULL,

 [SomeText] [varchar](50) NULL,

 [ImagePath] [varchar](200) NULL,

 [Image_Blob] [image] NULL,

 CONSTRAINT [PK_Image_Table] PRIMARY KEY CLUSTERED

(

 [id] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

Here is the table schema in figure


 Now Create one stored procedure to fetch data from database and bind that to GridView

CREATE PROCEDURE GetImageInfoFromDB

AS

BEGIN
 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table

END
In this example we are using HTTPHandler to fetch Images from Database. For that I have created another stored procedure which will accept one input parameter id


CREATE PROCEDURE GetImageFromDB(@id int)

AS

BEGIN        
 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table WHERE id = @id

END

I assume that some data is available into the table    


  To add HTTPHandler right click on the project explorer --> AddNewItem --> Generic Handler from the templete eg given pic below and Name it as ImageHanlder.ashx
 

Now in you HTTPHandler you can add this lines of code

<%@ WebHandler Language="C#" Class="ImageHandler" %>

 

using System;

using System.Web;

using System.Data.SqlClient;

using System.Data;

using System.Configuration;

 
 

public class ImageHandler : IHttpHandler {

 

    public void ProcessRequest(HttpContext context)

    {

        string strId = context.Request.QueryString["Id"];

 

        if (!string.IsNullOrEmpty(strId))

        {

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

            SqlDataReader sqlDr = null;

            try

            {

                conn.Open(); //open database connection

 

                SqlCommand sqlCmd = new SqlCommand("GetImageFromDB", conn);

                sqlCmd.CommandType = CommandType.StoredProcedure;

                 

                //Add the parameter to SQLCommand object

                sqlCmd.Parameters.AddWithValue("@id", strId);

 

                sqlDr = sqlCmd.ExecuteReader();

 

                sqlDr.Read();

 

                context.Response.BinaryWrite((Byte[])sqlDr[3]);

 

                context.Response.End();

                 

                 

            }

            catch (Exception ex)

            {

                //Handle error If occured

            }

            finally

            {

                if (sqlDr != null && !sqlDr.IsClosed)

                {

                    sqlDr.Close(); //close SqlDataReader

                }

                conn.Close();//close database connection

            }

        }

 

    }

  

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

Now in you page in which gridView is there your code should look like this after adding templete column

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False">

       <columns>

           <asp:boundfield datafield="SomeText" headertext="Header Text">

           <asp:templatefield headertext="Image Form DataBase">

               <itemtemplate>

                   <img alt="Image" src="%3C%#%20%22ImageHandler.ashx?Id=%22+%20Eval%28%22id%22%29%20%%3E" height="70px" width="70px">

               </itemtemplate>

           </asp:templatefield>

       </asp:boundfield></columns>

   </asp:gridview> 

Now to bind data in a gridview you can add below lines of code in any event in which you want like Page Load event, Button Click event etc.
In C# example


private void LoadData()

{

 

        string returnValue = string.Empty;

 

        //Get the databse connection string from web.config file

        string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

 

        SqlConnection sqlConn = new SqlConnection(conString);

        SqlDataReader sqlDr = null;

        try

        {

            //Call the stored procedure using SQLDataAdapter

            SqlDataAdapter salDa = new SqlDataAdapter("GetImageInfoFromDB", sqlConn);

             

            DataSet ds = new DataSet();

            salDa.Fill(ds);   // Fill the dataset

 

            //Bind the data which in form of dataset to ggridview

            GridView1.DataSource = ds;

            GridView1.DataBind();

 

        }

        catch (Exception ex)

        {

            //Handle Error if any occured

        }

        finally

       {

            if (sqlDr != null && !sqlDr.IsClosed)

            {

                sqlDr.Close(); //close sqldatareader

            }

            //Close SQL connection

            sqlConn.Close();

        }

 
} 







































 If you run the application you can see in image in gridview like this










































































































































































































Chart Controls in Asp.net

open Visual Studio 2008. In the Data tab on the Toolbox, observe the new ‘Chart’ control.
Chart Toolbox 

To get started, let us create a sample application using the Chart control:
Step 1: Drag and drop the Chart control from the Toolbox to the Design surface of Default.aspx. You will see a ‘Column chart’ which looks similar to the following:
Sample Chart 
 
If you click on the ‘Source’ view of the page, you find the following mark up added to the page:
<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
 
        <asp:Chart ID="Chart1" runat="server">
            <Series>
                <asp:Series Name="Series1">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
By default the ChartType is ‘Column’. In order to change the Chart Type to either Line, Bar, Pie or any of these 25 chart types; with the Chart control selected, go to the Properties window > go to ‘Series’ > Click on the ellipse button(…) > in the ‘Series Collection Editor’, click on the ‘ChartType’ to view and select a different chart type as shown below:
Series Coll Editor 
For this demonstration, we will keep the ChartType to the default ‘Column’.
We will be binding the chart to some data. For this purpose, we will be using the SqlDataSource.
Step 2: Click on the smart tag or right click Chart > Show Smart Tag > Choose a DataSource > New Data Source… > Select Database. We will keep the default ID for SqlDataSource, SqlDataSource1 and click OK.
Step 3: On clicking OK, you will be presented with a ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have typed (local) as the ServerName and the database I am connecting to is ‘Northwind’. Click on ‘Test Connection’ to make sure that there are no errors connecting to the server. Click Ok.
Step 4: In your ‘Configure Data Source’, click Next. An option will be displayed for saving the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’ , type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 5: In the ‘Configure Select Statement’ > select ‘Specify a Custom SQL Statement or stored procedure’ > click Next
SQL Data Src 
Type the SQL query to ‘list the count of products in a category’ as shown below:
SELECT CategoryName, COUNT(*) AS ProductCount FROM Products JOIN Categories ON Products.CategoryID = Categories.CategoryID GROUP BY CategoryName
Query 
Click Next > Finish.
Step 6: Select the Chart control > Go to the Properties window > ChartAreas property and click the ellipse (…) button to open the ChartArea collection editor. Go to the ‘Axes’ property in the ChartArea Collection Editor and click the ellipse (…) button to open the Axis collection editor as shown below:
 
Axis Coll Editor
Set the ‘Title’ of the X axis to ‘Categories’ and the ‘Title’ of the Y axis to ‘Product Count’. Click OK to close the Axis Collection Editor and an OK again to close the ChartArea Collection Editor.
With the Chart control selected, go to the Series property in the Properties window and click the ellipse (…) button to open the Series collection editor. Go to the Data Source section and add the XValueMember as ‘CategoryName’ and YValueMembers to ‘ProductCount’. Also set the ‘IsValueShownAsLabel’ to True to display the value of ProductCount on the columns. Click OK
 
Series Coll Editor 
Step 7: With the properties set, run the application. You will see a chart as displayed below:
Final Chart