Monday, 31 December 2012

Database connection in visual studio 2010


The database features that are included in Visual Studio make use of one or more database connections. Before you can connect to a database, you must create the connection.
           The first thing you will need to do when interacting with a database is to create a connection. The connection tells the rest of the ADO.NET code which database it is talking to. It manages all of the low level logic associated with the specific database protocols.

You must include the  using System.Data.SqlClient; namespace to your code.  The System.Data.SqlClient namespace is the.NET Framework Data Provider for SQL Server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

Creating a SqlConnection Object:
    A SqlConnection is an object, just like any other C# object. Most of them time, you just declare and instantiate the SqlConnection all at the same time, as shown below.
SqlConnection cn = new SqlConnection(@"Data Source=.local; Intial Catalog= testdatabase;Integrated Security=SSPI"); 
Data source=(local); - this means that we want to connect to the sql server instance located on the local machine.
Initial catalog=testdatabase; - This means the database we want to first connect to is named "testdatabase.
Integrated security=SSPI; - This means we want to connect using windows authentication.

To Create a Database connection Fellow below steps:
Step 1:  Open visual studio 2010 click on File->New->Project.


 Step 2:
     Select ASP.NET Empty Web Application->  Give  name to project as you like. I give here to my project name as " connection ". Next click on OK Button
 

Step 3:
Now right click on project --> "Add"  and choose "Add New Item".


Step 4:
Select the "Web Form"  item, give it a file name and click Add 


Step 5:
 Now you will get one blank web form. Add two text boxes, two labels and one button.


web form code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="home.aspx.cs" Inherits="connecton.home" %>
<!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>Connection in Visual studio 2010</title>
 </head>
 <body>
 <form id="form1" runat="server">
 <div>
 <asp:Label ID="Lable1" runat="server" Text="Student RollNo"></asp:Label>
 <asp:TextBox  runat="server" ID="Studentnum" ></asp:TextBox><br />

 <asp:Label ID="Label2" runat="server" Text="Student Name"></asp:Label>
 <asp:TextBox ID="stdname" runat="server"></asp:TextBox>
 <br />
 <asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
 <br />
 </div>
 </form>
 </body>
 </html>


Step 6:
Now you have to add database to your Project:
Right click on project --> "Add"  and choose "Add New Item".

Select the "Sql server Database"  item, give database name and click Add 
Step 7:
When you clicked on Add it will ask you as

 You are attempting to add a special file type(.mdf) to an asp>net web site. in general, to use this type of item in your site. You should place it in the ‘app_data’ folder. do you want to place the file in the ‘app_data’ folder

Click on Yes.

Database added to your project.

Step 8:
Click on Server Explorer you will find your database in server explorer. Click on "+" database:
Right click on Tables -->  Add new Table


Step 9:
 Enter table columns names and their data type.

Step 10:
Give a table name in popup window:

Create a Table using Query:

CREATE TABLE studentinfo
(
 studentno int,
 studentname varchar(50)
)

Step11:
This Is very important step in this topic.
 Right click on your database in server explorer select properties : In properties box you will  find connection string. Copy That total connection string and give it as a parameter to a SqlConnection string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

namespace connecton
{
public partial class home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e){
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename='c:\documents and settings\rajendar reddy\my documents\visual studio 2010\Projects\connecton\connecton\App_Data\connection.mdf';Integrated Security=True;User Instance=True");
cn.Open(); // Connection will be open here.
SqlCommand cmd = new SqlCommand("insert into studentinfo values(" + Convert.ToInt32(Studentnum.Text) + ",'" + stdname.Text + "')", cn);
cmd.ExecuteNonQuery(); // It Excutes SqlCommand
cn.Close(); // connection closing
 Response.Write("<script>alert('inserted successfully')</script>"); // it shows the message
}
}
}





Step 12:
Debug Home form:


Step 13:
Enter Values in text boxes


Out Put:


