Tuesday, October 30, 2012

Set autofocus to textbox in asp.net using HTML5

In previous versions of html we don't have direct property to set the auto focus to desired control.If we want to do this things,we have to use java script ,jquery etc.But the HTML5 provides set of new attributes to make easy such kind of things. Here i will set the auto focus to input control using AUTOFOCUS attribute in HTML5.Below are the examples for both patterns
In asp.net Each control has a method to set the auto focus property.Here tb name is textbox id.
Here i have taken two input controls for name and comments.Then set the autofoucs to name text box.
<label for="name">Enter your name : </label> 
<input autofocus="autofocus" type="text" /><br />
<label for="Comment">Enter your comments : </label> 
<input type="textarea" /><br />

Monday, October 29, 2012

Dynamically add columns to GridView in asp.net using C#.net

Title:How to create dynamic columns in grid view in asp.net using c#.net

Up to now we have gone through the data binding concepts like bind data to drop down list in grid view and how to use the link button in grid view.Here i would like to explain how to do customized grid view using c#.net.t.For this the i have created a data table which has three columns and assign the list data to data table using iterations.The resultant grid view can see in the below image

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add rows Dynamically to grdivew</title>
<form id="form1" runat="server">
<asp:gridview autogeneratecolumns="False" id="DynamicColAddGrid" runat="server">

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _DynamicCol : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
List<string> li = new List<string>();
DataTable ddt = new DataTable();
DataRow darow;
DataColumn dc = new DataColumn("Id", typeof(string));
DataColumn dc1 = new DataColumn("Name", typeof(string));
DataColumn dc2 = new DataColumn("FullName", typeof(string));
int ditem = 0;
while (ditem < 8)
darow = ddt.NewRow();
ddt.Rows[ditem][dc] = ditem.ToString();
ddt.Rows[ditem][dc1] = li[ditem].ToString();
ddt.Rows[ditem][dc2] = li[ditem].ToString();
DynamicColAddGrid.DataSource = ddt;

Sunday, October 28, 2012

bind all font name to list box in asp.net using C#.net

In this post i will show how to Display all font name in list box  and based on the selection show the preview in label.To get the font name we have add the name space for Drawing class

Using System.Drawing.Text;
Using System.Collection;

Private void from_load(..)
InstalledFontCollection ifcn=new InstalledFontCollection()
IEnumerator ien;
string si=ien.Current.Tostring();
int i=si.IndexOf("=");
//list box selected index changed event code
String sres=ListBox1.SelectedItem.Tostring();
Lbl.Form=new font(sres,40);

Thursday, October 25, 2012

Bind data to gridview using LINQ in asp.net

In previous posts we have seen how to bind the data to gridview and bind data to dropdown in gridview in asp.net.In this post i will given how to bind and filter the data then bind to grid view using LINQ in Asp.net.Here i have placed a button and grid view then get the orders data with linq query.
//add name spaces
//button click_event
SqlConnection con=new SqlConnection("User id=sa;password=;Databse=test;server=localhost");
SqlDataAdapet ad=new SqlDataAdapater("Select * from products",con);
Dataset dslq=new Dataset();
DataTable dtlq=dslq.Tables("d");
Enumerable <DataRow> Edr=dtlq.AsEnumerable();
Queryable <DataRow> EQ=dtlq.AsQueryable();
EQ=From i in EQ where i["ordername"].Tostring=="Computer" select i;
EQ=From i in EQ where int.parse(i["orderid"].Tostring())<5 select i;

Tuesday, October 23, 2012

how to create table in database using asp.net

In this post i will show how to create a table in sql server/Oracle data base using Ado.net program.For this  i just placed a button on page and write code for button click event to done this process

//BtnCreate_Click event
OledbConnection con=new OledbConnection("user id=scott;password =tiger;provider =msdaora.1");
MessageBox.Show("Con is good"); 
String strcmd="Create table ctr(eno number,Ename varchar(20),sal number(5))";
OledbCommand cmd=New OledbCommand(strcmd,con);
MessageBox.Show("Table is created");
Catch(OLEDB exception oe1)

obs:The table ctr has been created in  Oracle Database

Monday, October 22, 2012

Create a service to send a mail automatically in asp.net using c#.net

In previous post i have given an example on how to send a mail with attachment in asp.net.In this post i will show how to create a service to send automatic email every  day.
Open windows service project -->project menu-->add reference -->system.web(required for mail message class)
Place a timer control ,then set the properties for as below
Using System.Mail;
Time1_elapsed event
int sh=DateTime.Now.Hour;
int sm=DataTime.Now.Minute;
if(sh==9 &&sm==10)
MailMessage mm=new MailMessage()
mm.Body="<h1>Send automatic email</h1>";

