Thursday, December 31, 2009

Stored procedure:Out put Parameter..using @@rowcount

Please check the below example:

alter PROCEDURE UpdateLogin
@UserName nvarchar(15),
@UpdateCount int OUTPUT
AS
update login set username=@UserName where userid<4
select @UpdateCount = @@rowcount
RETURN @UpdateCount

DECLARE @TheCount INT
exec UpdateLogin @UserName = 'sa', @UpdateCount = @TheCount OUTPUT
SELECT TheCount = @TheCount

DataGrid--->Sample for Accessing no of row for a 'Single Click'


CODE PART
..


//The links important..
http://www.codedigest.com/Articles/ASPNET/132_GridView_with_CheckBox_%E2%80%93_Select_All_and_Highlight_Selected_Row.aspx
http://ramanisandeep.wordpress.com/tag/checkuncheck-all-items-in-an-asp-net-checkbox-list-using-jquery/
http://fun2code.blogspot.com/


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 Connection;

public partial class FakeMemberMark : System.Web.UI.Page
{
ClsConnection objCon = new ClsConnection();
string sqlStr = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Session["adminloginname"] = "satheesh";
Label5.Visible = false;

if ((string)Session["adminloginname"] != null)
{
if (!IsPostBack)
{
lblcaption.Text = "Admin � Fake Member Marking";
Label2.Text = "[ Hi, " + Session["adminloginname"].ToString() + "| <a href=adminwelcome.aspx>Control panel</a> | <a href=adminlogout.aspx >Logout</a> ]";
loadGrid();

}
}
else
{
Response.Redirect("adminlogin.aspx");
}
}
catch
{
Response.Redirect("adminlogin.aspx");
}
}



protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState ==DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
//{
// CheckBox chkBxSelect = (CheckBox)e.Row.Cells[1].FindControl("chkBxSelect");
// CheckBox chkBxHeader = (CheckBox)this.GridView1.HeaderRow.FindControl("chkAll");
// chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,'{0}');",chkBxHeader.ClientID);
//}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblIsFake = (Label)e.Row.FindControl("lblIsFake");
string IsFake = lblIsFake.Text.Trim().ToString();
CheckBox chkBxSelect = (CheckBox)e.Row.FindControl("chkBxSelect");
if (IsFake == "True")
{
chkBxSelect.Checked = true;
}
else
{
chkBxSelect.Checked = false;
}
try
{
HyperLink Hyperphotourl = (HyperLink)e.Row.FindControl("Hyperphotourl");

string HomeUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();//
string photourl = HomeUrl + "/" + Hyperphotourl.ImageUrl.ToString();
Hyperphotourl.ImageUrl = photourl;

Label lblusername = (Label)e.Row.FindControl("lblusername");
Hyperphotourl.NavigateUrl = "../" + lblusername.Text.ToString() + "/profile";
}
catch
{
}

}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{


try
{
Label5.Visible = true;
if (e.CommandName == "SET")
{
int IsFake = 0;
for (int i = 0; i < GridView1.Rows.Count; i++)
{

int userid = int.Parse(GridView1.Rows[i].Cells[0].Text.ToString());
CheckBox chbTemp = GridView1.Rows[i].FindControl("chkBxSelect") as CheckBox;
if (chbTemp.Checked)
{
// Response.Write(GridView1.Rows[i].Cells[0].Text + "<BR>");
IsFake = 1;
}
UpdateTheDetails(userid, IsFake);
}
Label5.Visible = true;
Label5.Text = "Success..Marked the Fake Members Successfully..";
}
}
catch { }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{

foreach (GridViewRow row in GridView1.Rows) //GridView1.PageSize * GridView1.PageCount
{
int IsFake = 0;
//Label lfilName = (Label)row.FindControl("lblfilename");
int userid = int.Parse(row.Cells[0].Text.ToString());

CheckBox chbTemp = (CheckBox)row.FindControl("chkBxSelect");
if (chbTemp.Checked)
{

IsFake = 1;
}
UpdateTheDetails(userid, IsFake);
}
Label5.Visible = true;
Label5.Text = "Success..Marked the Fake Members Successfully..";
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Label5.Visible = false;
GridView1.PageIndex = e.NewPageIndex;
loadGrid();
}

//the functions listed below...................
private bool UpdateTheDetails(int userid, int IsFake)
{
bool status = false;
try
{
sqlStr = "Update membersetting set IsFake=" + IsFake + " where userid=" + userid;
if (objCon.SqlExecuteQuery(sqlStr) == "Success")
{
status = true;
}
}
catch { }
return status;
}
private void loadGrid()
{
GridView1.Visible = false;
try
{
DataSet ds = GetUserDetails();
if (ds.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Visible = true;
}
else
{
Label5.Visible = true;
Label5.Text = "Sorry No User Details found";
}
}
catch
{
}
}
public DataSet GetUserDetails()
{
DataSet ds = new DataSet();
try
{

string sqlStr = "select l.userid,l.username,m.firstname,m.email,r.photourl,isnull(ms.IsFake,0) as IsFake from membermaildetails m,login l,registration r,membersetting ms where l.userid= m.loginid and r.loginid=m.loginid and ms.userid= m.loginid order by l.userid";
ds = objCon.SelectDataset(sqlStr, "0");
}
catch
{
}
return ds;
}


}

//*******************************************************************************



DESIGN PART
..


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FakeMemberMark.aspx.cs" Inherits="FakeMemberMark" %>

<!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 >
<script type="text/javascript">

function HighlightRow(chkB)

