Tuesday, January 31, 2012

application related settings in config file

Title: How to set connection string settings in app.config in c#.net

Description:
Here i will describe what are the settings are available in config files and what is the use of those settings .
In asp.net by default no values of current page or accessible to other pages .if we want to define application wide static settings then we can use app settings tag of web.config.This should be written under configuration tag.With above app settings when we run the application automatically id and month are loaded to retrieve the in code they have to use a .net assembly or name space called System.Configuration.

Configuration Manager(old configuration settings) or classes are that are retrieve value from configuration file.All applications that are related to data sources need connection string.It is very difficult to maintain connection string in programs and also to maintain consistent connection strings(connection pooling,asynchronous precessing etc)In .net version this is tag is added to write connection string in configuration level and refuse it for entire project .As per location are data source of project is relocated to connection strings.This connection string written under configuration directly

Codebehind:
string str=ConfigurationManager.ConnectionStrings["Con"].ToString();
SqlConnectioncn=new SqlConnection(str);
cn.open();
label.test="database connected";
Data source controls also recommended to save connection string in configuration file.We can use connection string and some other web.config settinggs in markup also.
< % $config settings % >
ex:-connectionString="< % $connectionString:pubs % >"

Monday, January 30, 2012

Accessing data from the Dataset

A data set i collection of tables where each table is represented in the form of a class as data table and identified by it's index position or name

Dataset:
collection of tables(DataTable)
[dataset].Tables[index] or Tables[name]
ds.Tables[0] or ds.Tables["students"]
Every data table is again a collection of row and cols where each row is represented in the form of a class known as DataRow and Identified by it's by index position,each column is represented in the form a class known as DataCol and Identified by it's Index position or name

Data Table:
//collection of Row(DataRow)
[datatable].Rows[index]

//collection of columns(DataColumn)
[datatable].columns[index]or columns[name]
ds.Tables[0].columns[0] or ds.Tables[0].columns["sno"]

//Retriving to a cell under the Data Table
[datatable].Rows[row][col]
ds.Tables[o].Rows[0][0]or
ds.Tables[0].Rows[0]["sno"]

Sunday, January 29, 2012

inherit control in asp.net

It is the control which id inherited from an existing control and providing additional functionalities in it.To create inherited user control the class declaration need to be as below.
ex:Masked Text box of Rich Text box which are inherited from a tex box control
public class MaskedTextBox :TextBox 
public class RichTextBox:TextBox 
Creating a mytextbox control which can be customised in such a way it can accept the only numeric or characters or both numeric of characters as well anything.Open the c# control project wha we developed previously and add a new class to it naming it as mytextbox.cs and write the following code in it.

using system,windows.Forms;
namespace inherited controls
{
public class mytextbox:TextBox
{
public ENUM options{Digits,Any,Chars,char or digit};
options opt=options.Any
public myTextbox()
{
This.keypress+=new KeyPressEventHandler (myTextBox-keypress);
}
private void mytextbox_keypress(object sender,keypressevent args e)
{
if(convert.toInt32(e.keychar==8)
return;
switch(opt)
{
case option.Digits;
if(char.IsDigit(e.keychar)==false)
{
messagebox.show("enter numbers only");
e.Handled=true;
}
break;
case options.cahrs
if(char.Isletter(e.keychar)==false)
{
{
messagebox.show("enter numbers only");
e.Handled=true;
}
break;
case options.cahrs or digit
if(char.Isletter or digit(e.keychar)==false)
{
{
messagebox.show("enter numbers and chars only");
e.Handled=true;
}
break;
} 
}
public option setoption
{
get{returns opt;}
set(opt= value;}
}
}
} 
} 

Saturday, January 28, 2012

Create custom Events and Delegates with c#

when part of user controls logic and part of forms logic need to be executed at one shot ,then user defied events are required.User defined events is called  as Callback procedure.For this we have to follow four steps to develop user defined events
1.create a delegate
2.Create a event wit the help of delegate
3.raise the event (call the event)
4.Define the event (write the body)
note:When developing the control,steps 1,2,&3 need to be fallowed.While using the control step four need to be followed
Hre i will shown an example for how to create events with delagates.In my application i have created a usecontrol and it has the option to load the data in when the ocntrol is loading.For this i have created a page load event .
 Load += new EventHandler(delegate(object PreRenderSender, EventArgs Evt) { if (ViewSet.GetActiveView() != Edit)GiveOutput(); });

protected void SetOutput()
 {
 }

Friday, January 27, 2012

How to use custom validator in asp.net

If all existing validation controls doesn't fulfill business requirements or validations then we can write our own logic and perform validations using validation control only.i.e custom validator.Custom validator can be used to perform validations in client and also to perform validations at server.Here i will given steps how to implementing custom validator at client side.

1.Place custom validator in the form and set the fallowing properties control to validate ,error msg client validation function
2.Go to source view and function with in the script tag.This function should have two arguments as CV will pass two arguments
ex:function fn(x,y)
{
}
second arguments provides 2 properties /value
i)Value ->provide the control value which custom validator is validating
ii)IsValid->bad which specifies whether validation is ok or not.
<script type="text\java script>
function checkmod(a,b){
if(b.value%10 ==0)
b.IsValid=true;
else
b.IsValid=false
}

