Tuesday, April 30, 2013

How to send a mail in asp.net

Title: How to send an email in asp.net using c#.net

Description:
In previous posts i have given send a mail with attachment in asp.net,Send mail using service,send a Email with html Format in Asp.Net.In the same way i just given an example on sending email concept in asp.net.The following example has two text boxes which are used to give the subject and name to mail message
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send a mail in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSub" runat="server"></asp:TextBox>
<asp:TextBox ID="txtbody" runat="server"></asp:TextBox>
<asp:Button ID="btnsendmail" runat="server" Text="Send" onclick="btnsendmail_Click" />
</form>
</body>
</html>
Codebehind:
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Mail.Net;

public partial class _sendmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnsendmail_Click(object sender, EventArgs e)
{
try
{
SmtpClient SmtpmServer = new SmtpClient(SmtpserverName);
SmtpmServer.Credentials = new System.Net.NetworkCredential(Username, PWD);
MailMessage MlMsg = new MailMessage();
MlMsg.From = new MailAddress("bhaskar7698@gmail.com");
MlMsg.Body = txtbody.Text;;
MlMsg.IsBodyHtml = true;
MlMsg.To.Add(mulebhaskarareddy@gmail.com);
MlMsg.Subject = txtSub.Text;
SmtpmServer.Send(MlMsg);
Respose.Write("Mail sent successfully");
}
catch (Exception em)
{
Respose.Write(em.Message.Tostring());
}
}
}

Monday, April 29, 2013

Edit,delete,update records in gridview using sqldatasource in asp.net

Title: Edit Delete Update in Grid view in asp.net

Description:In previous post i have given how to edit,delete,update in grid view using row events,Bind data to grid view using SQL data source(here you can see how to use it).For this we need to set the  properties for grid view to enable the columns for db transaction.Might be get where the DML commands are executed?.The answer is the sqldatasource has properties to executes those commands when user perform those action on grid view

Example:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OrderGrid.aspx.cs" Inherits="OrderGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvOrder" AllowSorting="True" Runat="server"
AutoGenerateEditButton="True" AutoGenerateDeleteButton="True" AutoGenerateColumns="False" DataSourceID="OrdrDb">
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName"
SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
SortExpression="Amount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="OrdrDb" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]" UpdateCommand="UPDATE [Orders] SET [OrderName] = @OrderName, [Phone] = @Phone,
[Address] = @Address, [Amount] = @Amount WHERE [OrderID] = @OrderID" DeleteCommand="Delete [Orders] WHERE [OrderID] = @OrderID"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
Result:
Display Order table table using Data source:
Bind data to gridview
Update Records using edit operation in grid view





Saturday, April 27, 2013

delete all gridview rows using checkbox in asp.net

Title:
How to delete rows in grid view using check box in asp.net

Introduction:
Hi all,I think you have seen so many articles and websites on grid view functionalists.But why i have given again the same delete records in grid view?".This question should get every one when you reading the title.The answer is,I would like to share the code or logic what i have done earlier in easy manner.Let go to the our task.I hope the below explanation is useful for us.Thanks to reading..

Example:
Some previous articles
select the multiple rows of grid view,
Get the check box in grid view using Jquery.
In this post i will show how to delete the all rows from grid view using check box in grid view.The design page have the grid view layout with item templates and and check which is used to select the specified rows in grid view to make functionality better
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Delete All Rows in grid view with check box in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GvOrder" runat="server" AutoGenerateColumns="False" CellPadding="4" GridLines="None" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Order NO.">
<ItemTemplate>
<asp:Label ID="lb1OrderId" Text='<%#Eval("OrdrNo") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField><asp:TemplateField HeaderText="OrderName Name">
<ItemTemplate>
<%#Eval("Ordrname") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<%#Eval("Amtsal") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="btnchkall" runat="server" OnClick="btnchk_Click">Check All</asp:Button><asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click">Delete</asp:Button>
</form>
</body>
</html>
Code behind:
The connection string settings in the config file has been made as per in the below snippet.It contain server and data base name.Before going to add this code we have to create a connection to database in web.config file. Here my connection name is "OrderDetailsConnection".

