Friday, August 20, 2010

Introduction to LINQ (Language Integrated Query) in C#

Introduction to LINQ (Language Integrated Query)


 Language Integrated Query (LINQ) is Microsoft's new technology for powerful, general purpose data access


 LINQ is a uniform programming model for any kind of data. LINQ enables you to query and manipulate data with a consistent model that is independent from data sources.

 LINQ is just another tool for embedding SQL queries into code


 This toolset can be used to access data coming from in-memory objects (LINQ to Objects), Databases (LINQ to SQL), XML documents (LINQ to XML), a file-system, or any other source.


 Query expressions start with the keyword from, and are written using SQL-like query operators such as Select, Where, and OrderBy:


 Every query starts with a from clause and ends with either a select clause or a group clause. The reason to start with a from clause instead of a select statement, as in SQL syntax, is related to the need to provide Microsoft IntelliSense capabilities within the remaining part of the query, which makes writing conditions, selections, and any other LINQ query clauses easier. A select clause projects the result of an expression into an enumerable object. A group clause projects the result of an expression into a set of groups, based on a grouping condition, where each group is a numerable object.


 LINQ works on collections that implement IEnumerable.

Enums in C#

Enums in C#


Enums are basically a set of named constants. i.e. these are basically a group of named constants defined under a common name.
Enums are value types and are created on the stack and not on the heap.

Eg:

using System;
public enum Colors
{
red,
green,
blue,
}


public class Mainclass
{
public static void Main()
{
string color = Colors.red.ToString();
Console.WriteLine("Color is:" + color);
int id = (int)Colors.blue;
Console.WriteLine("Color value:" + id);
}
}


Each enum type has a corresponding value type called underlying type of the enum type.

Unsafe Code ( Using Pointer) in C#

