Thursday, July 30, 2009

Export XML from SQL using a Stored Procedure.

1) Generate a file with the text-editor like:


<%begindetail%>
<%insert_data_here%>
<%enddetail%>


Save it as c:\temp\template.tpl

2) Open Query Analyzer and type:


sp_makewebtask @outputfile = 'c:\temp\myxmlfile.xml',
@query = 'select * from sysobjects for xml auto',
@templatefile = 'c:\temp\template.tpl'

The result is a XML-File!


More ^

Wednesday, July 29, 2009

Move Seleted Records using Checkbox in GridView

Hi ,

here is nice tutorial or you can say very simple example on how you can
delete or move the records from the Gridview

Move/Delete content From GridView

hope u like it ,

Monday, July 27, 2009

Hide Show Div

hi this is cool and simple javascript stuffs which HIDE and Show Details
using Div


<script language="javascript">
function toggle() {
var ele = document.getElementById("togText");
var text = document.getElementById("ShowText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Click Me";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide It";
}
}
</script>

Click Here to View Details
<a id="ShowText" href="javascript:toggle();">
Click Me </a>
<div id="togText" style="display: none">
< h1 > Hi, Kiran hows you? Hope u like this Cool stuff. < /h1 >
</div>



hope you like it ,

Friday, July 24, 2009

Set Favicon in different Browser

we have seen most of the site has Fevicon which describe the addtional information
about the site , Addtion in the sence it could be logo,company Profile, company production,web site application, and so many .

here are the top most Example of the fevicon sites




now how u can do this

its very simple to do , just u need to add some line's of code and be ready with small icon image, u can also add animated image in fevicon

add this part in between <head> </head> Section


<link rel="shortcut icon" href="images/favicon.ico">


now some time this code will not work on most of the Browser like IE old version
in this case u can add this line


<link rel="shortcut icon" href="images/favicon.ico" type="image/vnd.microsoft.icon" *gt;


any other query plz comment on it.

Thursday, July 23, 2009

Mini-URL on CodePlex using C#

if u want to minimize / Shrink / Shorten URL , then its a very good technique to do this then. its also useful as per the security and many others aspects.



its very useful for the developer to create a simple URL for there web application / url redirection services like tinyurl
,is.gd,sn.url

- you can download that sample ASP.Net MVC Application from here

- Project Description

hope u like that .

Wednesday, July 22, 2009

Eliminate Duplicate records from the Grid View

Most of the time we need to delete duplicate entries from GridView, in this case we can delete it manually also or using onRowcreate also we can remove that .

Example
suppose Mr.Xyz has has more than 2 Account in Blogspot.com site and we want to show
in GridView Person and RelatedBlogs like this





and in this case we dont want to repeat Person name on each row.
- I have a data source

DataTable dtsource = new DataTable();

//Adding columns to datatable
dtsource.Columns.Add("Person");
dtsource.Columns.Add("Related Blog");

//Adding records to the datatable
dtsource.Rows.Add("kiran", "kirank.blog.com");
dtsource.Rows.Add("kiran", "webdevlopmenthelp");
dtsource.Rows.Add("kiran", "www.kiran.com");
dtsource.Rows.Add("mark", "mark.blog.com");
dtsource.Rows.Add("mark", "asp-net.blogspot.com");


put the below code in codebehind


private void GenerateUniqueData(int cellno)
{
//Logic for unique names

//Step 1:

string initialnamevalue = grdUniqueNames.Rows[0].Cells[cellno].Text;

//Step 2:

for (int i = 1; i < grdUniqueNames.Rows.Count; i++)
{

if (grdUniqueNames.Rows[i].Cells[cellno].Text == initialnamevalue)
grdUniqueNames.Rows[i].Cells[cellno].Text = string.Empty;
else
initialnamevalue = grdUniqueNames.Rows[i].Cells[cellno].Text;
}
}



on GridView define property OnRowCreated="GenerateUniqueData" it will search the record via cell and set the Person name as a empty or person name

Caching in ASP.NET

Caching

is one of the best technique of persisting the data in memory for immediate access to requesting program calls.Caching is about storing data in memory the first time it is requested and then re-using it for the following requests for a specified period of time.

Why Caching is important ?

Every time we have to querying database for each request is not cost-effective in terms of server resources, hence is lot better to cache or persist the data to avoid this costly loss of resources.so in this case we are imporve the system performance and avoid the consistancy.