{

var IsChecked = chkB.checked;

if(IsChecked)

{

chkB.parentElement.parentElement.style.backgroundColor='black';

chkB.parentElement.parentElement.style.color='white';

}else

{

chkB.parentElement.parentElement.style.backgroundColor='white';

chkB.parentElement.parentElement.style.color='black';

}

}
function SelectAllCheckboxesSpecific(spanChk)

{

var IsChecked = spanChk.checked;

var Chk = spanChk;

Parent = document.getElementById('GridView1');

var items = Parent.getElementsByTagName('input');

for(i=0;i<items.length;i++)

{

if(items[i].id != Chk && items[i].type=="checkbox")

{

if(items[i].checked!= IsChecked)

{

items[i].click();

}

}

}

}
//*******************************************new one not using*******************

var TotalChkBx;

var Counter;

window.onload = function()

{

//Get total no. of CheckBoxes in side the GridView.

TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');

//Get total no. of checked CheckBoxes in side the GridView.

Counter = 0;

}

function HeaderClick(CheckBox)

{

//Get target base & child control.

var TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');

var TargetChildControl = "chkBxSelect";



//Get all the control of the type INPUT in the base control.

var Inputs = TargetBaseControl.getElementsByTagName("input");



//Checked/Unchecked all the checkBoxes in side the GridView.

for(var n = 0; n < Inputs.length; ++n)

if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl,0) >= 0)

Inputs[n].checked = CheckBox.checked;

//Reset Counter

Counter = CheckBox.checked ? TotalChkBx : 0;

}

function ChildClick(CheckBox, HCheckBox)

{

//get target base & child control.

var HeaderCheckBox = document.getElementById(HCheckBox);



//Modifiy Counter;

if(CheckBox.checked && Counter < TotalChkBx)

Counter++;

else if(Counter > 0)

Counter--;



//Change state of the header CheckBox.

if(Counter < TotalChkBx)

HeaderCheckBox.checked = false;

else if(Counter == TotalChkBx)

HeaderCheckBox.checked = true;

}


</script>
<title>Affiliser Admin � Fake Member Marking</title>
<link rel="stylesheet" type="text/css" href="StyleSheet.css" />
</head>
<body>



<div class="FormHeadingDiv"> Affiliser Admin � Fake Member Marking</div>
<div style="text-align:center;background-color:#E7DBD5">
<form id="form1" runat="server">
<div class="xLabelUserInfo"><asp:Label ID="Label2" runat="server" Text=""></asp:Label></div>



<div >
<div>
&nbsp;
<asp:Label ID="lblcaption" runat="server" BackColor="Olive" Font-Bold="True" Font-Names="Arial" Font-Size="Medium" ForeColor="PaleGreen" Width="123px" ></asp:Label><br />
&nbsp;</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<progresstemplate>
<strong>Please wait..Processing....</strong><br />
<img src="http://affiliser.com//images/site/ajax-loader.gif" />
</progresstemplate>
</asp:UpdateProgress>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<contenttemplate>
<div> <asp:Label ID="Label5" runat="server" ></asp:Label><br />
&nbsp;</div>
<div>

<asp:GridView ID="GridView1" CssClass="xGridViewPro" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#010101" BorderStyle="Groove" BorderWidth="1px" CellPadding="4" AllowPaging="True" ShowFooter="True" OnRowCommand="GridView1_RowCommand" OnRowCreated="GridView1_RowCreated" OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="userid" HeaderText="userid" Visible="true"/>
<asp:TemplateField HeaderText="userid" Visible="false">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Bind("userid") %>' ></asp:Label>
</ItemTemplate>

</asp:TemplateField>


<asp:TemplateField HeaderText="username">

<ItemTemplate>
<asp:Label ID="lblusername" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>


</asp:TemplateField>

<asp:TemplateField HeaderText="firstname">

<ItemTemplate>
<asp:Label ID="lblfirstname" runat="server" Text='<%# Bind("firstname") %>'></asp:Label>
</ItemTemplate>


</asp:TemplateField>

<asp:TemplateField HeaderText="lastname">
<ItemTemplate>
<asp:Label ID="lblastname" runat="server" Text='<%# Bind("email") %>' ></asp:Label>
</ItemTemplate>

</asp:TemplateField>
<asp:TemplateField HeaderText="Photo">
<ItemTemplate>
<asp:HyperLink ID="Hyperphotourl" runat="server" ImageUrl='<%#Bind("photourl")%>' NavigateUrl='<%#Bind("photourl")%>'>Photo</asp:HyperLink>
</ItemTemplate>

</asp:TemplateField>



<asp:TemplateField ControlStyle-BackColor="AliceBlue" FooterStyle-BackColor="graytext" >

<HeaderTemplate>

<asp:CheckBox ID="chkAll" onclick="javascript:SelectAllCheckboxesSpecific(this);" runat="server" Text="Select" />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox onclick="javascript:HighlightRow(this);" ID="chkBxSelect" runat="server" />

</ItemTemplate>

<FooterTemplate>
<asp:Button ID="BtnSET" runat="server" Text="SET" CommandName="SET" Height="33px" Width="99px" />
</FooterTemplate>


</asp:TemplateField>

<asp:TemplateField HeaderText="IsFake" Visible="false">
<ItemTemplate>
<asp:Label ID="lblIsFake" runat="server" Text='<%# Bind("IsFake") %>'></asp:Label>
</ItemTemplate>

</asp:TemplateField>

</Columns>


<FooterStyle BackColor="White" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />



</asp:GridView>
</div>
</contenttemplate>
</asp:UpdatePanel>
<br />
<asp:Button ID="btnSubmit" runat="server" Height="35px" OnClick="btnSubmit_Click" Text="Submit"
Width="99px" /><br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />


</div>




</form>
</div>







</body>
</html>

Saturday, December 19, 2009

Some tips image url

bnrimg.InnerHtml = "<a href=" + ds.Tables[0].Rows[0][1].ToString() + " target=_blank><img width=468 height=60 border=0 src=" + ds.Tables[0].Rows[0].ItemArray[0].ToString() + " /></a>";

//Thumbnail

System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)Parent.Page.FindControl("profImg");
dynDiv.InnerHtml = "";

System.Web.UI.WebControls.Label LabelParentfullname = (System.Web.UI.WebControls.Label)Parent.Page.FindControl("lblfullname");
LabelParentfullname.Text = fullNameN;

File Upload in Asp.net

private string IMAGEurl()
{
string saveLocation = "";
string imageurl = "/images/thumbnail/UnknownSuper.gif";
try
{
string imageName = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf("\\") + 1);
string extention = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf("."));

saveLocation = string.Empty;
saveLocation = Server.MapPath("/images/user");

imageName = txtUsername.Text.ToString() + extention;

saveLocation = saveLocation + "/" + imageName;
// jerry 01-07-2009
Bitmap photo = objvalid.ResizeImage(File1.PostedFile.InputStream, 300, 300);// width height
photo.Save(saveLocation);
//
// File1.PostedFile.SaveAs(saveLocation);

saveLocation = string.Empty;
saveLocation = Server.MapPath("/images/thumbnail");
saveLocation = saveLocation + "/" + imageName;
Bitmap photoFile = objvalid.ResizeImage(File1.PostedFile.InputStream, 64, 64);// width height
photoFile.Save(saveLocation);
imageurl = "/images/thumbnail/" + imageName;
}
catch
{ }
return imageurl;
}

Friday, December 18, 2009

DataSet Creation Dynamically

DataSet Ds = new DataSet();
DataTable Dt = new DataTable();
Ds.Tables.Add(Dt);
Dt.Columns.Add("F_Name");
Dt.Columns.Add("S_Name");
DataRow Dr = Dt.NewRow();
Dt.Rows.Add(Dr);
Dr["F_Name"]="satheesh";
Dr["S_Name"]="mnair";

Tuesday, December 15, 2009

DataGrid--Sample Code

//THE HTML TAGS OF A DATAGRID


<div>
<asp:GridView ID="GridView1" CssClass="xGridViewPro" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="300px" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating" AllowPaging="True" ShowFooter="True" OnRowCommand="GridView1_RowCommand" OnPageIndexChanging="GridView1_PageIndexChanging" >
<Columns>

<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtnameEdit" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtfootName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Value">

<ItemTemplate>
<asp:Label ID="lblvalue" runat="server" Text='<%# Bind("value") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtValueEdit" runat="server" Text='<%# Bind("value") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtfootValue" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Comment">

<ItemTemplate>
<asp:Label ID="lblcomment" runat="server" Text='<%# Bind("comment") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtcommentEdit" runat="server" Text='<%# Bind("comment") %>'> </asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtfootComment" runat="server"></asp:TextBox>

</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("id") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="BtnADD" runat="server" Text="Add" CommandName="addrow" />
</FooterTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="rowdelete" Text="Delete" />
<asp:CommandField ShowEditButton="True" />

</Columns>

<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>


*******************************************************************************

IN CODE BEHIND-->CODE SAMPLE



protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
Label5.Visible = false;
GridView1.EditIndex = e.NewEditIndex;
loadGrid();

}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
int index = GridView1.EditIndex;
int a = e.RowIndex;
GridViewRow row = GridView1.Rows[index];


Label Codelblid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblid");
TextBox CodetxtnameEdit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtnameEdit");
TextBox CodetxtValueEdit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtValueEdit");
TextBox CodetxtcommentEdit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtcommentEdit");

string id = Codelblid.Text;
string name = CodetxtnameEdit.Text;
string value = CodetxtValueEdit.Text;
string comment = CodetxtcommentEdit.Text;

Label5.Visible = true;
if (UpdateTheDetails(id, name, value, comment))
{
try
{
GlobalValues objGlob = GlobalValues.SET();
}
catch
{
}
GridView1.EditIndex = -1;
loadGrid();
Label5.Text = "Global value Updated Successfully";


}
else
{
Label5.Text = "Sorry..Error ocuured..Global values not updated..";
Label5.BackColor = Color.Red;
}
}
catch { }

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
Label5.Visible = false;
GridView1.EditIndex = -1;
loadGrid();
}

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
Label5.Visible = true;

if (e.CommandName == "addrow")
{

// int index = Convert.ToInt32(e.CommandArgument);

TextBox CodetxtnameEdit = (TextBox)GridView1.FooterRow.FindControl("txtfootName");
TextBox CodetxtValueEdit = (TextBox)GridView1.FooterRow.FindControl("txtfootValue");
TextBox CodetxtcommentEdit = (TextBox)GridView1.FooterRow.FindControl("txtfootComment");
string name = CodetxtnameEdit.Text;
string value = CodetxtValueEdit.Text;
string comment = CodetxtcommentEdit.Text;
string validSTR=Validate(name, value, comment);
if (validSTR == "true")
{
if (INSERTTheDetails(name, value, comment))
{
loadGrid();

}
}
else
{

Label5.BackColor = Color.Red;

}

}
else if (e.CommandName == "rowdelete")
{
int index = Convert.ToInt32(e.CommandArgument);

Label Codelblid = (Label)GridView1.Rows[index].FindControl("lblid");
string id = Codelblid.Text;
if (DELETETheDetails(id))
{
loadGrid();

}

}
}
catch { }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
Label5.Visible = false;
GridView1.PageIndex = e.NewPageIndex;
loadGrid();
}