Unsafe Code ( Using Pointer in C#)

C#.NET hides most of memory management, but in some cases we need direct access to the memory, then unsafe code is used.


Eg:
using System;
class Mainclass
{
public static void Main()
{
int a = 5;

unsafe
{
int* ptr;
ptr = &a;
*ptr = 20;
}
Console.WriteLine("a = " + a);
}
}



Eg:

using System;
unsafe class Mainclass
{
public static void Main()
{
int a = 5;
int* ptr;
ptr = &a;
*ptr = 20;


Console.WriteLine("a = " + a);
}
}

Thursday, August 19, 2010

Parameter Arrays in C#

Parameter array.


Parameter arrays allows us to pass a variant  number of arguments into a method. All incoming arguments will consider as a single dimensional array. Have a look on the following example.
using System;


class Mainclass
{
public static void Main()
{
Test obj = new Test();
obj.Add(10, 20);
obj.Add(10, 20, 30);
obj.Add(1, 2, 3, 4, 5, 6);
}
}


class Test
{
public void Add(params int[] ar)
{
int sum = 0;
foreach (int i in ar)
{
sum = sum + i;
}
Console.WriteLine("Sum : " + sum);
}
}

Reference Parameters in C#

Reference Parameter


These are input/output parameters; they can be used for passing value into a function as well as to get back value from a function.

using System;
class Test
{


public void Inc(ref int a) // here a is a reference parameter. It refer the same memory address of passing arguement.
{
a = a + 10;
Console.WriteLine(a);
}
}



class Mainclass
{
public static void Main()
{
int x = 10;
Test obj = new Test();
obj.Inc(ref x); // arguement x and parameter a will be using the same memory reference.
Console.WriteLine("From Main " + x);
}
}

Output Parameters in C#

Output Parameter


A function can return only a single value. But when we using output parameters it is possible to return multiple values.
Note: output parameters must be assigned with value before leaving method, otherwise it will results in a compilation error.
Eg

using System;
class Test
{


public void Cal(int a, int b, out int c, out int d) // a and b are input parameters. c and d are output parameters.
{
c = a + b;   // set value for output parameter c.
d = a - b;   // set value for output parameter d.}


}

class Mainclass
{
public static void Main()
{
int n1 = 10, n2 = 30, sum, dif;
Test obj = new Test();
obj.Cal(n1, n2, out sum, out dif);
Console.WriteLine("Sum is {0} and Difference is {1} ", sum, dif);
}
}

Input Parameters in C#

Input Parameter


It is used to receive values, means it just pass values.

e.g

using System;
class Test
{
public void Increment(int a) // here a is an input parameter it just takes value from the Main method.
{
a = a + 10;
Console.WriteLine("a=" + a);
}
}


class MainClass
{
public static vod Main()
{
int x = 10;
Test obj = new Test();
obj.Increment(x); // passing value into the method.
Console.WriteLine("x=" + x);
}
}

Partial Class in C#

Partial class:


It is possible to split the definition of a class over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.

Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

Eg;

using System;
partial class Test
{
private int x;
}


partial class Test
{
public Test()
{
x = 10;
}
}


partial class Test
{
public void Print()
{
Console.WriteLine("X is : {0}", x);
}
}

class Mainclass
{
public static void Main()
{
Test obj = new Test();
obj.Print();
}
}

Using a LinearGradientBrush in Silverlight

Using a LinearGradientBrush


LinearGradientBrush elements are similar to the SolidColorBrush. They define a linear gradient that flows between two or more colors. You can apply them to the properties of Silverlight controls the same way that the SolidColorBrush is applied.

To apply a LinearGradientBrush to a Silverlight control, you need to define the Linear- GradientBrush element and give it an EndPoint and a StartPoint that define the linear direction of the brush. The EndPoint and StartPoint are set on a 0 to 1 coordinate system separated by a comma.

Then you need to define two or more GradientStop elements inside the LinearGradient- Brush. Each GradientStop element needs the Color property set. You can also define the offset between 0 and 1 where that color is set using the Offset property. Silverlight applies the gradient linearly along the path defined by the StartPoint and EndPoint values matching the colors at each GradientStop along the way.

Eg:

< Rectangle Width="200" Height="200" Stroke="Black" >
< Rectangle.Fill >
< LinearGradientBrush StartPoint="0.0 0.0" EndPoint="0 1" >
< GradientStop Color="Red" Offset=""/ >
< GradientStop Color="Green" Offset="0.33"/ >
< GradientStop Color="Blue" Offset="0.67"/ >
< /LinearGradientBrush >
< /Rectangle.Fill >
< /Rectangle >

Eg:

< TextBlock Height="100"
TextAlignment="Center"
FontSize="30" >
< Run Text="Linear Gradient brush" >
< Run.Foreground >
< LinearGradientBrush >
< GradientStop Color="Blue" Offset=".3"/ >
< GradientStop Color="Red" Offset=".5"/ >
< GradientStop Color="Green" Offset=".8"/ >
< /LinearGradientBrush >
< /Run.Foreground >
< / Run >
< /TextBlock >

Adding a SolidColorBrush in Silverlight

Adding a SolidColorBrush


The SolidColorBrush is the most common type that you can apply to Silverlight objects. A SolidColorBrush is automatically created for you when you set the color in one of the properties of a Silverlight object. For example, the following code automatically creates a SolidColorBrush implicitly for the Background property of a Canvas control:

< Canvas Background="Lavender"
Height="200"
Width="200" >
< / Canvas >

The previous code could also be written explicitly as follows:

< Canvas Height="200"
Width="200" >
< Canvas.Background >
< SolidColorBrush Color="Lavender"/ >
< /Canvas.Background >
< /Canvas >

Adding the SolidColorBrush explicitly takes considerably more code; however, you can set some additional properties of the SolidColorBrush element to enhance the look and feel of the control. For example, you can make the SolidColorBrush appear semitransparent by setting the Opacity property, as shown in the following code:

< Canvas Height="200"

Width="200" >
< Canvas.Background >
< SolidColorBrush Color="Red" Opacity=".3"/ >
< /Canvas.Background >
< /Canvas >

Understanding the Silverlight Presentation Framework

Understanding the Silverlight Presentation Framework


The main purpose of the Silverlight presentation framework is to provide you with the UI controls and functionality to implement rich Internet applications. However, the presentation framework is much more than just the UI controls; it also encompasses browser interaction, threading, and system calls.

Namespaces that are part of the Silverlight presentation framework are:

System.Windows:

Provides the general presentation and base classes for Silverlight development. For example, the Application, UIElement, EventTrigger, and FontStyles.

System.Windows.Browser:

Provides the classes used to interact with the browser. For example, the HtmlDocument, HtmlElement, HtmlPage, and ScriptObject.

System.Windows.Controls:

Provides most of the UI controls. For example, TextBlock, Image, Grid, and UserControl.

System.Windows.Documents:

Provides the classes that support basic document concepts. For example, Fontsource, LineBreak, Inline, and Run.

System.Windows.Markup:

Provides the classes that support XAML processing. For example, XamlReader, ContentPropertyAttribute, and XmlLanguage.

System.Windows.Media:

Provides the classes that enable you to apply rich functionality to your applications. For example, GradientBrush, ScaleTransform, Colors, FontFamily, and PathGeometry.

System.Windows.Media. Animation:

Provides the classes used to animate Silverlight controls. For example, Begin Storyboard, Storyboard, DoubleAnimation, SplinePointKeyFrame, Timeline, and TimeLineMarker.

System.Windows.Shapes:

Provides the classes used to implement basic XAML shapes. For example, Ellipse, Path, and Rectangle.

System.Windows.Threading:

Provides the classes used to implement threads in your Silverlight applications. For example, Dispatcher, DispatcherOperation, and DispatcherTimer.

System.ComponentModel:

Provides the classes used to implement runtime and design-time behavior of components and controls. For example, ProgressChangedEventArgs, PropertyChangedEventArgs, BackgroundWorker, AsyncCompletedEventArgs, and TypeConverter.

Implementing Data Binding in Silverlight Applications

Implementing Data Binding in Silverlight Applications


An extremely useful feature of Silverlight is the ability to bind properties of Silverlight controls to data sources. When the values of the data sources change, the property values of the controls change as well.

Data binding can be implemented as one-time, one-way, or two-way. One-way data binding only changes the value of the control based on the data source. In two-way binding, if either the control value or the source value changes, the other is updated as well.

To implement data binding in XAML code, you first need to implement a Binding statement encased in {} brackets in place of the property value. The Binding statement uses the following syntax:

{Binding < value >, < options >}

The value setting in the Binding statement is the property of the data source that is used to fill in the value for the control property. You can also specify the following options in the Binding statement:

 Converter: Specifies the converter object that is called by the binding engine to modify the data as it is passed between the data source and target property

 ConverterCulture: Specifies the culture used by the converter to implement conversion of data

 ConverterParamter: Specifies a parameter that can be passed to the converter

 Mode: Specifies whether the data flow in the binding is one-way or two-way.

 Source: Specifies the source object for the binding

The Binding statement tells the control only what property of the data source the value is bound to. You also need to set the value of the DataContext property of the control to assign a specific object as the data source.


To implement a class as a data source, the class must implement the INotifyProperty Changed interface and have an event of type PropertyChangedEventHandler named PropertyChanged.


The DataContext property is inheritable by child elements in the Silverlight application. If you have several controls that are bound to the same data source, then you can group those controls in a parent container such as a Canvas or Grid and then set the DataContext property of the parent. The data context flows down to the children without the need to set the property for each child.

Eg:
 
< TextBox Height="24" HorizontalAlignment="Left" Margin="60,72,0,0" VerticalAlignment="Top" Width="150" Text="{Binding Name, Mode=TwoWay}" TextWrapping="Wrap" x:Name="txtName" / >
 
 
write the following code
 
public class Employee : INotifyPropertyChanged

{
string name;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyChange(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}

public string Name
{
set
{
name = value;
NotifyChange("Name");
}
get
{
return name;
}
}
}


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

public partial class Page : UserControl

{
Employee emp;


public Page()
{
InitializeComponent();


emp = new Employee{ Name = "Jobin John" };


LayoutRoot.DataContext = emp;


}
}
}


Hope its Helpfull for silverlight programmers.......

Wednesday, August 18, 2010

Perform Editing and Deleting with GridView Control

Editing and Deleting with GridView Control
Follow the following steps
  • First you place a GridView Control on the web form.
  • Under Add/Edit Column window, add apropriate columns ( I have added BoundColumns) to display data. Set its DataField property too.
  • Set AutoGenerateEditButton and AutoGenerateDeleteButton property into true.
  • Set GridView's apropriate events.
I have used Employee table to demonstrate this example. It has EmpId, Name, JobTitile and Salary columns.

public partial class GridViewAllCode : System.Web.UI.Page

{
SqlConnection con;
SqlCommand cmd;
DataTable dt;
SqlDataAdapter adp;


protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+Server.MapPath("App_Data")+"\\jobin.mdf"+";Integrated Security=True;User Instance=True");
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
if (!IsPostBack)
BindGrid();
}