ASP.Net Provides the flexibility in terms of caching at different levels.

  • Fragment Caching


  • in this case caching a user control that can be used in a base web form page.if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

    Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

    The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control.

    Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

    <script runat="server">
    private int _Departmentid=0;
    public int DepartMentId
    {
    get{return _Departmentid;}
    set{_Departmentid =value;}
    }
    //Load event of control
    void Page_Load(Object sender, EventArgs e)
    {
    lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = "
    + _Departmentid + "\n";
    }
    </script>
    <asp:Label id="lblText" runat="server"></asp:Label>




    Add the following to an *.aspx file. Please note the way "Register" tag is used;

    the declaration of control using syntax <[TagPrefix]:[TagName]>



    <%@ Page Language="C#" Trace="true" %>
    <%@ Register TagPrefix="CacheSample" TagName="Text" Src="CachingControl.ascx" %>
    <script runat=server>
    void Page_Load(Object sender, EventArgs e)
    {
    this.lbltime.Text ="Base form time is " + DateTime.Now.ToString() + "\n";
    }
    </script>
    <html><head><title></title><body>
    <asp:Label id="lbltime" runat="server"></asp:Label>
    <CACHESAMPLE:TEXT id="instance1" runat="Server" DepartMentId="0">
    </CACHESAMPLE:TEXT>
    <CACHESAMPLE:TEXT id="instance2" runat="Server" DepartMentId="1">
    </CACHESAMPLE:TEXT>
    </body>
    </html>

  • Application Level Caching


  • With Page level Output caching one cannot cache objects between pages within an application. Fragment caching is great in that sense but has limitations by using user controls as means to do. We can use the Cache object programmatically to take advantage of caching objects and share the same between pages. Further the availability of different overloaded methods gives a greater flexibility for our Cache policy like Timespan, Absolute expiration etc. But one of the biggest takes is the CacheDependancy. This means that one can create a cache and associate with it a dependency that is either another cache key or a file.

    Find below the snippet that uses CacheDependancy. Here what I have done is to provide a list view of existing employees. You need to create a Database in Sql Server, setup some data before you can continue. The schema scripts are enclosed in the article.

    Add database connection value in Web.Config and change the value as per your setup.


    <appSettings>
    <add key="conn" value="Data Source=vishnu;trusted_connection=yes;Initial Catalog=Users"/>
    </appSettings>


    First I get the dataset into which I fill the user list. But before this I check for the cache initially if it exists I directly cast it to a dataset, if not create a cache again.
    daUsers.Fill(dsUsers,"tblUsers");

  • Page Level Output Caching

  • This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.


Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

so at last Caching is a technique that definitely improves the performance of web applications if one is careful to have a balance in terms of which data needs to be cached and parameter values for expiration policy.

hope this article helps you to imporve your applicaiton performance and best result ever

- you can find more information here
- how to perform Cache Optimization

Tuesday, July 21, 2009

IsPostBack property

IsPostBack-Gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.

when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the Page..::.Validate method.

Syntax:


private void Page_Load()
{
if (!IsPostBack)
{
// Validate initially to force asterisks
// to appear before the first roundtrip.
Validate();
}
}


Example


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PageDataBind();
}
else
{
Response.write("2nd Time Visisted..");
}
}

protected void PageDataBind(string SearchProduct)
{
SqlDataAdapter SDA ;
DataSet ds = new DataSet();
String sql = "select * from Emp where ID ='"+ DropDownList.SelectedItem.Text +"'";
SDA.Fill(ds, "productDetails");
ShowId.DataSource = ds;
ShowId.DataBind();
}


when loading of the page, the control doesn't go through the redundant action of re-loading the control. It loads it only once, at the initial page load. Once the page is loaded, the click event from the button (or however you post back) is considered to be a postback. Yes, the page gets reloaded, but, by surrounding your data population with this statement, the page knows that the initial data loading was already done, so it doesn't happen any more, and it gets maintained throughout any subsequent post back. The second, and most rewarding thing that happens is that the selection which was made by the end user is maintained throughout the post back. This is the pay-off - by doing it with the If/Then Page.IsPostBack statement, your selection carries through to your query and the query returns the results you wanted in the first place.

Monday, July 20, 2009

Filter User via IP

its a good technique to Restrict user to view your website , this task can be done with the help of checking of user's IP Address and match with our database and if user get found under
that IP then you can set Denied Access to them .