<appSettings>
<connectionStrings>
<add key="OrderDetailsConnection" value="server=bhaskar/SQLEXPRESS;database=Order_Db;uid=bhaskar;password=br123;" />
</connectionStrings>
</appSettings>

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class _GrdivewChkDelete : System.Web.UI.Page 
{
SqlConnection cn = new SqlConnection(ConfigurationSettings.AppSettings("OrderDetailsConnection");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindOrdrGrid();
}
private void BindOrdrGrid()
{
SqlDataAdapter OrdrAd = new SqlDataAdapter("Select * from Order",ocn);
DataSet Ordrds = new DataSet();
OrdrAd.Fill(Ordrds);
GvOrder.DataSource = Ordrds;
GvOrder.DataBind();
}
protected void btnchkall_Click(object sender, EventArgs e)
{
CheckBox rchk;
for (int i = 0; i < GvOrder.Rows.Count; i++)
{
rchk = ((CheckBox)(GvOrder.Rows[i].FindControl("orbrcb")));
if (orbrcb.Checked == false)
//Check all check box in gridview
orbrcb.Checked = true;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
CheckBox rchk;
String ordrId = String.Empty;
for (int i = 0; i < GvOrder.Rows.Count; i++)
{
rchk = ((CheckBox)(GvOrder.Rows[i].FindControl("orbrcb")));
if (orbrcb.Checked){//Get the Id from lable
ordrId +=((Label)(GvOrder.Rows[i].FindControl("lb1OrderId"))).Text + ",";
}
}//Get the Order_Id
ordrId = ordrId.Substring(0, ordrId.Length - 1);
cn.Open();
//Delete all grdivew records
SqlCommand cmd=new SqlCommand("delete from Order where Order_Id in("+ordrId.ToString()+")",cn);
cmd.ExecuteNonQuery();
BindOrdrGrid();
}
}
//In the above code i have used to delete the records using "IN"  in sql command.By using this we can delete the all records with in the list.Keep coming to get latest updates 

Friday, April 26, 2013

Asp.net validation controls

Title:How to use validation control in asp.net

Description:
Normally in web application, validation are perform using java script. We must write JS and perform validations.If validations are successful then we redirect the user to sever and if validation fails then we display error to user to perform all these with java script. It is complex and also time consuming.In previous articles i explained how to pass server side variable to client side in asp.net,Validate drop down list in java script,How to validate text box in JQuery

Asp.net developers are provided with validation controls which enable user to perform validation just like server side controls.These validation controls render Jquery to the client or browser like this we can have rapid application development for validation and also we can reduce the Complexity of writing java script code validation controls of asp.net target clients as automatic which means based on browser validation are perform

The fallowing validation controls are supported by asp.net
1.Required Field validator
2.Range validator
3.Compare validator
4.Regular expression validator
5.Custom validator
6.Dynamic validator
7.validation summary

The most common property for validation controls:
Controltovalidate:web control id
Error message =message
setFoucsError=true/false
validation Group :makes the control part of separate validation group
Display:static(default)/dynamic/none
i.static :Initially place for displaying error will be reserved.When error occurs it will be visible otherwise it will be hidden
ii.Dynamic:No place in the form will be reserved initially only on error dynamically the message will be shown
iii.none:will not display the error message only

Required field validator:

Used to check null values and it is the only control that checks null values .Remaining validation controls doesn't perform any validation if null values are entered.IN the below example have used this validation for Textbox(txtOrder) which is used to give the Order value.
<asp:requiredfieldvalidator controltovalidate="txtOrder" display="dynamic" errormessage="Enter Order Details" id="RfOrder" runat="server">* 
</asp:requiredfieldvalidator>

Range validator:

To check for range of values.Useful for numeric and date format of data Additional properties Minimum value :1
maximum Value :1000

<asp:textbox id=" runat="server" txtage=""> <asp:RangeValidator id="RvAge" runat="server" ControlToValidate="txtage" 
 MaximumValue="16" 
 MinimumValue="24" 
 Type="Integer" 
 ErrorMessage="Enter valid age" Display="Dynamic">*</asp:RangeValidator>
Can one control have multiple validation controls? the answers is yes
we can use one validation control validate single controls only

Compare validator:

With compare validation we can perform 3 types of validation all will be based on comparison
1.Control with another control
2.control with value
3.control with data type

 UserName<asp:textbox id="txtuser1" runat="server"/>
 Reenter UserName: <asp:textbox id="txtuser2" runat="server"/>

<asp:CompareValidator ControlToValidate="txtuser1" ControlToCompare="txtuser2" Operator="Equals" ErrorMessage="Please enter valid user name" Display="dynamic">*</asp:CompareValidator>

validation summary control:

Used to report errors as a summary i:e display all control errors.error message display throw summary control.It has two properties
i)show summary :true/false
ii)show messageBox =true/false
when display is set to none then validation control will not display error in its place instead if displays error in summary control .