SQL Server Constraints Alexander Chigrik

/*1)Tablename-C_ActiorType
fields--ActiorID--->Pk
--Name --->UK
2)Tablename-C_CreditsMatrix
fields--ActorID---->Fk of ActiorID in C_ActiorType
*/

/* settng the primary key constraint...Unique and not allow null*/
ALTER TABLE C_ActiorType
ADD CONSTRAINT pk_ActiorID PRIMARY KEY (ActiorID)
GO

/*setting the Unique key constraint.....unique&can allow only one null*/
ALTER TABLE C_ActiorType ADD CONSTRAINT IX_Name UNIQUE(Name)
GO

/*drop the constraint*/
ALTER TABLE C_ActiorType drop CONSTRAINT IX_ActorID
GO
/*creating the foriegn key for another primary key*/
ALTER TABLE C_CreditsMatrix
ADD CONSTRAINT fk_ActorID
FOREIGN KEY (ActorID)
REFERENCES C_ActiorType (ActiorID) ON DELETE CASCADE
GO

//Please Refer this links

http://blog.sqlauthority.com/2007/02/05/sql-server-primary-key-constraints-and-unique-key-constraints/

http://mssqlserver.wordpress.com/2006/11/22/difference-between-unique-constraint-and-primary-key/

http://www.mssqlcity.com/Articles/General/using_constraints.htm

Monday, December 7, 2009

State Manaement-Good Article

Please Refer this link

http://www.dotnetjohn.com/articles.aspx?articleid=32

Cache-Asp.net simple example with concept

Please Refer this urls:

http://www.codeproject.com/KB/web-cache/cachingaspnet.aspx
http://aspalliance.com/795_Caching_in_ASPNET

Saturday, December 5, 2009

Impersonation in ASP.NET

Please redfer the urls:

http://www.4guysfromrolla.com/articles/031204-1.aspx
http://www.dotnet-guide.com/impersonation.html

Wednesday, December 2, 2009

Connection Class and WebConfig(Sample using for a application)

//***********a)CONNECTION CLASS(in C#)***********
using System;
using System.Data;
using System.Configuration;
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 System.Data.SqlClient;


namespace Connection
{

public class ClsConnection
{


private SqlConnection conSQL;
// private string conString = "server=SYS9;uid=root; password=integral; database=dbsuperlistexplode;";
// private string conString = ConfigurationSettings.AppSettings["constringLogin"].ToString();
private string conString = ConfigurationManager.ConnectionStrings["conStrSuperListExplode"].ToString();


//private MySqlConnection consql=new MySqlConnection(ConfigurationSettings.AppSettings(conStrTutorinn);



//-----------------------------------------------------------------------------------
string _SuccessMsg;
public string SuccessMsg //success message - cannot always be returned, so we have a read only access method..
{
get { return _SuccessMsg; }
set { _SuccessMsg = value; }
}
//-----------------------------------------------------------------------------------------
public ClsConnection()//Constructor
{

//conSQL = new MySqlConnection(ConnectionStringSettings["constringLogin"]);
conSQL = new SqlConnection(conString);
}

public string SqlExecuteQuery(string str)
{
try
{
conSQL.Open();
SqlCommand cmd = new SqlCommand(str, conSQL);
cmd.ExecuteNonQuery();
conSQL.Close();
SuccessMsg = "Success";
return SuccessMsg;
}
catch (Exception e)
{
conSQL.Close();
SuccessMsg = e.Message;
return SuccessMsg;
}

}
//-----------------------------------------------------------------------------------------
public bool SQLReturnBool(string sqlstr)
{

bool retval;
try
{
conSQL.Close();
conSQL.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conSQL);
int retvalbool = int.Parse(cmd.ExecuteScalar().ToString());
if (retvalbool == 1) retval = true;
else retval = false;
conSQL.Close();
}
catch (Exception ex)
{
conSQL.Close();
SuccessMsg = ex.Message;
retval = false;
}
return retval;
}

//-----------------------------------------------------------------------------------------
public int SQLReturnInteger(string sqlstr)
{

int retval;
try
{
conSQL.Close();
conSQL.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conSQL);
retval = int.Parse(cmd.ExecuteScalar().ToString());
conSQL.Close();
}
catch (Exception ex)
{
conSQL.Close();
SuccessMsg = ex.Message;
retval = 0;
}
return retval;
}

//-----------------------------------------------------------------------------------------
public float SQLReturnFloat(string sqlstr)
{
float retval;
try
{
conSQL.Close();
conSQL.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conSQL);
retval = float.Parse(cmd.ExecuteScalar().ToString());
conSQL.Close();
}
catch (Exception ex)
{
conSQL.Close();
SuccessMsg = ex.Message;
retval = 0;
}
return retval;
}
//-----------------------------------------------------------------------------------------
public string SQLReturnString(string sqlstr)
{
string retval;
try
{
conSQL.Close();
conSQL.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conSQL);
retval = cmd.ExecuteScalar().ToString();
SuccessMsg = "Success";
conSQL.Close();
}
catch (Exception ex)
{
conSQL.Close();
SuccessMsg = ex.Message;
retval = "";
}
return retval;
}