But in this case you need a Live IP Address database,
there are so many website are there they are provides free IP Address database range .

and with the help of that u can Denied user.

here are the List of free IP address database sites


Simply download that.

1. Create one IP check function
2. take user Ip address

in ASP : - Ip =Request.Servervariables("REMOTE_HOST")
in C# : - String ipAddress = (Request.ServerVariables["REMOTE_ADDR"]);

3. then check if user's Ip address is there in you'r database , depend on that
you can prevent user.


hope it will helps you,

open new window in GridView using OnRowCreated

In GridView using "OnRowCreated" function we can add onClick function.

here is the sample code

html code


<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text="Click Me"></asp:Label>
</ItemTemplate>
</asp:TemplateField>


and CodeBehind is


protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = (Label)e.Row.FindControl("Label1");
if (l != null)
{
string script = "window.open('Default.aspx');";
l.Attributes.Add("onclick", script);
}
}
}


run the Application and click "Click Me" it will open new window , indirectly we are adding
OnClick Event in That Row.

Saturday, July 18, 2009

import contact list from gmail,yahoo,rediffmail

yes , use can retrieve the contact list from mail server like Gmail, Rediff , Hotmail , AOL and all others They are providing free API to do this, u simply download the Application at your end and pass the parameter like (ID,Password) .

Gmail :

google code API



Yahoo / Live / Rediff

Yahoo / Live / Rediff



Rediff API
Rediff API


Zip application

opencontactsnet OpenContact.NET 1.0 file released: OpenContactsNet-1.0.zip


AOL API
AOL Guide to Integrating OpenAuth
happy coding.......

CountDown Timer

Hi , here is cool triks of CountDown timer, mostly its useful in website while validating time like online exam, date time , game countdown , and so many

Below is the code needed to display count down in HTML page using javascript.

You define container for the count down (either <span> or <div> tag) and the initial value, and the code updates the time automaticlly in the format HH:MM:SS

You can also control the style of the container using standard CSS, as demonstrated in the below and attached code.

To activate the count down in one of your existing pages you
have to follow two steps:

1. include the attached CountDown.js file with:


<script type="text/javascript" src="CountDown.js"> <script>


2. have such javascript in the section:



<script type="text/javascript">
window.onload=WindowLoad;
function WindowLoad(event) {
ActivateCountDown("CountDownPanel", 100);
}
</script>


where "CountDownPanel" is the ID of the container
(i.e. you should have <span> or <div> with this ID) and 100 is the time in seconds to be counted.

here is CountDown.js file -------------------------------

var _countDowncontainer=0;
var _currentSeconds=0;

function ActivateCountDown(strContainerID, initialValue) {
_countDowncontainer = document.getElementById(strContainerID);

if (!_countDowncontainer) {
alert("count down error: container does not exist: "+strContainerID+
"\nmake sure html element with this ID exists");
return;
}

SetCountdownText(initialValue);
window.setTimeout("CountDownTick()", 1000);
}

function CountDownTick() {
if (_currentSeconds <= 0) {
alert("your time has expired!");
return;
}

SetCountdownText(_currentSeconds-1);
window.setTimeout("CountDownTick()", 1000);
}

function SetCountdownText(seconds) {
//store:
_currentSeconds = seconds;

//get minutes:
var minutes=parseInt(seconds/60);

//shrink:
seconds = (seconds%60);

//get hours:
var hours=parseInt(minutes/60);

//shrink:
minutes = (minutes%60);

//build text:
var strText = AddZero(hours) + ":" + AddZero(minutes) + ":" + AddZero(seconds);

//apply:
_countDowncontainer.innerHTML = strText;
}

function AddZero(num) {
return ((num >= 0)&&(num < 10))?"0"+num:num+"";
}

Friday, July 17, 2009

Twitter API in C#

I used C# and WCF, but I could have just as easily used an ASMX web service. This code is fairly simple.

Note: This code will not run as listed. You have to have a password. This code has that as a shared variable, but I'm not showing that to you, seriously. I hope that this is of some help to you.



[OperationContract]
public void SubmitUserStatus(string username, string tweet)
{
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
// set the method to POST
request.Method = "POST";
// thanks to argodev for this recent change!
request.ServicePoint.Expect100Continue = false;
// set the authorisation levels
request.Headers.Add("Authorization", "Basic " + user);
request.ContentType = "application/x-www-form-urlencoded";
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream
reqStream.Close();
}