Regular expression validator:

Using they control we can specify on expression and ask validator to match the expression with control.Previously i have given to validate email using regular expression in asp.net.

Custom validator:

In previous post i have given example on how to use custom validator in asp.net.For complete details click here

Thursday, April 25, 2013

Bind data to datalist in asp.net

Title:How to bind data to data list in asp.net using c#.net

Description:
In previous post we have seen bind data to grid view,bind xml data to grid view in asp.net.In this post i will show how to bind the data to data list using SQL Data source in asp.net.Here we don't need write the code to get the data for data list
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server" Font-Size="10pt" Width="350px" HeaderStyle-BackColor="ActiveBorder"
 AlternatingItemStyle-BackColor="Aqua" DataSourceID="SqlDataSource1">
<HeaderTemplate>
Order Details
</HeaderTemplate>
<ItemTemplate>
OrderID: &nbsp;<asp:Label ID="OrderIDLabel" runat="server" Text='<%# Eval("OrderID") %>' />
OrderName:
<asp:Label ID="OrderNameLabel" runat="server" Text='<%# Eval("OrderName") %>' />
Phone:
<asp:Label ID="PhoneLabel" runat="server" Text='<%# Eval("Phone") %>' />
Address:
<asp:Label ID="AddressLabel" runat="server" Text='<%# Eval("Address") %>' />
Amount:
<asp:Label ID="AmountLabel" runat="server" Text='<%# Eval("Amount") %>' />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
1.Select data source for data list using options
Design mode ->Data list Tasks->choose new data source
2.Select the SQL Data Source->click next
3.Create new connection wizard will open.In this we have make select the new connection button.
4.Select the data base which you want to use
5.click on next then get wizard to configure the data using query.
6.click finish

Tuesday, April 23, 2013

How to bind data to dropdownlist with arrarylist in asp.net


In previous post we have discussed on how to bind the Data in Gridview,Disable dropdownlist .In this post i will show how to bind data to dropdownlist using array list in asp.net.Here i will populate drop down for city names.
<html>
<head>
</head>
<body>
<form runat=server>
<asp:DropDownList id="ddlcity" runat="server" />
</form>
</body>
</html>
We have to used ispostback to avoid the populating drop down while every time loading the page

protected void Page_Load(Object Sender, EventArgs E) 
{
if (!IsPostBack) {
ArrayList citynames = new ArrayList();
citynames.Add ("NewYork");
citynames.Add ("Hyderabad");
citynames.Add ("Bombay");
ddlcity.DataSource = citynames;
ddlcity.DataBind();
}
}

Monday, April 22, 2013

how to get selected items from checkboxlist in asp.net c#


In previous post i have given how to get the id of checkbox using jqury ,check all checkbox in gridview.In this post i will show how to get the selected values of check box list in asp.net.I below piece of code i have looping thorough the check box list items on button click event .Then the resultant value has assigned to string
<html>
<head>
</head>
<body>
<form>
<asp:CheckBoxList ID="ChkOrdrList" runat="server">
<asp:ListItem>COmputers</asp:ListItem>
<asp:ListItem>Books</asp:ListItem>
<asp:ListItem>Laptop</asp:ListItem>
<asp:ListItem>Ipad</asp:ListItem>
</asp:CheckBoxList>
<div>   
<asp:Button ID="btngetOrdr" Text="Ok" OnClick="btlgetOrder_Click" runat="server" />
</div>
<asp:TextBox ID="txtOrdername" runat="server" />
</form>
</body>
</html>

public void btlgetOrder_Click(object Source, EventArgs e)
{
String strOrdr = "Checkboxlist selected Item is:";
for (int i = 0; i < ChkOrdrList.Items.Count; i++)
{
if (ChkOrdrList.Items[i].Selected)
{
strOrdr = strOrdr +","+ ChkOrdrList.Items[i].Text;
}
}
txtOrdername.Text = strOrdr;
}

how to create usercontrol with user defined properties in asp.net

In previous posts i have given examples on how to convert string to data table in asp.net,Gridview Examples,Add colums dynamically to gridview.Her i will show how to develop a scrolling label control with text,color,font  properties using csharp.The timers are used to get the time inteval of process
Place label control
Place Timer Control with enabled =true
Place one more timer with enabled =false