Then do the below process:-
1.open the service.cs[Design]
2.Right click on in side of service.cs design-->Add installer
obs:Then two new control will be added
3.service process installer-->right click-->properties-->account=Local system
4.Service Installer --><Right click-->Properties -->service name=P2
5.Build the project(Build-->Build solution)
obs:WS2.exe created under D:c197/ws2/bin/Debug folder with a service called P2

Open .Net command prompt and type as follows ar c:> drive
 Install util -i 197/ws2/bin/debug/ws2.exe

open service(start-->run-->services.msc-->right click on P2-->start

Obs:P2 service will be executed sharp settled time and a mail will be delivered

Saturday, October 20, 2012

Difference between ExecuteNonQuery,ExecuteReader and ExecuteScalar

These three are OLEDB command class methods.Now we will see what is main difference between them
This method is required to execute DDL,DML,TCL and stored procedure
2.Execute Reader:
a)This method required to execute select statement
b)This is required while expecting multiple records
c)Execute Reader() returns the records in the format of Data Reader

3.Execute Scalar:
a)This is also required To execute select statement
b)required which expecting a Particular record
c)Execute scalar() returns object
d)Execute Scalar() checks for first match only,If the match is found ,then on first column value of the first record will returned

Difference between Sealed and Partial class in C#.Net

Sealed Class:
1.Sealed is a keyword
2.Sealed class are not inheritable
3.When ever a class is providing full functionality as per the requirements,then that class need to be declared as sealed

Partial class:
1.Partial keyword can be used with classes and interfaces
2.When a class or interface need be written in multiple locations with same name then those class or interfaces need to be partial

Here i will given an example on Partial class
//Open windows form project.Then place a button
//Code in General declaration
Interface test
void read();
void print();
Partial class testchild:Test
public void read()
Partial class testchild
public void print()

//Code for button click
testchild tc=new testchild();
test t=new test();

Friday, October 19, 2012

User defined exceptions in Asp.net using c#.Net

1.User define exception is a class,which must be inherited from exception class
2.It required based on the projects requirement
3.Syntax to write user defined exception class
class test:exception
4.User defined exception must be raised with throw keyword
syntax:throw new abc()

Here i will given an example to create user defined exception.I just placed a text box and button on the form

Class salexception:Exception
public salexception()
Messagebox.Show("sal must be 5K");
}//class sql exception
//code for button_click event
int sal =Int.Parse(txtsal.Text);
if(sal >5000)
Messagebox.Show("ur sal is:"+sal);
Throw new Exception ();
catch (salexception se)

How to send a Email with html Format in Asp.Net

In previous post we have seen how to send  a mail with attachement.Send a Email with html content can do in two ways.The first One is Creating html page as a body and Create html string as a body .Here i will show how to send the html format using String Builder in asp.net .In the below code i will send the user details to user in valid html format , who are submitting the form .This html string is bind to string builder then assign to email body.The below code have to place in button click event to send mail
Note:We need to set the ISbodyHtml to True For MailMessage properties
System.Text.StringBuilder mailBody = new System.Text.StringBuilder();
mailBody.Append("<b>Phone Number:</b>");
mailBody.Append("<b>Zip Code:</b>");
mailBody.Append("<b>Email Address:</b> ");

///////////////////////////////////////Email Sending method//////////////////////////////////////////////////
string sFrom = Email.Value;
SmtpClient SmtpServer = new SmtpClient(SmtpserverName);
SmtpServer.Credentials = new System.Net.NetworkCredential(Username, PWD);
SmtpServer.Port = int.Parse(Port.ToString());
MailMessage objMailMsg = new MailMessage();
objMailMsg.From = new MailAddress("mulebhaskarareddy@gmail.com");
objMailMsg.Body = mailBody.ToString();
objMailMsg.IsBodyHtml = true;
objMailMsg.Subject = "Details of Registration";


Wednesday, October 17, 2012

Windows 8 app development tutorials