for more information on Twitter API
Link : http://twitter.com/twitterapi
Orignally posted from this Article

Wednesday, July 15, 2009

Use XMLHTTP Object in C#

The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP. you can use this XMLHTTP object in C#.

follow the steps to do thi.

Steps
1. Add New Refrence to the Microsoft,Ver3.0 (Msxml 3/4) in your project.

how to add new Refrence

2. import the Namespace Using MSXML2;

3. now add this code in codebehind



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MSXML2;

public partial class MSXML : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
// to get page data (using msxml4)
XMLHTTP40 http = new XMLHTTP40();
http.open("GET", "http://www.xyz.xom/sendResult.aspx"+TextBox1.Text+"", false, null, null);
http.send();
string value = http.responseText;
Response.Write(value.ToString());
}
}





4.Add this code in Html



<form id="form2" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>

Tuesday, July 14, 2009

Pass multiple parameter using HyperLink field in GridView

While using Hyperlink field u can send multiple parameter in Gridview , and then u can retrive it using QueryString Parameter.

here in this Example when user will click on username then it will redirect to
http://xyz.com/ShowUser.aspx?id={0}&city={1} this page
and it will pass customer id and city .






<asp:SqlDataSource id="datasource1" runat="server" SelectCommand="SELECT CustomerID, CompanyName, City FROM Customers"
/>

<asp:GridView id="gridview1" DataSourceID="datasource1" runat="server"
AutoGenerateColumns="False">
<Columns>

<asp:BoundField DataField="CustomerID" HeaderText="BoundField" />

<asp:HyperLinkField
DataTextField="CustomerName"
DataNavigateUrlFields="CustomerID,City"
DataNavigateUrlFormatString=
"http://xyz.com/ShowUser.aspx?id={0}&city={1}" />

</Columns>
</asp:GridView>

Detecting Client IP address

To keep track of Visitor's Record such as IP address and all
then u can use this way ,
it will display the Client proxy ip address , if the client is using Proxy server.



if (Context.Request.ServerVariables["HTTP_VIA"] != null)
{
IP = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
IP = Context.Request.ServerVariables["REMOTE_ADDR"].ToString();
}

Monday, July 13, 2009

Paging with DataList Control

DataList is a data bound list control that displays items using certain templates defined at the design time.The content of the DataList control is manipulated by using templates sections such as FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate ,AlternatingItemTemplate, EditItemTemplate and SeparatorTemplate

PagedDataSource, is a class that encapsulates the paging related properties for data-bound controls such as DataGrid, GridView, DataList, DetailsView.

Now lets take an Example of Displaying Country on Datalist with Paging

Steps.



1. Create Datalist for Country

<asp:DataList ID="dlCountry" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country_Code") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Country_Name") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>


<asp:DataList ID=" dlPaging" runat="server" OnItemCommand="dlPaging _ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="lnkbtnPaging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
</ItemTemplate>
</asp:DataList>



2. now on Code Behind write a method to fetch data from the Country’s table.

private void BindGrid()
{
string sql = "Select * from Country Order By Country_Name";
SqlDataAdapter da = new SqlDataAdapter(sql, “Yourconnectionstring”);
DataTable dt = new DataTable();
da.Fill(dt);

pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;

dlCountry.DataSource = pds;
dlCountry.DataBind();

doPaging();
}



3.Call this BindGrid method in the Page load event.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}


4.Declare a PagedDataSource object at page scope.
PagedDataSource pds = new PagedDataSource();

5. create new property call CurrentPage to maintain the latest selected page index.
and pu this code on it.

public int CurrentPage
{

get
{
if (this.ViewState["CurrentPage"] == null)
return 0;
else
return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
}

set
{
this.ViewState["CurrentPage"] = value;
}

}


6.write a method ‘doPaging’ to create a list of page numbers.

private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");
for (int i = 0; i < pds.PageCount; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}

dlPaging.DataSource = dt;
dlPaging.DataBind();
}


7. create new paging event


protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}


8. Previous And Next Button Events


protected void lnkbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
BindGrid();
}

protected void lnkbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
BindGrid();
}


9.Change PageSize Dynamically

protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentPage = 0;
BindGrid();
}



10.HighLight Selected Page Number


protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;
}
}



view Demo here

Javascript Calendar.

Calendar

