Wednesday, 29 August 2012

Code For Pyramid Shape in c#


Program to display a shape in form of Pyramid.............

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

namespace ConsoleApplication1
{
    class pyramidagain
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {

                for (int k = i; k < 10; k++)
                {
                    Console.Write(" ");
                }

                for (int j = 2 * i + 1; j > 0; j--)
                {
                    Console.Write("*");
                 
                }
                Console.WriteLine("");
             
            }
            Console.ReadKey();
        }
    }
}

Result of the Program will be as given below.....

Tuesday, 28 August 2012

To compile and run from a command prompt



With The Help of these steps you can run your program through command prompt.
  1. Paste the code from the preceding procedure into any text editor, and then save the file as a text file. Name the file Hello.cs. C# source code files use the extension.cs.
  2. On the Start menu, expand Visual Studio Tools, and then choose the shortcut to open a Visual Studio Command Prompt window.
    As an alternative, you can follow the instructions in How to: Set Environment Variables to enable command-line builds from a standard Command Prompt window.
  3. In the Visual Studio Command Prompt window, navigate to the folder that contains your Hello.cs file.
  4. Enter the following command to compile Hello.cs.
    csc Hello.cs
    If your program has no compilation errors, an executable file that is named Hello.exe is created.
  5. In the Visual Studio Command Prompt window, enter the following command to run the program:
    Hello


    Note: This information is taken from Microsoft site so if you want to know more then follow the link which is given below...





Friday, 24 August 2012

Main method can be Private?

Yes, Main method of the program can be private.it does not effect on output of the program.
i have checked It practically using C# on the visual Studio 2010.


You can see it in Example..............


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

namespace ConsoleApplication1
{
    class Factorial
    {
        public int fact(int n)
{
    if (n == 0) return 1;
    else return n * fact(n - 1);
}
       private static void Main(string[] args)
        {
            Factorial ob = new Factorial();
            Console.WriteLine("Type a number up to 20:");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(ob.fact(n));
            Console.Read();

        }
    }
    }

And Second thing if any program contain more than one Main method then what will happen?
No Problem, if  first main method declared as private and Second is Public then first Main method will compile and run but it can not be entry point of your Application.

For Example......


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

namespace ConsoleApplication1
{
    class MAinmethod
    {
==>        private static void Main(string[] args)
        {
            Console.WriteLine("Its awsome,, i am private and runnig here");
        }
        class testing
        {

==>          public static void Main(string[] args)
            {
                Console.WriteLine("i am public and running here");
                MAinmethod.Main(args);
                Console.Read();

            }
        }
    }
}

And Next question arise that if given example both are private then what will happen?


So it will not effect on the program output or in compilation and run. and take last Main method as the entry point of the Program...

for example............


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

namespace ConsoleApplication1
{
    class MAinmethod
    {
-->        private static void Main(string[] args)
        {
            Console.WriteLine("Its awsome,, i am private and runnig here");
        }
        class testing
        {

-->          private static void Main(string[] args)
            {
                Console.WriteLine("i am public and running here");
                MAinmethod.Main(args);
                Console.Read();

            }
        }
    }
}

out put of this Program will be............

Thursday, 23 August 2012

Super Key in DataBase

Super Key: A superkey is a combination of attributes that can be uniquely used to identify a database record. A table might have many superkeys. Candidate keys are a special subset of superkeys that do not have any extraneous information in them.

Candidate key and Alternate key ,Composite key

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. 
Composite Key: A key formed by combining at least two or more columns is called composite key.

Generally Candidate key is irreducible set of Super key, means you can't reduce more to make a primary key.and you can say it set of primary key because any one of them it can be a primary key. 
And rest of all called Alternate Key.

If you are unable to understand then we take an example and try to understand you.
if any table schema  is:  Student(a,b,c,d)
then we make set of primary key like this, then Candidate Key((a,b),(c,a),(a,b,d)) here you may be confuse but no problem ,it is only set of primary key, so any set of candidate key can be make a primary key. 
And if we make a set primary key(a,b) then rest of set is called alternate key.
and Composite key only those key which contains two or more than column of the table.

Here is example of Composite Primary Key......