Friday, 28 December 2012

Mater Page

Srinivas Amrutha:
In this article, I am going to explain how to create a "Master Page" , what is the Advantages of Master Page, Interview Questions and Answers.

Master Pages:
A mater page can be created to hold those page elements that represents the common look and feel of website. Various page elements that you might normally have added to each content page (banners,footers,menus etc..) can instead be placed in the master page. When a new content page is created, the developer simply needs to link it to an existing master page.
            However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derived page does not need to override this content.

To create a Master Pages open  Visual Studio 2010 Click on Start new project ->



  Select ASP.NET Empty web application.



Give the name to project as you like. I give here to my project name as " Masterpage ". Next click on OK Button. Now right click on project and choose "Add New Item", and select the "Master Page"  item.
Select Master Page, give it a file name and click Add



When you create a new master page in Visual Studio, you start with a blank page that includes a ContentPlaceHolder control. If you add a header, that header appears in every content page.
If you want to give the content page the opportunity to supply content in a specific section of
the page, you need to add a ContentPlaceHolder.



Master Page Code:
---------------------------------------------------------------------------------------------------------------
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="srinivas.master.cs" Inherits="Masterpage.srinivas" %>

<!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>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <h2> Wlecome To Srinivas Amruthas's Blog</h2>
    <br />
    <a href="http://dotnettutorialblog.blogspot.in/" target ="_blank" >
    http://dotnettutorialblog.blogspot.in/ </a>

</div>
 
       <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
   
    </form>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------------------------

 Now that i have my Master Page defined, I can go ahead and build pages using it. To build one, right click on project and choose "Add New Item", and select the "web Form using Master Page"  item.



Developer that you want to have this new page use a Master Page. when you click the "add" button it will then ask you to pick the Master Page to use:

Click on OK button. Now, the web form will have the Master page entry as below:

<%@ Page Title="" Language="C#" MasterPageFile="~/srinivas.Master"
AutoEventWireup="true" CodeBehind="Homepage.aspx.cs" Inherits="Masterpage.Homepage" %>


After selecting the master page, on the web form Visual web developer has automatically added an <asp:content> control for the "Main Content" ContentPlaceHolder. 

Content Page:



 Content Page Code:
----------------------------------------------------------------------------------------------------------
 <%@ Page Title="" Language="C#" MasterPageFile="~/srinivas.Master"
AutoEventWireup="true" CodeBehind="Homepage.aspx.cs" Inherits="Masterpage.Homepage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h3 > Hi This is Srinivas Amrutha</h3>
</asp:Content>

 --------------------------------------------------------------------------------------------------------------
Debug content page:


Advantages of Master Pages:

If you're wandering why you should start using master pages take a look at the following list:
  • Creating websites using master pages usually requires less work because you create a template of website and then just add content to it.
  • Consistent look and feel - because there is only one master page each webpage has exactly the same design.
  • It's flexible - if you want to change something in look and feel of your website you can just edit master page, then each of your pages will also be changed.
  • You can use pages designed for content placeholders also in you other projects. For example you can use contact page on various websites with different designs because it usually remains the same.
  • There are mechanisms that allow you to change master page from each content page.
  • It's easy to change final layout of your pages.
Interview Questions: 

1. What is the file extension for a master page?
 .master
 2. Can I write any script outside Content control of the content page?
No, if you write any script outside of Content tag in a content page, you will get a compilation error. 
Compilation Error: “Only Content controls are allowed directly in a content page that contains Content controls.”   
3. Can I access controls of master page in content pages?
Yes, controls in master page are accessible to content pages.  
4.  Can I add more than one content placeholder to a master page? 
Yes, a master page can have more than one ContentPlaceHolder.  
 5. How do you identify a master page?
The master page is identified by @Master directive, which replaces the @Page directive that is used for    ordinary aspx page.  
 6. Can master page inherits another master page..?