Thursday, January 26, 2012

Jquery and how to declare variables

Here i will share some useful information about jquery($) variables,how to declare variables,how to pass the variables ,how to execute any script after the DOM loading will be completed and what is $ symbol in jquery.The $ symbol is used to initialize the jquery object.Now i will show how to the initialize jquery object.we can use the $ or Jquery to pass a selector ,because both will give same result
Jquery("#Id")
 or 
$("#Id")
In the above example i will get the id of the element using jquery object.We will have to know that most Javascript programmers are added some code to their program when the page is loaded.
window.onload = function(){ alert("Test Jquery"); }
When we try to run your code at page loading using JavaScript with onload function,it will execute after load images of the page.So To avoid this problem jquery gives a statement to check the page loading concept.

$(document).ready(function() {
      //logic

    }); 

Wednesday, January 25, 2012

Insert multiple rows using a single INSERT statement

The common thing That all have you done using Insert command is to insert the data into data base table .But the thing here is "can we store the data into multiple tables using single Insert command?".we can say surely "it can possible ". Recently i had a requirement to store the data into different tables using single INSERT query.Here i will show how to insert the data into multiple table using single select statement in sql

Example:
INSERT ALL
  INTO employee(empid, empname) VALUES (1, 'Developer')
  INTO Departments (Deptid, Deptname, category) VALUES (15, 'Information 
Technology', 'Computers')

 SELECT * FROM dual;
The above query will insert one row into the employee table and one row into the
Departments table.

Tuesday, January 24, 2012

"data not found" error in PLSQL

When we working with PLSQL statements some common errors will raise.In this one of the common Error in PLSQL is " data not found" .It will arise when there is no particular field in table. Here i will shown an example how to prevent the exception when a record is not found in PLSQL code.
Example:
select Id,Name, Address from Details where Address = City.Address;
Solution:
The above example give an error because of the record"Address" is not found.So for this we have to get the count of records then using the condition we will execute the PL/SQL code
select count(1) into testcount from Details where Address=city.Address;

if testcount>0 then 
select Id,Name, Address
from Details
where Address = City.Address;
end if;
R3MQ7XNAWTMR

Sunday, January 22, 2012

how to save image in database in asp.net


Here i will demonstrates how to upload image and then save into Sql data base in ASP.NET.application.For this i have taken a File Upload Control.button and grid view.Before going to insert the Image into Database i am checking the the file upload in empty or not.If it is not empty then go to insertion procedure

Code behind:
protected void btnImgUpload_Click(object sender, EventArgs e)
{
string strImg= txtImgName.Text;
if (ImgFileUpload.PostedFile != null && ImgFileUpload.PostedFile.FileName != "")
{
byte[] strImageSize = new byte[ImgFileUpload.PostedFile.ContentLength];
HttpPostedFile uploadImage = ImgFileUpload.PostedFile;
uploadImage.InputStream.Read(imageSize, 0, (int)ImgFileUpload.PostedFile.ContentLength);

SqlConnection cn=new SqlConnection("Userid=sa;Password=123;Database=employee");

try
{ 
cmd.parameter.clear();
cmd.Parameters.Add("@ImageName", SqlDbType.VarChar).Value = strImg.ToString();;
cmd.Parameters.Add("@Imagesize", SqlDbType.Image,imageSize.Length).Value = strImageSize; 
cn.Open();
cmd = new SqlCommand("SaveImagerecord", cn);
cmd.CommandType = CommandType.StoredProcedure; 
cmd.ExcuteNonQuery();
 
}
catch(exception ex)
{
messageBox.show(ex.message);
}
finally
{
cn.Close();
}
gvimages.DataBind();
}
}
Stored Procedure:
//stored procedure to insert the Images into  in Sqlserver Table
CREATE PROCEDURE SaveImagerecord

(
@ImageName VarChar(100),
@Imagesize byte
)

AS
INSERT INTO Images(ImageName,Imagesize)VALUES (@ImageName,@Imagesize);

Intersect and Except in sql server

These are called as Set operators.The set operators are used to perform mathematical set operations on the data available in the tables .To work with set of operations we need to write multiple select statements the data retrieved by each select statement will be treated as one set and then set operator are apply on those sets.Sql Server supports three set operators
INTERSECT: The set operator INTERSECT will written the values that are common in both the sets by eliminating duplicate values.Here i will show an example to find the jobs that are available in both the departments 40 and 30
select Job from emg where deptno=30
INTERSECT
select Job from emg where deptno=40
EXCEPT:
The set operator INTERSECT will written the values that are available in first but not in second set.Here i will show an example to find the jobs that are available in first
select Job from emg where deptno=30
EXCEPT
select Job from emg where deptno=40

Saturday, January 21, 2012

multiple row subqueries

When a sub query returns more than one row then that sub query is called as multi sub query.Here i will shown an example to find out the all customers who are having high sales
select *from Orders where sales in(select max sales)from Orders group by city no)
Any ans All:with the multi row sub query it is not possible to use the operators like equal(=),greater than(>),>=,<=,<.because these operators can be used only with single values.but there may be a situation where you have to use these operators with multi row sub queries and for this two predicates are provided Any or same and All The predicate any will return true when the given condition is true with any one value returned by multi row sub query and All will return true when the given condition is true with all values returned by the multi row sub query
Here i will given an example for getting highest sales in order
select *from Orders where sales =(select max sales)from Orders group by city no
)
Find out the emp who are not working in dept30 and whose Sal is more than any one employee working dept 30
select *from emp where deptno!=30 and Sal>Any (select distinct Sal from emp where dept no=30)
)