Windows 8 apps can develop  using different web technologies (Java script,C#,HTML5,Direct X etc).If you develop the apps in Visual Studio,we need to install  Microsoft Visual Studio Express 2012 for Windows 8, Windows 8 (SDK). and also need get the  developer license.

Windows 8 apps basics
Develop windows 8 app using javascript ,html5 and css
Develop app using .net with c#,WPF
Windows 8 App life cycle
Windows API reference

Tuesday, October 16, 2012

How to Creating an Entity Data Model from a Database in Asp.net MVC 4

In this post i have given how to create an Entity Data Model in MVC4 project. Here i will create Entity Data model on "TestKrihsna" database which contains eight tables.
Steps for creating EDM:
1.Right click -->select add -->new item -->select "data" in installed templates frame-->select the Ado.net entity data model.

2.We have two option to create EDM which are 1.using Data Base 2.Empty Model.Here i will select Generate From data base option to create EDM with existing database
3.Here we have to select the which data base  used for application .Then the connection string has generated as per sql server credentials.
4.We can see in the below screen ,it  has check box options to select which tables,views and procedures to include in model.Here i have select all table for my application then click on next button
5.Finally we can see the browser window which has entity data model(model.edmx) in VS

 Why we are using entity data model? .

Monday, October 15, 2012

How to add external script(JS) on page in sharepoint 2010

Here i will explain how to import the external java script file into specified share point site web page.To add the file reference by using  a class "script link" which will be used to request scripts by the time of page rendered in share point 2010.We will add the reference both client side and sever side to page using this below piece of code.
Client Side:
<SharePoint:ScriptLink ID="sl" name="/_layouts/Jscripts/testadd.js" runat="server" Defer="false"/>
Server Side:
By using the below method we can access script on server side.The Register method contains the there variable which are page name,script file name and localizable value .
ScriptLink.Register(this.Page, "/_layouts/Jscripts/testadd.js", false);


Sunday, October 14, 2012

Required and compare Validations in Asp.net MVC4

I have created a registration form  for my application,then placed some validation for user inputs based on requirement.In asp.net we have to use validation controls to implement validations.In Asp.Net MVC System.ComponentModel.DataAnnotations name space has been included to get the validation class to perform validations on it.The below code has done for required validation for user name and compare validation for password field

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace TestApp.Models
public class RegisterModel
public int Id { get; set; }
public string UserName { get; set; }
[StringLength(100,ErrorMessage="Password must have 5 characters at least",MinimumLength=5)]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }

There is one more validation  i have done i:e String-length validation on user name.This can make the password minimum length to "5"

Saturday, October 13, 2012

Difference between TCP channel and HTTP channel

TCP ChannelHTTP channel
Streambinary standard streamXML based stream
FormatCompressed formatText format
memoryconsume less memoryconsume Huge memory
platformsSupport homogeneoushomo and hetero geneous
Networksupports normal networksupport both normal and Internet

Friday, October 12, 2012

How to read XML file data in sharepoint 2010

In this post i have given code for how to read  the XML file data which in document library .Here i instantiated a Web Request object by using the path(URI) of the XML file ,then get the Response from path using Web Response class.The GetResponseStream method  is used to get the stream of  content in XML file to stream.Finally we will read the stream into resultant string.By doing the same process we can access any external XML file(URI) into application.But we have to use HttpwebRequest class to make request.
String file_path = "http://sp12/test"
WebRequest wr = WebRequest.Create(file_path);
wr.Credentials = CredentialCache.DefaultCredentials;
WebResponse Wresponse = wr.GetResponse();
using (StreamReader str = new StreamReader(Wresponse.GetResponseStream()))
String Result_Data =str.ReadToEnd();

Thursday, October 11, 2012

How to Get Last updated /Inserted records from the table in sql server

How could you solve if you had a big problem with data base when insert the huge amount of duplicate records into table ?The same situation i have faced recently.by the time i  simply makes the insertion process for that bulk records.But later on i got a trouble  with those records .For this i want to checked out to display the recent insertion data from table.In the  below query i have used date function and length function to get the last updated records which are  greater than current date minus 5 (last five days) and length of header is greater than 4
select * from order
where len(order_head)<=4
and (inactive_date is not mull or inactive_date > getdate()-5)
and order_head is not null
and order_code like 'SAT%'
Finally all redundant insertion records has been deleted for last five days using the below query
Delete order
where len(order_head)<=4
and (inactive_date is not mull or inactive_date > getdate()-5)

Wednesday, October 10, 2012

How to convert the Date/Number to string in sql server 2012

The new version(2012) of sql server makes easy to string conversion from number or date.We don't have any direct  function to do this one in older versions .If we want to do this one ,then we have to use Conversion functions(CAST or CONVERT).
SELECT CAST(date AS nvarchar(100)) AS string_date from Orders
The FORMAT string function has introduced to convert the number/date to string in Sql server 2012 .Here i have given a simple query to get the amount(It has money data type in table)  in currency format.
SELECT order_ID,FORMAT(Price_Amt, 'C', 'en-us') AS 'Amount' from Orders
In this function we  have to use standard numeric formats for desired Format ..Details about standard Numeric Format Strings

Tuesday, October 9, 2012