Yes.One master page can inherit a second master page in ASP.NET.
 However ,a single page cannot inherit two different master pages directly. But a single page inherit two different master pages indirectly.
7. Define multiple Master Pages..?
In ASP.NET, you can have multiple master pages each for a different purpose. You can provide users several layout options using Multiple Master Page. You can define Master Page at multiple places in the web application.
You can specify page-level using the @Page dierective.
You can specify using the Web.config.
Remember that the definition closest to the user wins that means page-level definition supersedes site-level definition.  

8. What is a content placeholder..ContentPlaceHoder is a region where replaceable content will appear.  
9. At what stage of page processing, master page and content page are merged?
Master page and content page are merged during page initialization stage.  
10. What are the different ways to attach content pages to a master page?
You can attach content pages to a master page at three levels: 
 I. page level
<%@ Page Language="C#" MasterPageFile="MySite.Master" %>
 II. Application Level: By making a setting in the pages element of the application's configuration file
<pages masterPageFile="MySite.Master" />
 III. At the folder level : This strategy is like binding at the application level, except that you make the setting  in a Web.config file in one folder only.  


Wednesday, 26 December 2012

Factorial of a number

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace fact
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, sum=1;
            Console.WriteLine("Enter The number");
            n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("factorial of a number");
            for (i = 1; i <= n; i++)
            {
                sum = sum * i;
            }
            Console.WriteLine(sum);
            Console.ReadLine();
        }
    }
}

GCD of two Numbers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace even
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            Console.WriteLine("Enter 'a' value");
            a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter 'b' value");
            b = Convert.ToInt32(Console.ReadLine());
            while (a != b)
            {
                if (a > b)
                {
                    a = a - b;
                }
                else
                {
                    b = b - a;
                }
               
            }
            Console.WriteLine("GCD IS   " + b);

            Console.ReadLine();
        }
       
    }
}

Pascal's Triangle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace pascal
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, i, row, n;
            Console.WriteLine("Enter number of rows");

            row = Convert.ToInt32(Console.ReadLine());
            a = 1;
            i = 0;
            Console.WriteLine("Pascal Triangle");
            while (i < row)
            {
                for (b = 40 - 3 * i; b > 0; b--)
                {
                    Console.Write(" ");
                }
               
                for (n = 0; n <= i; n++)
                {
                    if ((n == 0) || (i == 0))
                    {
                        a = 1;
                    }
                    else
                    {
                        a = (a * (i - n + 1)) / n;
                    }
                    Console.Write(a);
                    Console.Write("     ");// give 5 spaces
                }

                Console.WriteLine();
                i++;

            }
            Console.ReadLine();

        }
       
    }
}

Generate Fibonacci Series.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace fibonacci
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, sum=1;
            Console.WriteLine("Enter The number");
            n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("factorial of a number");
            for (i = 1; i <= n; i++)
            {
                sum = sum * i;
            }
            Console.WriteLine(sum);
            Console.ReadLine();
        }
    }
}

Print the Pyramid of numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace pyramid
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i, j;
            Console.WriteLine("Enter the N value");
            n = Convert.ToInt32(Console.ReadLine());
            for (i = 1; i <= n; i++)
            {
                for (j = 1; j <= i; j++)
                {
                    Console.Write(j);
                }
                Console.WriteLine();
            }
            Console.ReadLine();

        }
    }
}

Swapping of two numbers with using third variable and without using third variable

I. With Using Third variable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace swap
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, swap;
            Console.WriteLine("Eneter 'a' value");
            a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter 'b' value");
            b = Convert.ToInt32(Console.ReadLine());
            swap = a;
            a = b;
            b = swap;
            Console.WriteLine("a== " + a + ",  b== " + b);
            Console.ReadLine();
        }
       
    }
}