Tuesday, January 17, 2012

how to use Ispostback property in asp.net

It is one of the properties of Page Object.Page object is a reference of web page class object.This will be created by implicitly.The client request to web server [web page] can e classifieds two types
1.Ordinary Request
2.Post Back Request
Ordinary Request:When user is typing URL under address bar of browser ,to make a request,It is called Ordinary request
Post back Request:When user is interfacing with a control to make a request to web server.It is called Post Back request

Ispostback Properties
|
|
True->when the request is post back request
False->when the request is Ordinary request

This properties is useful to execute certain logic with in the page load event towards ordinary Ordinary Request
Default.aspx:
<button id="myButton" onclick="Btn_Click" runat="server" text="Click Me" type="submit"></button>
Example:
Protected void Page_Load(Object sender, EventArgs e)
 {
  if(page.Ispostback==false)
    {
      Response.Write("Ordinary Request);
      else
      Response.Write("Post Back Request); 
    }
  }
public void Btn_Click(Object sender,
                           EventArgs e)
{
 //logic
}
The post back can perform when click on the button .

Tuesday, January 10, 2012

Ranking functions in sqlserver

Ranking functions are used to generate a rank for the row based on values of a column of that row
RANK():Is used to generate the rank based on the values of a specified column.Here i will show an example by generating a rank for the employee based on the salary
SELECT empno,ename,sal,RANK() OVER(ORDER BY sal DESC)From eemp
While using the ranking functions it is compulsory to use OVER clause with ORDER BY rank will be generated based n the values in the column that is specified in order by clause with in the over clause.The RANK function will skip the next immediate ranks when more than one row share the same rank

DENSE_RANK():
This function will also generate a rank same as the rank function based on the values of column .That is specified in order by clause of over clause but unlike the rank function it will skip the next immediate ranks when more than one row share the same rank
Example:
SELECT empno,ename,sal,DENSE_RANK() OVER(ORDER BY salDESC)From eemp
While using the ranking function you may want to generate the rank by dividing the rows in to groups.In this case you need to use partitions by with in the over clause along with order by and partion by must be written first
SELECT empno,ename,,Deptnosal,DENSE_RANK() OVER(PARTITION BY deptno ORDER BY salDESC)From eemp
TOP n:Top n clause is used to retrieve only top n rows from the rows retrieved by select statement
SELECT TOP 4 cusno,cname,sales from emp orderby sales DESC
Top n clause supports the keyword "PERCENT" using which you can retrieve TOP n percent of rows instead of top n rows

Top n clause also supports the key word "WITH TIES" and this case it will retrieve all the rows in table that contain the same value is the column that is specified in order by same as last row retrieved by the top n clause
SELECT TOP 10 percent WITH TIES cno,cname,sales from customers ORDER BY sales DESC
Actually the above query has to written only the rows as the total no of rows in the table is 15 and we specify top 10 percent but displays 5 rows because there are 4 customers drawing the sales 4000 which is the sales of last employee retrieve with TOP 10 percent option

Monday, January 9, 2012

Tree view in asp.net using csharp

The control is used for displaying the information in hierarchical structure.
ex:solution explorer
you can construct a tree in two ways
1.manual construction using tree node editor
2.pragmatically construction

Manual construction using tree editor:

If you want to construct a tree using a tree node editor ,go to the properties of tree view and select nodes properties which displays you button beside it.click on it open tree node editor.Use the add root and add child buttons to adding the root nodes and child nodes according to requirements
Place a Tree view control on the form and construct the tree as fallowing using tree node editor
Dock Property:
Every control provides the property known as DOCK property which is used to specify the way the control has to be placed on the form .it takes any of 6 different values-->None,Left,Right,Top,Bottom,Fill

None:it is used a fixed width and height as well as uses fixed X and Y coordinating to place itself on the form which will not be changing all at the run time
if set as left,right,top or bottom the control sits on the selected option irrespective of the form size as well as adjusts according to the form size

if set as fill the control occupies the complete size of the form with out room for any other controls
Every node under a tree is referred by using it's index position as fallowing
Nodes[0]
Nodes[0].Nodes[0]
Nodes[0].Nodes[0].Nodes[0]
Nodes[0].Nodes[1]
Nodes[0].Nodes[1].Nodes[0]
Construct a tree view Pragmatically:

If you want to construct a tree view pragmatically we require to construct each node explicitly and add it user the tree view control using the node start add method
Nodes.Add(string text)
Place tree view control on the form and set DOCK property as left and write the fallowing code in the form load
TreeView1.Nodes.Add("Home");
TreeView1.Nodes[0].Nodes.Add("About");
TreeView1.Nodes[0].Nodes[0].Nodes.Add("Portfolio");
TreeView1.Nodes[0].Nodes.Add("Contact us");
TreeView1.Nodes[0].Nodes[1].Nodes.Add("Location");
TreeView1.ExapandAll();
Here i will show an example for tree view
Using System.IO;
namespace windowsproject
{
publec partial class Forms:Form
//form load
Treeview1.Nodes.Add("c://");
string[]florders=Directory.GetDirectoroies(c://")
foreach(string fpath in folders)
{
string fname=fpath.substring(3);
Treeview1.Nodes[0].Nodes.Add(fname);
}
Treeview1.ExapndAll();
}

Sunday, January 8, 2012

command builder in asp.net

Title:How to use Command builder in asp.net using c#.net
The command builder class is used to generate the SQL statements,command builder takes constructed parameter is data adapter depending on the data adapter columns ,generates SQL statement
Methods:

GetInsertCommand method:This method generates the insert statement
GetDeleteCommand method:This method generates the delete statement
GetUpdateCommand method:This method generates the update statement
here i will show an example to insert the rows using data table class.For this i have taken one grid view,two text box's and three buttons
Code behind:
Using System.Data.Oledb;

OleDbConnection cn=new OleDbConnection("provider=MSADAORA.1;serid=scott;password=tiger")
OleDbDataAdapter ad;
DataSet ds=new dataSet();
DataTable dt=new DataTable();
DataRow dr;
//button _click(bind the data to grid view)
{
ad1=new OleDbDataAdapter("select*from customers",con)
ad1.fill(ds,"c");
dt=ds.Tables["c"];
Gvcustomers.DataSource=dt;
}
//button2_click(add to Table rows using command builder)
{
OleDbCommandBuilder cbd=new OleDbCommandBuilder(ad1);
dr["cno"]=convert.Toint16(txt1.Text);
dr["cname"]=(txt2.Text);
dt.Rows.Add(dr);
ad1.InsertCommand=cbd.GetInsertCommand();

}
//button3_click(update using command builder)
{
ad1.Update(ds,"s");
}

Saturday, January 7, 2012

CREATE a table from another table in SQL Server

There may be a situation where you want to create a duplicate copy of an existing table .For this write a select statement with the fallowing syntax
select <column> into <newnametable> from <tablename>
Here i will show an example to creates a table with the name of customer from the table oldcustomers
select* into customer from oldcustomers
select*from customers

When you creates a new table from existing table then only columns and a data types will be copy but not the constrains and indexes

Insert Rows from One table to another:
To insert the rows from one table to another table and for this user can use insert statement with the fallowing statement
Insert into  select*from 
Insert into customers select cid,cname,cadd from oldcustomers

Create Temp table:
Select * into #orderstemp from orders

Friday, January 6, 2012

Identity in sql server

Identity is used to specify to automatically generate values for a column during insert.
IDENTITY [( seed , increment )]
seed is used to specify the starting value for the identity and increment is used ti specify how much increment to be done to generate a new value for the new row.The fallowing example creates a table with name Customers in which Identity is provided on Cid column
Create table Customers(Cid int PRIMARY KEY IDENTITY(1000,1),cname varchar(30),city varchar(20)
when identity was specified on a column then it is not possible to provide a value for that column manual and during insert you must exclude that column .The fallowing example insert the rows in to customer table
Insert customers(cname,city) values('AB','Hyderabad')
Insert customers(cname,city) values('Bc','New York')
Getting identity values:
To get the details of an identity like seed of the identity increment of the identity and current value of the identity use the fallowing set of functions
IDENT_SEED('customers ')
//returns the seed of the identity available on customers table 
IDENT_INCR('customers ')
//returns increment of the identity available on the customers  table
IDENT_CURRENT('customers ')
//returns current of the identity available on the customers  table

Thursday, January 5, 2012

OrderBy and GroupBy in LINQ

If you are familiar with SQL,You would know it can enable you to perform some relational operations like the data to be returned in a specific Order and get the summary values based on the rows in each group.Here the LINQ is provide the same functionality
OrderBy:
The OrderBy is used to retrieve the data in particular order.The OrderBY expects a method as its argument.This methods identifies expressions that you want to use to sort the data.
For this i will show an example to get names of each city in AllCountry array
IEnumerable citynames=Allcountry.OrderBy(acoun=>acoun.CityName).Select(City=>city.CityName)
List li=New List();
 foreach(string name in Country)
  {
         li.add(name);
  }
 foreach (string s in list) // Loop through List with foreach
  {
 Console.WriteLine(s);
  }
The OrderByDescending is get the data in descending order.Here there one method i.e ThenByDescending which is used for more than one key value
GroupBy:
The GroupBy method is used to group the data to common values in one or more Fields.The GroupBy method expects a methods that specify the fields to group the data
var citiesGroupByCountry= Allcountry.GroupBy(acoun=>acoun.Country);
foreach(var citiesPerCountry in citiesGroupByCountry)
{
 foreach(var citis in citiesPerCountry)
 {
   Console.Writeline(Country.CountyName);
 }
}

Wednesday, January 4, 2012

code access security in asp.net

Using code access security we can convert the normal string format data into the encrypted format,the encrypted format data we can convert into the decrypted format (or) normal string format the code access security .we can implement by importing system.Security.Cryptography name space .The code access security depending on the hexa decimal byte values and encoding class.As per Microsoft the standard hexadecimal byte values are ox01 to ox16
using encoding class we can convert the normal string format data into the byte format,the byte format data we can convert into the normal string format,this class defined in the system.text name space.

TripleDESCryptoServiceProvider:
The class is used to encrypt the data,decrypt the data this class is depending on the hexa decimal byte values and encoding class

methods in TripleDES cryption:
1.Create Encryptor
2.create Decryptor
3.Cryptostream
Here i will shown how to encrypt and decrypt using TripleDES in asp.net.For this i have taken two button,one is for encryption and other one is for decryption
Example:

//name spaces which we have to add 
Using System.Security.Cryptography;
Using System.Text;
Using System.Io;


byte[] k=new byte[]{0x01,0x02,0x03,0x04,0x04..0x16}
byte[] i=new byte[]{0x01,0x02,0x03,0x04,0x04..0x16}
//button1_click
FileStream fs=new FileStream("c:/test.txt",FileMode.Create);
TripleDESCryptoServiceProvider tds=new TripleDESCryptoServiceProvider();
CryptoStream cs=new CryptoStream(fs,tds.CreateEecryptor(k,i),CryptoStreamMode.Write);
byte[]data=Encoding.ASCII.GetBytes("The  welcome")
cs.write(data,o,data.lenth)";
cs.close();
fs.close();

//button2-click
FileStream fs=new FileStream("c:/test.txt",FileMode.Open);
TripleDESCryptoServiceProvider tds=new TripleDESCryptoServiceProvider();
CryptoStream cs=new CryptoStream(fs,tds.CreateDecryptor(k,i),CryptoStreamMode.Read);
byte[]data=new byte[1000];
int len;
len=cs.read(data,o,data.lenth);
string s=Encoding.ASCII.GetString(data,o,data.lenth)
messagebox.show(s);
cs.write(data,o,data.lenthe)";
cs.close();
fs.close();

Tuesday, January 3, 2012

compute by in sql server

Drawback of group by is we can display information from only those columns that are used in group by and not possible to display the information from other columns available in the table that are not used in group by.When you want to display information from the columns in the table that are not used for grouping while grouping the rows,use "compute by"
syntax:
select statement computeby
ex:Display complete details of orders along with total quantity transfer to customers
select*from orders compute sum(quantity)
Display complete details of orders along with total quantity transfer to customers
select*from orders orederby customerno  compute sum(quantity) by customerno
Rule:A rule to use compute by is the columns that are specified in compute by must be in order by

Monday, January 2, 2012

Retrieve current user permissions in SQL

To get the list of permissions available for the current user on a Db or an object in the Db,use the function"fn-my-permissions".This function takes arguments,name of the DB or object and whether the first argument you specified is a DB or an object .
The fallowing example gets the DB level permissions on the DB for the current user
select *from fn-my-permissions('My DB','Database')
The fallowing example gets the object level permissions on orders table for the current user
select *from fn-my-permissions('orders','object')

Sunday, January 1, 2012

On-fly windows in Asp.net

If we want to create a window with no source file as it's content then we have to implement on-fly window concept(blank windows)This type of windows content is populated completely based on other programmer statements.The blank windows are not useful but by adding the reference to this blank window we can populate dynamic content .Here i will show how to create the blank window using java script.In java script we use same open method but this time with out file name and assign they open statement result to js variable.

on-fly windows in javacript

<form nane="form1">
username=<input name="t1" />
password=<input name="t2" />
<input name="b1" onclick="fly()" type="button" value="Click me" /> </form>
<script language="javascript">
function fly()
{
x=open("");
x.document.write("<h1>

welcome");
x.document.write("<img src=wondor.gif>");
}
</script>
//Here i will given more example script for area is covered on not.This can be use in above fly() method
x.document.write("welcome"+document.form.t1.value);

 x.document.write("<img src="http://www.blogger.com/wondor.gif" />");
 if(document.form.t2.value="12345")
 {
x.document.write("<img src="http://www.blogger.com/wondor.gif" />");
 x.document.write(" Area covered");
 }
 else
 {
 x.document.write("<img src="http://www.blogger.com/wondor.gif" />");
 x.document.write(" Area not covered");
 }
 }
The above on fly windows code create a blank window and populate static dynamic and decision content.Area not cover is decision base welcome is static username image is dynamic
Note:If you want to display the result in current window just do a small modification as below
this.document.write instead of x.document.write

Bel