Friday, November 12, 2010

Solving Request.Files.Count is 0 in mvc

Solving problem while uploading files in ASP.NET MVC 2

You should set both name and id attributes for fileupload control.

You should set enctype attribute of form element into multipart/form-data

Try your self uploading file.

See the following Example for more details

<form method="post" enctype="multipart/form-data" action="MyController/Upload">
    <input type="file" class="file" id="File1" name="File1" />
    <input type="submit" id="Submit1" class="btn80" value="Upload" />
</form>



public ActionResult Upload()
{
    foreach (string upload in Request.Files)
    {
        var file = Request.Files[upload];
        string filePath = "C:\\Temp\\" + DateTime.Now.Ticks.ToString() + file.FileName;
        file.SaveAs(filePath);
                  
    }
    return View();
}

Thursday, October 28, 2010

Javascript callback with parameter

Javascript delegates with parameter:

Here is one example for calling a javascript function using a delegate ( function pointer ) .

While calling a method using delegate, you should use the first parameter as 'this' (or an object), after that you can pass additional parameters.

For more details see the following example.

Eg:

pass a function as parameter.

do_AjaxPostWithData(url,function (str) { });


the following function calls the delegate with a parameter.
function do_AjaxPostWithData(actionUrl, callback) {

callback.call(
 
this,context.responseText);

}

Wednesday, September 29, 2010

Defining Structural Contracts

Defining Structural Contracts
Data Contracts:

Data contracts are the contractual agreement about the format and structure of the payload data (that is, the SOAP body) in the messages exchanged between a service and its consumer.
Data contracts are the preferred WCF way to enable serialization of complex types included in operation signatures, either as parameters or as return values.

Using a data contract, you can specify exactly how the service expects the data to be formatted as XML. The data contract is used by a data contract serializer in WCF client applications to describe how to serialize the data for parameters into XML, and by a data contract serializer in the service to deserialize the XML back into data values that it can process. Values returned by a service are similarly serialized as XML and transmitted back to the client application, which deserializes them.


DataContract Attribute
The DataContract Attribute, defined in the System.Runtime.Serialization namespace, is used to declare a type as a Data contract.
It can be applied to enums, structs, and classes only.


DataMember Attribute
The DataMember Attribute, also part of the System.Runtime.Serialization namespace, is applied only to members and is used to declare that the member should be included in the serialization of the data structure.


EnumMember Attribute
The final Data contract–related attribute to consider is the EnumMemberAttribute. As the name suggests, it is used to declare that a given element of an enum that has been declared with a DataContractAttribute should be considered as part of the Data contract.

Eg: Create a WCF Service and write the following code in the IService.cs file.

[ServiceContract]
public interface IService
{
    [OperationContract]
    Employee GetEmployee();
}

[DataContract]
public class Employee
{
    string name, job;
    [DataMember]
    public string Name
    {
        set { name = value; }
        get { return name; }
    }
    [DataMember]
    public string Job
    {
        set { job = value; }
        get { return job; }
    }
}

Write the following code in the Service.cs

public class Service : IService
{
    public Employee GetEmployee()
    {
        Employee emp = new Employee
        {
            Name = "Jobin John",
            Job = "Software Eng"
        };
        return emp;
    }
}