II. without using third variable

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace swap
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, swap;
            Console.WriteLine("Eneter 'a' value");
            a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter 'b' value");
            b = Convert.ToInt32(Console.ReadLine());
            a = a + b;
            b = a - b;
            a = a - b;
            Console.WriteLine("a== " + a + ",  b== " + b);
            Console.ReadLine();
        }
       
    }
}

Find where the given number is prime or not

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace prime

{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i,count=0;
            Console.WriteLine("Eneter the Number");
            n=Convert.ToInt32 (Console.ReadLine ());
            for (i = 1; i <= n; i++)
            {
                if (n % i == 0)
                {
                    count++;

                 }
              
            }
            if (count == 2)
            {
                Console.WriteLine("The Given Number is prime");
            }
            else
            {
                Console.WriteLine("The Given Number is not prime");
            }
            Console.ReadLine();
        }
      
    }
}

program for whether the given string is a palindrome or not

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace palindrome
{
    class Program
    {
        static void Main(string[] args)
        {
            int  i;
            string str = Console.ReadLine();
            char[] arr = str.ToCharArray(); // converting string to array
           char[] arr1 = new char[arr.Length];
            // now reverse an array using for loop
            for (i = 0; i < arr.Length; i++)
            {
                arr1[arr.Length - 1 - i] = arr[i];
            }
            // converting an array to string
            string result = new string(arr1);
          
         
            if (result == str)
            {
                Console.WriteLine("Given String is a palindrome");
            }
            else
            {
                Console.WriteLine("Given String is not a palindrome");
            }
            Console.ReadLine();
        }
    }
}

Biggest of three(3) numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace bigest
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            Console.WriteLine("Enter 'A' value");
            a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter 'B' value");
            b = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter 'C' value");
            c = Convert.ToInt32(Console.ReadLine());
            if (a > b && a > c)
            {
                Console.WriteLine("A is greater");

            }
            else if (b > c)
            {
                Console.WriteLine("B is greater");

            }
            else
            {
                Console.WriteLine("C is greater");
            }

            Console.ReadLine();
        }
      
    }
}

Revese a number

Hi friends commonly  we  are using below program to reversing a number. but in some cases its wont work like reversing of 20 and 02. once check it by using below program.

class Program
    {
        static void Main(string[] args)
        {
            int n , b, sum=0;
            n = Convert.ToInt32(Console.ReadLine ());
            while (n > 0)
            {
                b = n % 10;
                sum = (sum * 10) + b;
                n = n / 10;
            }
            Console.WriteLine(sum);
            Console.ReadLine();
             }
    }

I think you find its wont work to reverse a numbers which are starting with zero '0' and ending a number with a Zero '0'.  so am suggesting to you  choose below program while they are asking to reverse a number.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace reverse_of_a_number
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i;
            n = Convert.ToInt32(Console.ReadLine());
            string str = Convert.ToString(n); // converting int to string

           char[] arr = str.ToCharArray(); // converting string to array
           
           char[] arr1 = new char[arr.Length];
            // now reverse an array using for loop
            for (i = 0; i < arr.Length; i++)
            {
                arr1[arr.Length - 1 - i] = arr[i];
            }
            string result = new string(arr1); // converting an array to string
            Console.ReadLine();
        }
    }
}

NOTE:  1. For understanding purpose i added some unnecessary code.
             This program also have some mistakes Lts See who will finds it.
                                                  
                                                                          Thank You.

Tuesday, 25 December 2012

Basic Programs.

 Try to execute these programs with out using Predefined functions. 

1. write a program to find the biggest of  three(3) numbers.

2.  write a program to find the factorial of a number.

3.  write a program to reverse a number.

4.  write a program to whether the given string is a palindrome or not.

5.  write a program to find where the given number prime or not.

6.  write a program to swap two numbers with using third variable and with out using third variable.

7.  write a program to print the pyramid of numbers.

8.  write a program to generate fibonacci series.

9.  write a program to print the Pascal's triangle.

10. write a program to find gcd of two numbers.