How to insert data from view to table in sql server

Recently i have work with large database for data insertion which is from "excel sheet".For this first I will export data from  excel sheet to data table,then  "create view" (test_orders)which has data based on where condition.
insert into orders(ordr_code,ordr_desc,ordr_code,price_amt)
select [Title ID] ,Name,replace(ORDERCODE,'-',''),[List Price] from [test_orders]
In the above first i have select the data from view then insert into desired table.Here i have done string replacement for one column when fetch the data from view

Monday, October 8, 2012

Get current user Profile in SharePoint 2010

Earlier i have given a customised solution to get the current user permissions in share point 2010.Here i will show how to get the user details from share point site using  UserProfileManager class.Before going to get the profile details we need to check whether the user is valid or not.Then the resultant data will be assigned to user profile class and get account name into string

SPSite sps = SPContext.Current.Site;
using (SPWeb spw = sps.OpenWeb())
SPServiceContext spsc = SPServiceContext.GetContext(sps);
UserProfileManager uprofile = new UserProfileManager(spsc);
string useraccountname = SPContext.Current.Web.CurrentUser.LoginName;
if (uprofile.UserExists(useraccountname))
UserProfile Profileinfo = uprofile.GetUserProfile(useraccountname);
if (!string.IsNullOrEmpty(Profileinfo["FirstName"].ToString()))
string AccountName = userProfile["FirstName"].ToString();

Friday, October 5, 2012

How read data from List in sharepoint 2010

In previous posts i have given how to read data from the excel file in document library.Here i have given a customised code to read the data from share point list. In the below code we are first get the data(ordername,orderamount,orderarea) from "orders" list using QAMLquery .Then the resultant data in to list item collection and read the each values through loop condition
SPList spl =SPContext.Current.Web.Lists.TryGetList("Orders");
SPQuery spq = new SPQuery();
spq.ViewFields =string.Concat("<FieldRef Name='OrderName' />","<FieldRef Name='OrderAmount' />","<FieldRef Name='OrderArea' />");
SPListItemCollection splc = spl.GetItems(spq);
foreach(SPListItem sitem in splc){
if(sitem != null)
Oname = item["OrderName"].ToString(); 
Oamt = item["OrderAmount"];
Oarea = item["OrderArea"];

I have used condition to check whether the list item(sitem) is null or not.Because the variables (oname and etc) has used in another method  here .

Thursday, October 4, 2012

How to concatenate strings in sql server 2012

In previous versions there is no direct function to make this one.If we want concatenate two strings we have to use '+' symbol .
But in the latest version of sql server2012 introduce a new string function "CONCAT()" ,which is used to concatenate the strings.Let me explain one example for how to use and execute this function in sql server 2012.
Here i have table with three five columns(id,name,sal,surname,add).Now i want to concatenate the name and surname when executes the select query from emp table

select id,CONCAT(name,surname) as FullName from employee

Monday, October 1, 2012

How to add images/files to document library in sharepoint 2010

In previous post we have seen how to get the updated items from the document library and read the excel file data from document library.Here i will shown how to add the image files to document library/List .For this i have been converted  the attachment file to string format then get the size using some length and memory of this.Then using document  library class the result Data has added to library after check in .
XPathNavigator dX = MainDataSource.CreateNavigator();
XPathNavigator XN = fileAttach.Current;
byte[] converted_attachment = Convert.FromBase64String(XN.ToString());
double filelength= converted_attachment.Length;
double memoryb = 2048 * 2048;
double resultfSize = filelength / memoryb;
if (resultfSize < 8 && resultfSize != 0)
int fln = converted_attachement[32] * 2;
byte[] fb = new byte[fln];
for (int i = 0; i < fb.Length; i++)
fb[i] = converted_attachement[24 + i];
string[] filenameparameter = System.Text.UnicodeEncoding.Unicode.GetChars(fb);
string ResultfName = new string(Filenameparameter);                            
byte[] Result_Data = new byte[converted_attachement.Length - (24 + fln)];
for (int i = 0; i < Result_Data.Length; i++)
Result_Data[i] = converted_attachement[24 + fln + i];
SPDocumentLibrary dl = (SPDocumentLibrary)Web.GetList(Site.ServerRelativeUrl + "/DesiredLibraryName");
SPFolder spfolder = dl.RootFolder;
SPFileCollection spf = spfolder.Files;
SPFile sf = spf.Add(spfolder.Url + "/" + DateTime.Now, Result_Data);
SPListItem spf_item = sf.Item;
spfitem["Filename"] = resultfName;
spfitem.File.CheckIn("WF CheckIn", SPCheckinType.MajorCheckIn);