//-----------------------------------------------------------------------------------------



public DataSet SelectDataset(string sqlstr, string sqltbl)
{
DataSet dssql = new DataSet();
try
{
if (conSQL.State == ConnectionState.Open)
{
conSQL.Close();
conSQL.Open();
}
else
{
conSQL.Open();
}

SqlDataAdapter dasql = new SqlDataAdapter(sqlstr, conSQL);

dasql.Fill(dssql, sqltbl);

}
catch (Exception ex)
{
SuccessMsg = ex.Message;
conSQL.Close();
}
conSQL.Close();
return dssql;
}

public byte[] SQLReturnByte(string sqlstr)
{
byte[] Rblob = null;
// try
// {
conSQL.Close();
conSQL.Open();
SqlCommand cmd = new SqlCommand(sqlstr, conSQL);
SqlDataReader MyReader = cmd.ExecuteReader();
if (MyReader.Read())
{
//byte[] m_MyImage = (byte[])MyReader["pimage"];
Rblob = (byte[])MyReader[0];
//Response.BinaryWrite(retval);

}
//retval[]= Convert.ToBase64CharArray(cmd.ExecuteScalar().ToString());
SuccessMsg = "Success";
conSQL.Close();

// }
// catch (Exception ex)
// {
// conSQL.Close();
// SuccessMsg=ex.Message;
// //retval= "";
//
// }
return Rblob;

}


}
}

//-------------------------------------------------------------------------------

// **********b)WEBCONFIG****************


<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>

<appSettings>
<add key="ChooseMode" value="TEST"/>
<!--
Set ChooseMode as TEST for test server.
Set ChooseMode as LIVE for live server.
-->
<add key="mailFrmPrimestreams.SendMail" value="http://primestreams.net/SendMail.asmx"/>
</appSettings>
<connectionStrings>
<add name="conStrSuperListExplode" connectionString="Data Source=SYS26\SQLEXPRESS;Initial Catalog=dbAffiliser;User ID=sa;Password=integraloffice"/>
<add name="dbAffiliserConnectionString" connectionString="Data Source=SYS26\SQLEXPRESS;Initial Catalog=dbAffiliser;User ID=sa;Password=integraloffice" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</controls>
</pages>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<sessionState mode="InProc" cookieless="false" timeout="30"></sessionState>
<identity impersonate="true" />
<httpHandlers>
<add verb="GET" path="FtbWebResource.axd" type="FreeTextBoxControls.AssemblyResourceHandler, FreeTextBox" />
<add verb="GET" path="CaptchaImage.aspx" type="WebControlCaptcha.CaptchaImageHandler, WebControlCaptcha" />
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

</httpHandlers>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<!--jerry-->
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->

<customErrors mode="Off" />
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>

</system.web>
<system.web.extensions>
<scripting>
<webServices>
<!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
<!--
<jsonSerialization maxJsonLength="500">
<converters>
<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
</converters>
</jsonSerialization>
-->
<!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
<!--
<authenticationService enabled="true" requireSSL = "true|false"/>
-->
<!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
writeAccessProperties attributes. -->
<!--
<profileService enabled="true"
readAccessProperties="propertyname1,propertyname2"
writeAccessProperties="propertyname1,propertyname2" />
-->
</webServices>
<!--
<scriptResourceHandler enableCompression="true" enableCaching="true" />
-->
</scripting>



</system.web.extensions>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
</configuration>

SQL-The Language Specifications:

The Language Specifications::

http://treasure4developer.wordpress.com/2009/07/12/what-are-the-difference-between-ddl-dml-and-dcl-commands/
http://www.orafaq.com/faq/what_are_the_difference_between_ddl_dml_and_dcl_commands

Roll Back And TRY - CATCH to Rollback a Transaction - SQL Server

Defenition:-

a rollback is an operation which returns the database to some previous state. Rollbacks are important for database integrity,
because they mean that the database can be restored to a clean copy even after erroneous operations are performed.


. A transaction begins with the execution of a SQL-Data statement when there is no current transaction. All subsequent SQL-Data statements until COMMIT or ROLLBACK become part of the transaction. Execution of a COMMIT Statement or ROLLBACK Statement completes the current transaction.

COMMIT Statement
The COMMIT Statement terminates the current transaction and makes all changes under the transaction persistent. It commits the changes to the database. The COMMIT statement has the following general format:

COMMIT [WORK]

WORK is an optional keyword that does not change the semantics of COMMIT.

ROLLBACK Statement
The ROLLBACK Statement terminates the current transaction and rescinds all changes made under the transaction. It rolls back the changes to the database. The ROLLBACK statement has the following general format:

ROLLBACK [WORK]

The major link for refferring these is:

http://www.eggheadcafe.com/tutorials/aspnet/6a8ef7d5-840e-4629-b53a-1a40e7db601f/using-try--catch-to-roll.aspx

Click to View in Detail

Triggers: Defenition

It is a piece of SQL that is activated when a certain event happens or occurs.

The Major Links are,

http://www.datasprings.com/Resources/ArticlesInformation/CreatingEmailTriggersinSQLServer2005.aspx
http://www.sqlteam.com/article/using-ddl-triggers-in-sql-server-2005-to-capture-schema-changes
http://msdn.microsoft.com/en-us/library/ms189799.aspx

Triggers: Sample DDL trigger for Database