is a one of Gread fucntion while retriveing date from user end , there are lot many use of calendar ex- date of Brith , Order date , Shipping Date and lot many..

in this case selecting proepr date is very imp , in term's of DD/MM/YYYY, some where using YYYY/MM/DD or MM/DD/YYYY , so in this case its its not undustable for the End user to Write Proper date in Text Box , but if you use Drop down in term of (DD/MM/YY or MM/DD/YY ) then its useful for the user ,

here i found some great Javascript code to do same ,

1.Ajax enabled DatePicker v4 :



2. VLA Calendar version 2

3.Customizable calendar component

4.jQuery:time/datePicker


5. Fancy moo tools date picker

6. Clean Calendar

7. Date picker Widget

8. Yet another JQuery Calendar

9.Simple one

hope this collection likes you.

Friday, July 10, 2009

Simple File Uploads in ASP.NET

uploading a single file from the client machine to your server.

watch live video here How to Upload

Thursday, July 9, 2009

automation for microsoft application using C#

Automation client for Microsoft Excel by using C#.
its a very basic requirement in Client side automation for Microsoft Application like
Excel / Word / OutLook / Powerpoint and all.

To Automate Excel application using C# have a look on this Article

Known Issues with Automation

Because the CLR uses a garbage collector for memory management, and because your RCW is itself a managed object, the lifetime of your Automation object is not guaranteed to end.you can get the actual help from here

317109 : Office Application Does Not Quit After Automation from Visual Studio .NET Client

Use of "IDENT_CURRENT"

in sql if we declare column as a Identity columen,as if we want to retrieve the last inserted value then use this
"IDENT_CURRENT"


All SQL Server functions that retrieve the last inserted value into the Identity column of a table - @@IDENTITY, SCOPE_IDENTITY, IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.


Use SCOPE_IDENTITY() , if you are not sure, if some triggers are going to be written or not on a table. Or, even better, use IDENT_CURRENT(tablename) to be more specific.

for more details

Wednesday, July 8, 2009

Export Gridview to xls

Now you can Export content from GridView to Excel file

1. Create one Button "Export"

<asp:Button id="Export" Text="Export" onClick="Export_Click"> </asp:Button>

2. Add this on Export Event

protected void Export_Click(object sender, EventArgs e)
{
Response.AddHeader("content-disposition", "attachment;filename=ExportData.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter SWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmWr = new HtmlTextWriter(SWrite);
GridView1.RenderControl(htmWr);
Response.Write(SWrite.ToString());
Response.End();
}


that's it

Tuesday, July 7, 2009

Limiting Data from GridView

while Desinging GridView we want some special effets like (coloring , bold, Setting width , height )
and so many , you can do this by handling event like RowCreated and implementing event handler for it OnRowCreated.


<asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />


And in your code behind you can add


protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Comments = (String)DataBinder.Eval(e.Row.DataItem, "Comment");
if (Comments != null)
{
if (Comments.Length > 30)
{
Comments = Comments.Substring(0, 40) + "...";
e.Row.ForeColor = System.Drawing.Color.red;

}
}
}
}


in that on "Comment" filed , i just simply minimize the string uptp 40 character and make it as a "RED" color.
like that you can add more feature as u want.

How To Access Content From MasterPage in ASP.NET