private void BindGrid()
{
adp = new SqlDataAdapter("select * from Employee", con);
dt = new DataTable("Emp");
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex =-1;
BindGrid();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name=((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string jobTitle=((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
int salary = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
cmd.CommandText = "update Employee set Name='" + name + "', JobTitle='" + jobTitle + "', Salary=" + salary + " where EmpId=" + empId;
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
BindGrid();
}


protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empId = int.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
cmd.CommandText = "delete Employee where EmpId=" + empId;
cmd.ExecuteNonQuery();
BindGrid();
}
}

Exporting a Server Control into Microsoft Excel Format

Exporting a Server Control into Microsoft Excel

public void DownLoad(string strFileName)
{
HttpContext.Current.Response.ClearContent();



HttpContext.Current.Response.Buffer = true;


HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);


HttpContext.Current.Response.ContentType = "application/ms-excel";


HttpContext.Current.Response.Charset = "";


StringWriter sw = new StringWriter();


HtmlTextWriter htw = new HtmlTextWriter(sw);
 
Panel1.RenderControl(htw); // here u can use gridview, panel etc.....



HttpContext.Current.Response.Write(sw.ToString());


HttpContext.Current.Response.End();
}
 
 
 
public override void VerifyRenderingInServerForm(Control control)  // u must put this method on the code behind page.

{
}

Sending Emails using Gmail User Account in Asp.Net

To send an email you can use System.Net.MailMessage class.  The following example demonstrates how to send an email using your own Gmail user account.

MailMessage mailMsg = new MailMessage();

mailMsg.From =new MailAddress( yourmail@domain.com);
mailMsg.To.Add( jobinjohn@live.com);
mailMsg.Subject = "Hai";
mailMsg.Body = "Chumma";
mailMsg.Priority = MailPriority.High;
SmtpClient c = new SmtpClient("smtp.gmail.com",587); // or u can use port 465
NetworkCredential cred = new NetworkCredential("username", "password"); //ur account username and password to authenticate your request.
c.Credentials = cred;
c.EnableSsl = true;
try
{
c.Send(mailMsg);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Tuesday, August 17, 2010

Working with Configuration Files in C#

Configuration


A common issue when developing applications is how to retrieve configuration information, such as database connection strings, event log names, or other parameters.

The System.Configuration namespace provides the functionality for reading configuration files.

The location for application settings depends on the type of application you are creating. For web applications, settings are stored in the web.config, in console or WinForms gui applications, settings are stored in app.config file.

appSettings Section

An application configuration file follows a specific XML schema. The appSettings section is a predefined section of the configuration file designed to make it very easy to retrieve a value based on a given name. This is the easiest way to add application-specific settings into an application configuration file. The appSettings section of the configuration file consists of a series of "add" elements with "key" and "value" attributes.

Eg: Create a console application and add app.config file.

< configuration >< appSetting s>
< add key="SourceFile" value="d:\test\source.txt" / >
< add key="DestinationFile" value="d:\test\destination.txt" />
< /appSettings>
< / configuration >

--------

string source = ConfigurationSettings.AppSettings["SourceFile"];
string dest = ConfigurationSettings.AppSettings["DestinationFile"];
Console.WriteLine(source);
Console.WriteLine(dest);

Or

NameValueCollection nvc = ConfigurationManager.AppSettings;
Console.WriteLine(nvc["SourceFile"]);
Console.WriteLine(nvc["DestinationFile"]);

Eg:

< connectionStrings >
< add name="MyConnetion" providerName="System.Data.SqlClient" connectionString="data source=.\sqlexpress;initial catalog=MYDB;integrated security=true" / >
< / connectionStrings >

string constr = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
Console.WriteLine(constr);

Or

ConnectionStringSettingsCollection coll = ConfigurationManager.ConnectionStrings;
foreach (ConnectionStringSettings cs in coll)
{
if (cs.ProviderName == "System.Data.SqlClient")
{
Console.WriteLine(cs.ConnectionString);
}
}

Monday, August 16, 2010

Create and alter Tables

Create and alter Tables:


A table is a repository for data, with items of data grouped in one or more columns. Tables contain zero or more rows of information.

Eg: Creating tables
CREATE TABLE Student
(
rollNo INT,
name VARCHAR(50),
mark1 INT,
mark2 INT
)
 
Altering tables:


If we need to change the definition of a table after creating it, we can use the ALTER TABLE statement.
We can use ALTER TABLE to add additional columns to a table, remove columns from the table, add and remove constraints, disable and enable constraints and disable and enable triggers.

Eg:
ALTER TABLE Student

ADD Total INT

ALTER TABLE Student
DROP COLUMN Total

Jagged array in C#

Jagged array:


A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays".

Declaration:       int[][] array;


Initialization:      array=new int[3][];
                        array[0]=new int[2];
                        array[1]=new int[5];
                        array[2]=new int[3];

 
Eg:
 
using System;

class jaggedarray
{
int[][] ja;


public void Accept()
{
Console.WriteLine("Enter the size of jagged array :");
int jsize = Convert.ToInt32(Console.ReadLine());
ja = new int[jsize][];
for (int i = 0; i < jsize; i++)
{
Console.WriteLine("Enter size of Single dimension array ");
int ssize = Convert.ToInt32(Console.ReadLine());
ja[i] = new int[ssize];
Console.WriteLine("Enter {0} elements ", ssize);
for (int j = 0; j < ssize; j++)
{
ja[i][j] = Convert.ToInt32(Console.ReadLine());
}
}
}


public void Display()
{
Console.WriteLine("Jagged Array Is :");
foreach (int[] a in ja)
{
foreach (int n in a)
{
Console.Write(n + "\t");
}
Console.WriteLine();
}
}
}


class Mainclass
{
public static void Main()
{
jaggedarray obj = new jaggedarray();
obj.Accept();
obj.Display();
}
}

Performing site navigation in Asp.Net

Performing site navigation


Page navigation is the process of moving between one actual page of your Web site and another.
There are many ways to navigate from one page to another in ASP.NET.

Client-side navigation: Client-side code or markup allows a user to request a new Web page. Your client code or markup requests a new Web page in response to a client-side event, such as clicking a hyperlink or executing JavaScript as part of a button click.

Cross-page posting: A control and form are configured to PostBack to a different Web page than the one that made the original request.

Client-side browser redirect: Server-side code sends a message to the browser, informing the browser to request a different Web page from the server.

Server-side transfer: Server-side code transfers control of a request to a different Web page.