CREATE trigger [SQLInfoNewTrigger]
on database
for create_procedure, alter_procedure, drop_procedure, --events
create_table, alter_table, drop_table,
create_function, alter_function, drop_function
as
set nocount on
declare @data xml
set @data = EVENTDATA()

insert into databasename.dbo.SQLINFONEW(DatabaseName,EventType,ObjectName,ObjectType,LoginName,TSQLCommand,date)
values
(@data.value('(/EVENT_INSTANCE/DatabaseName)[1]','varchar(50)'),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)'),
@data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(50)'),
@data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(50)'),
@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(50)'),
@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)'),

getdate()
)

Triggers: Sample DML trigger

CREATE trigger [dbo].[Triggername]
ON [dbo].[Table_exist]
FOR update
AS

declare @userid int
select @userid=userid from deleted d
insert into Tble (userid) values(@userid)

Wednesday, November 18, 2009

Aboug WPF refer links

http://www.wpftutorial.net/LearnWPFin14Days.html
http://windowsclient.net/learn/videos_wpf.aspx
http://idealprogrammer.com/languages/visual-basic-vbnet/windows-presentation-foundation-18-hours-of-free-video-tutorials/

Friday, November 13, 2009

Global.ascx

<%@ Application Language="C#" %>

<script runat="server">


void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["Hits"] = 0;
Application["Sessions"] = 0;
Application["TerminatedSessions"] = 0;
}
//new
//The BeginRequest event is fired for every hit to every page in the site
void Application_BeginRequest(Object Sender, EventArgs e)
{
Application.Lock();
Application["Hits"] = (int) Application["Hits"] + 1;
Application.UnLock();
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
Application["Sessions"] = (int) Application["Sessions"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

Application.Lock();
Application["TerminatedSessions"] =
(int) Application["TerminatedSessions"] + 1;
Application.UnLock();
}
void Application_End(object sender, EventArgs e)
{

string _write="Total Hits="+Application["Hits"].ToString()+"<br>Total Sessions="+Application["Sessions"].ToString()+"<br>Expired Sessions:="+Application["TerminatedSessions"].ToString();
// Code that runs on application shutdown
//Write out our statistics to a log file
//...code omitted...
System.Collections.Generic.List<string> allLines = new System.Collections.Generic.List<string>();
allLines.Add(_write);
string[] _LastContent = allLines.ToArray();

System.IO.File.WriteAllLines("merged.txt", _LastContent);

}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs

}

//The global.asax file in Listing 3.8 contains event handlers for the Session and Application objects. Each event handler has the same signature as the Page_Load event handler.
//The code in Listing 3.8 handles three Application object-related events: Start (Lines 3-8), End (Lines 24-30), and BeginRequest (Lines 11-16). Start and End are called when the Web application starts and ends, respectively. BeginRequest is called for every page hit that the site receives. Listing 3.8 updates the total number of hits on this event.
//The Session Start (Lines 17-22) and End (Lines 24-30) events are handled in the middle of the listing. These two events count how many different Web users have accessed the site.
//You can write a simple page to utilize the statistics that Listing 3.8 tracks. Listing 3.9 shows a page that writes out the results of the hit-counting code

</script>

//------------------------------The links----------------
Detals about global.ascx

Tuesday, October 27, 2009

Making querry from exel or Csv

using System.Collections.Generic;
List<string> allLines = new List<string>();
allLines.Clear();
string[] ldf = { "#$#" }; //put the character "#$#" instead of space..
string[] lines = File.ReadAllLines("D:\stringfile.txt");
string curLine = String.Empty;
for (int j = 0; j < lines.Length; j++)
{
curLine = Insert(lines[j].Split(ldf, StringSplitOptions.None)[0].Replace("'", "''"), lines[j].Split(ldf, StringSplitOptions.None)[1].Replace("'", "''"), 5);
allLines.Add(curLine);
}
string[] _allLines = allLines.ToArray();
File.WriteAllLines("Querrymerged.txt", _allLines);

//Function making the querry using string
private string Insert(string text1, string text2, string no)
{
return "Insert into table (no,feild1,feild2) values (" + no+ ",'" + text1 + "','" + text2 + "')";
}

Thursday, October 8, 2009

SQL-finding duplicate row in table

The querry is

select userid from table group by userid having (count(*)>1) or
select userid from table group by userid having (count(userid)>1)

GridVeiw ; Dropdownlist filling in editing mode

//In editing the dropdownlist is filling On DataGrid

<asp:TemplateField HeaderText="Business Type">
<EditItemTemplate>
<asp:DropDownList ID="DDLedit" runat="server" ></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>





//**Gridview1_RowDataBound
DataSet Ds;