CREATE TABLE Persons(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
This example is taken from w3schools.com....
AND / ORSELECT column_name(s) FROM table_name WHERE condition AND|OR condition
ALTER TABLEALTER TABLE table_name  ADD column_name datatypeor
ALTER TABLE table_name  DROP COLUMN column_name
AS (alias)SELECT column_name AS column_alias FROM table_nameor
SELECT column_name FROM table_name  AS table_alias
BETWEENSELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2
CREATE DATABASECREATE DATABASE database_name
CREATE TABLECREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name2 data_type, ... )
CREATE INDEXCREATE INDEX index_name ON table_name (column_name)or
CREATE UNIQUE INDEX index_name ON table_name (column_name)
CREATE VIEWCREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition
DELETEDELETE FROM table_name WHERE some_column=some_valueor
DELETE FROM table_name  (Note: Deletes the entire table!!)
DELETE * FROM table_name  (Note: Deletes the entire table!!)
DROP DATABASEDROP DATABASE database_name
DROP INDEXDROP INDEX table_name.index_name (SQL Server) DROP INDEX index_name ON table_name (MS Access) DROP INDEX index_name (DB2/Oracle) ALTER TABLE table_name DROP INDEX index_name (MySQL)
DROP TABLEDROP TABLE table_name
GROUP BYSELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name
HAVINGSELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value
INSELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..)
INSERT INTOINSERT INTO table_name VALUES (value1, value2, value3,....)or
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....)
INNER JOINSELECT column_name(s) FROM table_name1 INNER JOIN table_name2  ON table_name1.column_name=table_name2.column_name
LEFT JOINSELECT column_name(s) FROM table_name1 LEFT JOIN table_name2  ON table_name1.column_name=table_name2.column_name
RIGHT JOINSELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2  ON table_name1.column_name=table_name2.column_name
FULL JOINSELECT column_name(s) FROM table_name1 FULL JOIN table_name2  ON table_name1.column_name=table_name2.column_name
LIKESELECT column_name(s) FROM table_name WHERE column_name LIKE pattern
ORDER BYSELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC]
SELECTSELECT column_name(s) FROM table_name
SELECT *SELECT * FROM table_name
SELECT DISTINCTSELECT DISTINCT column_name(s) FROM table_name
SELECT INTOSELECT * INTO new_table_name [IN externaldatabase] FROM old_table_nameor
SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name
SELECT TOPSELECT TOP number|percent column_name(s) FROM table_name
TRUNCATE TABLETRUNCATE TABLE table_name
UNIONSELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
UNION ALLSELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2
UPDATEUPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value
WHERESELECT column_name(s) FROM table_name WHERE column_name operator value

Tuesday, 21 August 2012

Foreign Key

A foreign Key is a combination of columns with value is based on the primary key values from another table. A foreign key constraint also known as Referential Integrity Constraint

A foreign key is an attribute of the table which have the reference of a primary key in Second Table.



CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

and Here on question arise that is, foreign key should be primary key in second table or not?
 So don't be confuse i am clearing you.
Its not necessary that foreign key should be unique or primary key.
it is simple an attribute as other attribute in table.




Note-if you are very confused so do it practically. make table and apply all keys and try to understand.
Follow this Link to Help...www.w3schools.com

Monday, 20 August 2012

Primary Key

Primary Key
It is one or more columns in a table which is uniquely identified the rows of the table.

§       The primary key is the columns used to uniquely identify each row of a table. A table can have only one primary key.No primary key value can appear in more than one row in the table.
      
    Simply you can make any column as a primary key by using this code........
     Create Table testing(ID int not Null  primary key, name varchar(29),Fathername nvarchar(30)
    )
   
   
    But if you make this type of table and try to make a primary key in that table.........
   
    create table PanakjTesting
( Pid int , Name nvarchar(30),FatherName nvarchar(50),class nvarchar(10),Rollnumber numeric)

    And then we will try Alter the table to make a primary key so we will fire this query ...
    
    Alter table PanakjTesting
  add primary key(pid)
   
   Then it will show this error when we are making primary key in this table
  Error:  ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'ID' cannot be added to non-empty table ' PanakjTesting ' because it does not satisfy these conditions.

   Means if any table does not have any column as unique or not null constraint you can not alter that table to make primary key.
  
   Now we will talk about the Null value or Zero value.
   So Primary key can accept the 0 but can  not accept null value....
  I tested it practically ! if there is no identity the PRIMARY KEY WILL ACCEPT 0! BUT NOT NULL
  insert into PanakjTesting values('0','Panakj','Papa','MCA','02457265345')

    But if you set the identity to start primary key from a particular value then it will not accept.

   

  NOTE:-If YOu have any question or doubt then please send me that on my mail id:kushwaha.pankajkumar07@gmail.com

Sunday, 19 August 2012

Difference between Web.config and Machine.config:


Configuration files are used to control and manage the behavior of a web application.

  1. Machine.config:This is automatically installed when you install Visual Studio. Net.This is also called machine level configuration file. Only one Machine.config file exists on a server.This file is at the highest level in the configuration hierarchy.
  2. Web.config:This is automatically created when you create an ASP.Net web application project. This is also called application level configuration file. This file inherits setting from the Machine.config
Difference between Web.config and Machine.config:
  • The settings made in the Web.config file are applied to that particular web application only whereas the settings of Machine.config file are applied to the whole asp.net application.
  • Web.config file Setting of asp.net all project Machine.config are setting of server setting and when the web side are implemented time it work all project but Web.config file set all projects
  • Web config will be for that particular aplln whereas the Machine .config will for the whole machine
  • Every ASP.NET application that you has a Web.config file . The settings specified in this will imply only to that application.Whereas Your System will have a Machine.config file in Microsoft.NET\Framework\v1.1.4322\CONFIG Folder which contains specifications and settings at a system level.
  • Web.config file is to override the settings from the Machine.config file. Machine.config file settings are applied to all the webapplications residing on the server while Web.config settings are application specific.
  • Machine. config is configuration file for all the application in the IIS. but Web.config is a configuration file for a application or folder.
  • Machine.config for machine level configuration. but Web.config for a application/folder level configuration

Friday, 17 August 2012


Asp.net Read/insert data into XML file and bind data to DataList

Introduction

how to insert data into XML and how to retrieve data from XML and how to bind data to DataList using asp.net.

Description:

XML means Extensible markup language why we need to use this one because by using XML we can store the data and we can easily retrieve and display the data without using database in our applications.if we need to display dynamic data in our application it will take time to conenct database and retrive data from database but if use XML to store data we can do operations with xml file directly without using database. If we store data in database that is incompatible to some of the computer applications but if we store data in XML format it will support for all applications. It is independent for all software applications and it is accessible with all applications.

Now I will explain inserting data into xml and retrive data from XML and bind data to datalist with simple example.

Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="width100px">
Name:</td>
<td style="width100px">
<asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width100px">
Location:</td>
<td style="width100px">
<asp:TextBox ID="txtLocation" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width100px">
Email:</td>
<td style="width100px">
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width100px" valign="top">
Comments:</td>
<td style="width100px">
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Height="104px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /></td>
</tr>
</table>
<br />
<asp:DataList ID="dlComments" Runat="server" Width="100%">
<ItemTemplate>
<hr size=0/>
Name: <%# DataBinder.Eval(Container.DataItem, "name"%><br />
E-mail: <a href="mailto:<%# DataBinder.Eval(Container.DataItem, "email") %>"><%#DataBinder.Eval(Container.DataItem, "email"%></a><br />
Location: <%# DataBinder.Eval(Container.DataItem, "location"%><br />
Date: <%# DataBinder.Eval(Container.DataItem, "Date"%><br />
Description: <%# DataBinder.Eval(Container.DataItem, "Description"%>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>
After that add XML file to your application and give name as "Sample.xml" intially xml file like this root element is compulsary for XML files that’s why I added CommentInformation in XML file that root element in XML file.

<?xml version="1.0" encoding="utf-8"?>
<CommentsInformation>
 </CommentsInformation>
After that add this namespace in codebehind

using System.Xml;
using System.Data;
After that write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind xml data to datalist
BindDatalist();
}
}
/// <summary>
/// btnSubmit event is used to insert data into XML file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnSubmit_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("Sample.xml"));
XmlElement parentelement = xmldoc.CreateElement("Comments");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = txtName.Text;
XmlElement location = xmldoc.CreateElement("location");
location.InnerText = txtLocation.Text;
XmlElement email = xmldoc.CreateElement("Email");
email.InnerText = txtEmail.Text;
XmlElement Description = xmldoc.CreateElement("Description");
Description.InnerText = txtComments.Text;
XmlElement date = xmldoc.CreateElement("Date");
date.InnerText = DateTime.Now.ToString();
parentelement.AppendChild(name);
parentelement.AppendChild(location);
parentelement.AppendChild(email);
parentelement.AppendChild(Description);
parentelement.AppendChild(date);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Sample.xml"));
BindDatalist();
}
/// <summary>
/// Bind xml data to datalist
/// </summary>
private void BindDatalist()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("Sample.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
dlComments.DataSource = ds;
dlComments.DataBind();
}
else
{
dlComments.DataSource = null;
dlComments.DataBind();
}
}