Add a new website to Solution. Place a button and write the following code.

        protected void btnDisplay_Click(object sender, EventArgs e)
        {
            EmployeeServiceReference.ServiceClient client = new WebApplication1.EmployeeServiceReference.ServiceClient();

            EmployeeServiceReference.Employee emp = client.GetEmployee();
            Response.Write("Name : " + emp.Name);
            Response.Write("
Job : " + emp.Job); }

Returning Views in MVC Application

Create an ASP.NET MVC 2 empty application. Add a controller named HomeController and write the following action method.

public ViewResult Index()
        {
            return View();
        }


 

ActionResult Class:

All methods within a controller are Action methods, and returns ActionResult object.

The above function returns ViewResult
object; which is a subclass of ActionResult

Adding View:

    Right click in the method and select add view option. Name the View as "Index" and add the view.

Run the application. Hence you have created an MVC application which returns a View.

jQuery Selectors: Select elements using Id

Selecting HTML elements with Id.

syntax:
$("#elementid")

The # selector selects an element with a unique id.

eg:
write the following in html head section
<script type="text/javascript">
$(
}
function DisplayAll() {"#divDetails").text("Welcome to my first jQuery application.");</script>

write the following in the body.

<div id="divDetails"></div><hr />
<div></div><hr /><div></div><hr /><div></div><hr />

Tuesday, September 14, 2010

Using jQuery Selectors : Using tag name

Using jQuery Selectors
  tag name, ID, and class. They can be used either on their own or in combination with other selectors.             
Three building blocks of selectors are

Selecting HTML elements with tag name.


The following example demonstrates how to select all div elements and assign a text value into it within  an HTML page.
syntax:
 $(element name)  : which returns all matched html elements.
 $('element name').text('text to display'); : which assign the text value into all matched element.
Eg:
Add following in html head

<script type="text/javascript">
$(
}
function DisplayAll() {"div").text("Welcome to my first jQuery application.");</script>
Add following in html body

<input id="Button1" type="button" value="Display Text onclick="DisplayAll()" /><div></div><hr />
<div></div><hr /><div></div><hr /><div></div><hr />

Introduction to jQuery & What jQuery does

Introduction to jQuery

jQuery is a library of JavaScript Functions, ie; a group of built-in javascript function to improve the interaction with web development.

Using jQuery you can do the following:
  • Simplify common JavaScript tasks
  • Access HTML elements in a document
  • HTML element manipulation
  • Modify the appearance of a web page
  • Manipulate CSS properties 
  • Alter the content of a document
  • Respond to a user's interaction
  • Animate changes being made to a document. 
  • Retrieve information from a server without refreshing a page ( AJAX).
  •  

Thursday, September 9, 2010

First MVC 2 Application with Visual Studio 2010

Creating your First MVC Application with Visual Studio 2010

Eg: Follow the following steps.

  • Create an empty MVC 2 web application.


  • Add a controller named HomeController and write the following method.
public string Index()
{
  return "My first MVC Application";
}

  • Run the application.

The above application just returns a string value. We dont have any view. The browser will display only a string.

ASP.NET MVC Folder Conventions

ASP.NET MVC Folder Conventions


App_Data : Contains database files. For example, the App_Data folder might contain a local instance of a SQL Server Express database.

Content : Contains static content such as images and Cascading Style Sheet files.

Controllers : Contains ASP.NET MVC controller classes.

Models : Contains ASP.NET MVC model classes.

Scripts : Contains JavaScript files including the ASP.NET AJAX Library and jQuery.

Views : Contains ASP.NET MVC views.

Introduction to MVC 2 with Visual Studio 2010

Microsoft MVC 2 in Visual Studio 2010


The Microsoft ASP.NET MVC framework is Microsoft’s newest framework for building web applications. The ASP.NET MVC framework was created to support pattern-based software development. In other words, the framework was designed to make it easier to implement software design principles and patterns when building web applications.

An MVC application, a Model View Controller application, is divided into the following three parts:

• Model: An MVC model contains all of an application’s logic. The model includes all of an application’s validation logic, business logic, and data access logic.

• View: An MVC view contains HTML markup and view logic.

• Controller: An MVC controller contains control-flow logic. An MVC controller interacts with MVC models and views to control the flow of application execution. which handle incoming requests, perform operations on the domain model, and choose a view to render back to the user

Tuesday, September 7, 2010

Adding a VideoBrush in Silverlight

Using a VideoBrush in Silverlight Application


VideoBrush elements are very similar to the ImageBrush. Instead of an image, they define a video MediaElement that is applied as a brush. You can apply them to the properties of Silverlight controls the same way that the ImageBrush is applied.

To apply a VideoBrush to a Silverlight control, you need to define the VideoBrush element just as you do with an ImageBrush. However, different from an ImageBrush, you need to set a SourceName property that points to the x:Name of the MediaElement. Therefore, you also need to define a MediaElement separate from the Silverlight control. If you do not want the video to be displayed outside of the Silverlight control, set the Opacity property of the MediaElement to 0.

Eg:

< MediaElement Source="first.wmv"
x:Name="movie"
Opacity="0"/ >


< TextBox Height="100" Width="150" >
< TextBox.Background >
< VideoBrush SourceName="movie" Stretch="UniformToFill"/ >
< /TextBox.Background >
< /TextBox >

Adding an ImageBrush in Silverlight

Using an ImageBrush in Silverlight Application


ImageBrush elements are similar to the SolidColorBrush. Instead of a solid color, they define an image that is applied as a brush. You can apply them to the properties of Silverlight controls the same way that the SolidColorBrush is applied.

To apply an ImageBrush to a Silverlight control, you need to define the ImageBrush element and set the ImageSource property to an image that has been added to the project. You will likely want to set the Stretch property so that the image appears appropriately in the control.

Eg:

< TextBox Height="200" Width="150" >
< TextBox.Background >
< ImageBrush ImageSource="jobin.jpg"/ >
< /TextBox.Background >
< /TextBox >

Monday, August 30, 2010

Computed Columns

Computed columns in Microsoft SQL Server:


A computed column is based on an expression defined when you create or alter the table, and is not physically stored in the table unless you use the PERSISTED keyword.

A computed column is one defined to be an expression that is executed whenever the column is retrieved. If we use the PERSISTED keyword the expression is being executed while we insert or modify a row.

Syntax:

column_name AS computed_column_expression [ PERSISTED ]


Eg: Non-persisted computed column

CREATE TABLE Student
(
RollNo INT IDENTITY PRIMARY KEY,
Name VARCHAR(25),
Mark1 INT,
Mark2 INT,
Total AS Mark1+Mark2
)


Eg: Persisted computed column

CREATE TABLE Student
(
RollNo INT IDENTITY PRIMARY KEY,
Name VARCHAR(25),
Mark1 INT,
Mark2 INT,
Total AS Mark1+Mark2 PERSISTED
)

Thursday, August 26, 2010

Using RadialGradientBrush in Silverlight

Adding a RadialGradientBrush


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

To apply a RadialGradientBrush to a Silverlight control, you need to define the Radial- GradientBrush element. You can define the center of the gradient radius using the GradientOrigin property. The GradientOrigin is set on a 0 to 1 coordinate system separated by a comma.

You can also define the radius of the gradient in the X and Y planes using the RadiusX and RadiusY properties. These properties are set on a scale where 1 is the Height or Width of the Silverlight control.

Then you also need to define two or more GradientStop elements inside the Radial- GradientBrush. 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 on a radius centered at the GradientOrigin and defined by the RadiusX and RadiusY properties matching the colors at each GradientStop along the way.

Eg:

< Rectangle Height="200" Width="200" >


< Rectangle.Fill >


< RadialGradientBrush >


< GradientStop Color="Blue" />


< GradientStop Color="White" Offset=".5" / >


< GradientStop Color="Blue" Offset=".9"/ >


< /RadialGradientBrush >


< /Rectangle.Fill >


< /Rectangle >



Eg:

< Rectangle Height="200" Width="200" >


< Rectangle.Fill >


< RadialGradientBrush GradientOrigin="0,0" >


< GradientStop Color="Blue"/ >


< GradientStop Color="White" Offset=".5"/ >


< GradientStop Color="Blue" Offset=".9"/ >


< /RadialGradientBrush >


< /Rectangle.Fill >


< /Rectangle >



Eg:

< Rectangle Height="200" Width="200" >


< Rectangle.Fill >


< RadialGradientBrush GradientOrigin=".5,.5" RadiusX=".6" RadiusY=".2" >


< GradientStop Color="Blue"/ >


< GradientStop Color="White" Offset=".5"/ >


< GradientStop Color="Blue" Offset=".9"/ >


< /RadialGradientBrush >


< /Rectangle.Fill >


< /Rectangle >

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.

Friday, August 13, 2010

Read & Write operations using Console class

Console Class:


In this class we use two important methods named WriteLine() and ReadLine(). This class contained in the System namespace.

Eg: Print a message

class WriteString
{
public static void Main()
{
   System.Console.WriteLine("Welcome to C#.")
}
}

Eg: read a string

using System;
class WriteString
{
public static void Main()
{
   Console.WriteLine("Enter a string ");
   string str = Console.ReadLine();
   Console.WriteLine("You entered = " + str);
}
}

WriteLine() pumps a text string to the output stream. ReadLine() allows you to receive information from the input stream. The ReadLine(0 method returns a string value.

Thursday, August 12, 2010

Attaching detaching Databases

Attaching detaching Databases


At times, you may want to move an entire database- including all of its objects data, and log files- to another SQL server machine. To do this, SQL server enables attaching and detaching databases.

Eg: Detach

SP_DETACH_DB 'DBTEST'

Eg: Attach

SP_ATTACH_DB 'DBTEST','E:\jobin\database\DBTESTDATA.mdf','E:\jobin\database\DBTESTLOG.ldf'

Reserved CommandName values

GridView Control's Reserved CommandName values and its Description

Cancel :  Cancels an edit operation and returns the GridView control to read-only mode. Raises the    RowCancelingEdit event.


Delete : Deletes the current record. Raises the RowDeleting and RowDeleted events

Edit : Puts the current record in edit mode. Raises the RowEditing event,

Page : Performs a paging operation. Sets the CommandArgument property of the button to "First", "Last", "Next", "Prev", or a page number to specify the type of paging operation to perform. Raises the PageIndexChanging and PageIndexChanged events

Select: Selects the current record. Raises the SelectedIndexChanging and SelectedIndexChanged events.

Sort: Sorts the GridView control. Raises the Sorting and Sorted events.

Update : Updates the current record in the data source. Raises the RowUpdating and RowUpdated events.

Custom Sorting with GridView Control | Handling GridView Sorting Event

Custom Sorting with GridView Control, Handling GridView Sorting Event

Bind a grid, and Set SortExpresion property for the particular field to be sortable (Eg, BoundField).
In the following example coulmn name is assigned to SortExpression property. I have a table with column with country; I need to sort records in ascending and descending order based on the country.

In the following example you can see three methods:

1. GridView1_Sorting :  GridView's Sorting event handling method.

2. Sort : implementation of sort logic

3. ManageViewState : To keep current sorting order.


#region Sort




protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
   Sort(e.SortExpression);
}


void Sort(string column)
{


switch(column)
{
case "Country":


if (ViewState[column] == null)
{
reportsSorted = (from r in report orderby r.Country ascending select r).ToList();
ManageViewState(column,true);
}

else
{
reportsSorted = (from r in report orderby r.Country descending select r).ToList();
ManageViewState(column, false);
}
break;


}


BindGrid(reportsSorted);
}



void ManageViewState(string key, bool Tokeep)
{
if (Tokeep)
    ViewState[key] = true;
else if(ViewState[key]!=null)
   ViewState.Remove(key);


}
#endregion


Have a look at above code and try to work out it.