if (e.Row.RowType == DataControlRowType.DataRow)
{
//if (Gridview1.EditIndex == e.Row.RowIndex)
if((e.Row.RowState & DataControlRowState.Edit)>0)
{
DropDownList dx = new DropDownList();
dx = (DropDownList)e.Row.FindControl("DDLedit");
Ds1 = getUserDetails(); //Get username and userid
dx.DataSource = Ds1;
dx.DataTextField = "username";
dx.DataValueField = "userid";
dx.DataBind();
}

Frame Page using C#

using System.Text;

Response.Write(GEtFramePage(userid).Tostring());

//the method is following..
public string GEtFramePage(string userid)
{
System.Text.StringBuilder strbuild = new System.Text.StringBuilder();
string BottomURL= "https://gmail.com";
TrafficName = getTrafficName1(userid);
StringBuilder str = new StringBuilder();
str.Append("</body></html><html><head>");
str.Append("<frameset rows=79px,* FRAMEBORDER=NO FRAMESPACING=0 BORDER=0>");
str.Append("<frame id=topframe src=toppage.aspx?userid=" + userid + " frameborder=0 MARGINWIDTH=0 MARGINHEIGHT=0 scrolling=no>");
// str.Append("<iframe src =\""+ BottomURL+"\" width=\"100%\" height=\"100%\">");
str.Append("<frame id=urlframe src=" + BottomURL+ "");
str.Append(" MARGINWIDTH=0 MARGINHEIGHT=0>");
str.Append("</frameset>");
str.Append("</head></html>");
string test = str.ToString();
return str.ToString();
}

Session Removing

string mid = "satheesh";
//*************clear the session of the mid

Session[mid] = null;
Session.Remove(mid);
Session.Contents.Remove(mid);
//************************************************

DropDownList Related

//Find the Index of an item--
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(ddlBusName.Items.FindByText("-Select name-"));

SQL-Stored Procedure(Example)

CREATE procedure [dbo].[sp_Example](@tablename varchar(30))
As /*BY Satheesh 14-09-2009 */
begin
DECLARE @userid int,@count int,@id int

DECLARE @Table_Cursor CURSOR
SET @Table_Cursor=CURSOR FAST_FORWARD FOR select distinct userid from memberblog
--close @Table_Cursor

open @Table_Cursor
fetch next from @Table_Cursor into @userid
while @@FETCH_STATUS = 0
BEGIN
select @count=Count(*) from memberblog where userid=@userid
select @id=isnull(min(id),0) from memberactivitycount where userid=@userid

if(@id>0)
begin
--update
update memberactivitycount set blog=@count where id=@id
end
else
begin
--insert
insert into memberactivitycount (userid, blog ) values (@userid,@count)
end
fetch next from @Table_Cursor into @userid
END
close @Table_Cursor
deallocate @Table_Cursor

/* Excecuting another sp --example is -->exec sp_sentmessage */
/* Excecuting a function from sp --example is -->if dbo.FunctionExm(@MemberID,@UserID)=1 */
end

SQL- function(Example)

/*check whether a member is downline or not
jerome 5_9_09
if a member is downline it return 1 other wise 0
*/
ALTER function [dbo].[IsSponsor](@MemberID int,@UserID int)RETURNS int
as begin
declare @status int,@TempID int
set @status=0
set @TempID=@UserID
if @MemberID=@UserID
set @status=1
else
begin
while @TempID>0
begin
select @TempID=isnull(min(userid),0) from login where username=(select sponsorid from registration where loginid=@UserID)
set @UserID=@TempID
if @TempID=@MemberID
begin
set @status= 1
break
end
end
end
return @status
end
/*
call a function***********
select dbo.IsSponsor(1,1)
print dbo.IsSponsor(1,21)
*/

Arraylist and GenericList

Arraylist
----------
using System.Collections;
ArrayList ContentList = new ArrayList();

Genericlist
---------------
using System.Collections.Generic;
List<string> ContentList = new List<string>();

//find the a item
ContentList[ContentList.IndexOf("Yellow")] = "Black";


Find Difference between Arraylist and Genericlist refer the link

Monday, August 10, 2009

Sql:User Defined functions link

Know about sql UserDefinedFunctions

Redirection page for error(In Web Config)

Error : 404 page not found
Response.StatusCode = (int)HttpStatusCode.NotFound;

Error : 301 -moved permanently
Response.StatusCode = (int)HttpStatusCode.MovedPermanently;

Response.Write("This page has moved.<br/><a href=" + ReURL + ">Click here</a> to proceed to the new page.");
Response.AddHeader("Location", ReURL);

Random selection of a row --NEWID() (ms sql)

//Querry for selecting a random field

SELECT top 1 * FROM dbtable where status=0 order by NEWID()

//Example :
SELECT username FROM login order by NEWID();

Try :
SELECT top 15 (ROW_NUMBER() over (order by userid)) as i,username FROM login order by NEWID();

Page Refreshing

Refresh after 15 secondes

string RefreahTime="15";
Response.AppendHeader("Refresh",RefreahTime); //using code

<meta http-equiv="refresh" content="15"> //using metatag

Include contents of an html page in an aspx page

If you are creating a new ASP.NET application, but have a huge collection of existing content in html files, one option is to move all the content into a database and generate pages dynamically. However, migration to a database can be a time-consuming task depending on the volume of content. So wouldn't it be easier to somehow import the relevant parts of the existing html pages into your aspx page?
The use of System.IO and regular expressions makes this a very easy task. Place a <asp:Literal> control (ID="htmlbody") on your page, and then use the following code to strip out everything up to and including the <body> tag (regardless of whether the tag contains additional attributes), and everything from the closing </body> tag onwards:

StreamReader sr;
string html;
sr = File.OpenText("<path_to_file.htm>");
html = sr.ReadToEnd();
sr.Close();

Regex start = new Regex(@"[\s\S]*<body[^<]*>", RegexOptions.IgnoreCase);
html = start.Replace(html,"");
Regex end = new Regex(@"</body[\s\S]*", RegexOptions.IgnoreCase);
html = end.Replace(html, "");
htmlbody.Text = html;

Getting HTML from another page(aspx page)

string html;
string newurl = "http://localhost:1997/testpage.aspx";

WebClient c = new WebClient();
Stream s = c.OpenRead(new Uri(newurl));
StreamReader reader = new StreamReader(s);
html = reader.ReadToEnd();
reader.Close();
divid.InnerHtml = html; //This is div id

Getting HTML from ascx in a class

//namespace
using System.Text;
using System.IO;

//public class ThisClass: System.Web.UI.Page//class name should inherit from ystem.Web.UI.Page

public string ReturnContent(string username)
{
Control c = Page.LoadControl("WebUserControl.ascxx");
((UserControlBaseMemberDesign)c).function(username)//function in webusercontrol.ascx for displaying in ascx page
HtmlForm form1 = new HtmlForm();
form1.Controls.Add(c); //a control as html for class

StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
string contents = null;
try
{
c.RenderControl(writer);
contents = sw.GetStringBuilder().ToString();
}
finally
{
sw.Close();
writer.Close();
}
return contents;
}

Getting HTML from ascx and place the html in another aspx page

//namespace
using System.Text;
using System.IO;

Control c = Page.LoadControl("WebUserControl.ascx");
((UserControlBaseSoloDesign)c).function(string username)//function in webusercontrol.ascx for displaying in ascx page
form1.Controls.Add(c); //form 1 is the control in the page
StringWriter sw = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(sw);
string contents = null;
try
{
c.RenderControl(writer);
contents = sw.GetStringBuilder().ToString();
}
finally
{
sw.Close();
writer.Close();
}
Response.Write(contents.ToString());

Wednesday, June 24, 2009

Searching a field in sql table

string username=""; //username string
string useremaipart=""; //email string

// for selecting username's
-->select username from table1 where username like'%" + username+ "%'

// for selecting emailid's
-->select username from table1 where SUBSTRING(email,1,CHARINDEX('@',email)-1) like'%" + useremaipart+ "%'

IT PAPERS CORNER

Click 1).Some Question papers related to IT