hi , some time we required some content from master page.
lets say we have created menu bar in Master page and i want to use that menu bar in some page
consider(Details.aspx) and my master page is ("MasterPanel.master) , now how to access master page content
to display the Menu.

MasterPanel.master

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPanel.master.cs" Inherits="MasterPanel" %>
<!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 id="Head1" runat="server">
<title>: Master Demo: </title>
</head>
<body>
<form id="form1" runat="server">
<table border="0" style="width: 100%">
<tr>
<td style="width: 100%">
<ul>
<li>File</li>
<ul>
<li>Open </li>
<li>Save </li>
</ul>
<li>Logout</li>
</ul>
</td>
</tr>
</table>
</form>
</body>
</html>



Details.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Details.aspx.cs"
Inherits="Details" <b><font color=red>MasterPageFile="~/MasterPanel.master"</font></b> %>
<asp:Content ID="Det" runat="Server" ContentPlaceHolderID="ContentPlaceHolder1">

//Menu source will come

</asp:Content>

in Details.aspx we have add MasterPageFile as "~/MasterPanel.master" so it will inclue all the
content from master page . by using <asp:Content> you can place that menu where you want in
Details.aspx page

That's it

Happy coding ......

Monday, July 6, 2009

How to Access Outlook Emails with ASP.NET ,C#

Hi,
on my first post, i have covered how to add Refrences
on you'r .net application
now we require same thing to Send / Receive Mail via outlook using ASP.NET.
To acquire these, all you need is Interop.Outlook.dll.

Stpes :
1. Create one Project as "OutlookSendReceive" .
2. include "Bin" folder on same , right click on it , select Add refrence
then click tab "COM " and select " Microsoft Outlook 11.0 " click ok

3. it will add assemblies on you'r web.config page
like

<assemblies>
<add assembly="Microsoft.Office.Interop.Outlook, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e29c34"/>
</assemblies>

4. Define
"using Microsoft.Office.Interop.Outlook;
using System.Text;"

5. copy that code on Page_load() event


Microsoft.Office.Interop.Outlook.Application nOutlook;
Microsoft.Office.Interop.Outlook.NameSpace oNs;
Microsoft.Office.Interop.Outlook.MAPIFolder oFldr;

try
{
nOutlook = new Microsoft.Office.Interop.Outlook.Application();
oNs = nOutlook.GetNamespace("MAPI");

//getting mail folder from inbox
oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Response.Write("Total Mail in Inbox :" + oFldr.Items.Count + "
");
Response.Write("Total Unread items = " + oFldr.UnReadItemCount);
foreach (Microsoft.Office.Interop.Outlook.MailItem oMessage in oFldr.Items)
{
StringBuilder str = new StringBuilder();
str.Append("<table><tr><td><b>Sender :</b></td><td>");
str.Append(oMessage.SenderEmailAddress.ToString() + "</td></tr>");

//Define Additional Information of Message
str.Append("<tr><td><b>Date :</b></td><td>" + oMessage.SentOn.ToShortDateString() + "</td></tr>");
if (oMessage.Subject != null)
{
str.Append("<tr><td><b>Subject :</b></td><td>" + oMessage.Subject.ToString() + "</td></tr>");
}

str.Append("</table><br>");
Response.Write(str.ToString());
}

}
catch (System.Exception ex)
{
Response.Write("Execption generated:" + ex.Message);
}
finally
{
GC.Collect();
oFldr = null;
oNs = null;
nOutlook = null;
}




like this way you can access Outlooks mail ,
thank you,
will come up more on how to access gmail /yahoo mail directly

Using Parameters with the SqlDataSource Control

When using the SqlDataSource control, you can specify SQL queries and statements that use parameters. This helps make your data-binding scenarios more flexible by
reading and writing database information based on values




how to Specifying Parameters in Commands
When you use the SqlDataSource control, you can set the control's command properties to parameterized SQL statements or to the name of a stored procedure.
The SqlDataSource control adds the value of the ParameterPrefix property to the beginning of all parameter names. (The default prefix is "@".)


Using Parameters with the SqlClient Provider:
By default, the SqlDataSource control uses the System.Data.SqlClient data provider to work with SQL Server as the data source. The System.Data.SqlClient provider supports named parameters as placeholders, as shown in the following example:


SELECT * FROM Stud WHERE Rollno = @Rno
AND Name = @Name


The following example shows how to use parameters in an SQL command for a SqlDataSource control that uses the System.Data.SqlClient provider

[C# code]

<asp:sqlDataSource ID="StudInfo"
SelectCommand="SELECT Marks,Rollno,ID FROM Stud WHERE Rollno = @Rno"
ConnectionString="<%$ ConnectionStrings:Stud %>" RunAt="server">
<SelectParameters>
<asp:Parameter Name="Rno" Type="Int32" DefaultValue="0" />
</SelectParameters>

//Suppose for insert query
<InsertParameters>
<asp:Parameter Name="abc" Type="String" />
<asp:Parameter Name="xyz" Type="String" />
</InsertParameters>

// for update
<UpdateParameters>
<asp:Parameter Name="abc" Type="String" />
</UpdateParameters>

//you can also use Seesion Parameter

<SelectParameters>
<asp:SessionParameter
Name="Rollno"
SessionField="Rno"
DefaultValue="1" />
</SelectParameters>

// also pass via querystring
<SelectParameters>

<asp:QueryStringParameter Name="Rollno" QueryStringField="rno" Type="int" />

</SelectParameters>


like this u can access Parameters with the SqlDataSource Control
also refer This Article