Code fro timer_TickEvent(--)
{
lblname.Top=lblname.Top-5;
if(lblname.Top<0)
{
Timer1.Enable=false;
Timer2.Enable=True;
}
}
Code for time2_tick event(...)
{
lblname.Top=lblname.Top+5;
if(lblname.Top>250)
{
Timer1.Enable=false;
Timer2.Enable=True;
}
}
//Code in General Declaration
//create properties
Publlic string Ltext
{
set {lblname.Text=value;}
get{return lblname.Texte;}
}

Publlic string Lbcolor
{
set {lblname.BackColor=value;}
get{return lblname.BackColor;}
}

Publlic string Lfont
{
set {lblname.Font=value;}
get{return lblname.Font;}

}
Publlic int Lspeed
{
set {timer1.interval=value;
timer1.interval=value;
}
get{return timer1.Interval;}

}
Build the project
note:Scrolling lable.dll is created under d:\myprojects\scrolling label \bin\debug folder
Open page and drag scrolling.dll into my controls tab of toolbox.Then user control slable has been added to tool box

Tuesday, April 16, 2013

GridView TemplateField in asp.net || how to bind the Data in Gridview TemplateField in asp.net


Inprevious posts i have given examples on how to export data from gridview to excel,Bind dropdown in gridview .Here i will explain the gridview template fields. Template field is used for complex content and it is unlimited and also can be used for any type of presentation.It is both attribute based and content based for producing output.It's content is defined using templates.A template is an area where we can present any type of data .Template fields has no attribute for retrieving data from data objects and it uses asp.net data binding expressions to retrieve data and support data binding.The following syntax and statement are used for writing data bind expressions
<%# data bind expression #>
<%# Eval("filedname") #> (2.0)
<%# Bind("filedname") #>
<%# DataBinder.Eval(container.DataItem,"filedname")%>
The last method is the older asp.net method

Eval gets data from data object and bind gets data from data object like eval but also sends data back to data object for changes,It is conditional
Note:db expression can be written separately inside templates and also along with properties of controls when used.Along with properties.we must enclose them in single quotes
<asp TextBox Text='<%#Eval("job_id")%>'> </asp:Texbox>

Monday, April 15, 2013

Collection initializer in c sharp


Collection initializers are extension of object initializers.It look like an array.To create a collection initializers ,Auto-implemented properties are required.To work with this,a generic data type called as list is required.Generic data type holds any type of data. These are similar to c++ templates and will be indicated with <>

Example:
Code in General declaration
class result
{
public int marks {set; get;}
public string sname {set; get;}
public int id {set; get;}
}
Code for btn click
{
list<result> rs= new list<result>
{
new result{marks=100,sname="siva",id=1}
new result{marks=100,id=2}
}
foreach(result r,int rs)
Messagebox.Show(r1.marks+" "+r1.sname+" "+r1.id);
}
In the above i have taken one button to done this example

Saturday, April 13, 2013

object initializer in c sharp

In this post  i would like to give an example on object initializers in c#.net.
1.Object initializers are used to initialize the instance variables automatically
2.These are bit similar to constructions syntaxically
obs:
if the class name is test
Test t=new test(101,"bhaskar") is called as constructor
Test t=new test{eno=101,ename="bhaskar"} is called as object initializers
In the above syntax eno and ename are two implemented properties
3.The main objective of object initializer is to save no of lines  in the source code

Example:
place a button on the form
Cod in GD
class emp
{
public int eno {set;get}
public int sal {set;get}
public string name {set;get}
}
Code for button click event
{
emp e1= new emp{eno=101,ename="bhaskar",sal=5000};
MessageBox.Show(e1.no+""+e1.name+""+e1.sal);

Monday, April 8, 2013

Automatic password change in SharePoint 2013

Share Point 2013 provides the automatic password change feature which will use to update the password
for managed accounts with out manual changes.By using APC we can modify the pass on scheduled time,Quickly reset the all passwords ,Get the expiration time of the passwords etc.
For complete description please click link here 

Sunday, April 7, 2013

new and update for share point 2013


The below are the updated and new things have been added  to Share Point 2013 by march.
New:
1. XLIFF interchange file format .click here  for more
2.Customize  page layouts for a catalog-based site . For Brief Description
3.BCS connection objects
Updated:
1.BCS REST API reference
2.Create external event receivers
3.e Discovery 
4.eDiscovery and compliance
5.design packages 

Download Visual studio 2012 Update 2 (VS2012.2)


Visual Studio 2012 update has been done by last week .The following are the new features that have been included in this update.
1.Web access to  the test case management tools in Team Foundation Server.
2.Windows Store development.
3.Line-of-business development.
For complete details of update click here
Download VS2012 update 2(VS2012.2)

Bel