C Sharp CORNER

Click 1).Explaining about C#
Click 2).Explaining about C#

.NET CORNER

A simple guide for .Net

WebSite for STUDY(Referrence)

Click : 1).WebSite Study(SQL,HTML,PHP)(C#)
Click : 2).WebSite Study(w3 School)(C#)

Tuesday, June 23, 2009

String Manipulation(C#)

Click : String Manipulation(C#)

Convert C# to VB.Net

Click : Convert VB.NET to C# & C# to VB.NET

Special Charecters to HTML(links)

Click : first Usefull page

Click : second Usefull page

MetaTag in Asp.Net

Click here : Useful HTML Meta Tags

Click here : Meta Tag Using C#

New window settings using javascript

popupwindow option in asp.net(Code behind)
===================================

string URL ="asppage.aspx";

Response.Write("<script language=javascript>window.open('" + URL + "',null,'left=100, top=100,width=657,height=500,status=no, resizable= no, scrollbars= yes, toolbar= no,location= no, menubar= no,titlebar=0')</script>");

Close window option in asp.net(Code behind)
===================================

Response.Write("<script language='javascript'> { window.close();}</script>");

Thursday, June 4, 2009

Take a Value from webconfig

/* In webconfig file add the following code...

<appsettings>

 <add key="ChooseMode" value="LIVE"></add><!--
Set ChooseMode as TEST for test server.
Set ChooseMode as LIVE for live server.
-->
</appsettings>

/* We can take this value by using c#,asp.net 2.0 by giving the key "ChooseMode" is

using System.Configuration; //name space

string ChooseMode=System.Configuration.ConfigurationManager.AppSettings
.Get("ChooseMode");

Wednesday, June 3, 2009

SQL--Convert (binary) in to string using sql

/* datafield--->binary(imageformat) field in table (or blob field in mysql)*/
/* in ms sql give the following code...*/

Convert(char,Convert(binary,datafield)))

/* in my sql give the following code...*/

cast(datafield as char)

Allow numbers (0-9), and periods (.) for Registration form(Asp.net+C#)

string password=string.empty /* (Give ur password here) */

if (!Regex.IsMatch( password, "^[-0-9a-zA-Z_.]{3,25}$"))
{

Response.Write("Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed for
password.");

}

Mail sending from C#.Net (.NEt2.0,Godaddy hosting)

Namespace used :

using System.Net.Mail;
using System.Net;

Code in C#.Net :

public void sendMail()
{
MailMessage objMail = new MailMessage();
objMail.To.Add(new MailAddress("toaddress"));
objMail.From = new MailAddress("fromaddress", "dispalyname");
objMail.Subject = "mailSubject";
objMail.CC.Add("Ccmailaddress");
objMail.Bcc.Add("Bccmailaddress");
objMail.IsBodyHtml = true;
objMail.Priority=MailPriority.High;
objMail.Body = "mailContent";
SmtpClient objSmtp = new SmtpClient("relay-hosting.secureserver.net");
objSmtp.Credentials=CredentialCache.DefaultNetworkCredentials;
objSmtp.DeliveryMethod=SmtpDeliveryMethod.Network;
objSmtp.Send(objMail);
}

Equating text datatype with string in SQL

/* datafield-->field in tabl(text datatype)
variable-->string field */

convert(char,datafield)=convert(char, 'variable')

Set Paging in Datagrid

/*set Allow paging=true (in datagrid properties) and write the following code.. */

protected void DataGrid1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataGrid1.PageIndex = e.NewPageIndex;
LoadDataGrid1();

}

check

Date format MS SQL

To format date as yyyy-mm-dd in MS SQL :

select convert(char(10),getdate(),121);
Result format : 2009-06-03
select convert(char(19),getdate(),121);
Result format : 2009-06-03 15:55:00