24 May 2012
Set no cache in WCF service
protected static void SetNoCache()
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.Headers.Add("Cache-Control", "no-store");
response.Headers.Add("Pragma", "no-cache");
}
protected static void SetCache(TimeSpan span)
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.Headers.Add("Expires", DateTime.Now.Add(span).ToString());
}
protected static void SetCache(int expiration)
{
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.Headers.Add("Expires", DateTime.Now.AddMinutes(expiration).ToString());
}
Throwing custom exception message from wcf to json jquery error part
try
{
}
catch (Exception ex)
{
WebOperationContext.Current.OutgoingResponse.StatusDescription = "Error in retrieving information";
throw;
}
14 December 2011
Image from a sharepoint location
string url = "URL";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("test", "test", "test");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
BinaryReader br = new BinaryReader(stream);
byte[] content = br.ReadBytes(500000);
br.Close();
string[] imagetype = url.Split('.');
Response.ContentType = "image/" + imagetype[imagetype.Length-1];
//Response.ContentType = "image/jpeg";
Response.BinaryWrite(content);
response.Close();
//string file_name = Server.MapPath(".") + "\\logo.jpg";
//FileStream fs = new FileStream(file_name, FileMode.Create);
//BinaryWriter bw = new BinaryWriter(fs);
//try
//{
// bw.Write(content);
//}
//finally
//{
// fs.Close();
// bw.Close();
//}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential("test", "test", "test");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
BinaryReader br = new BinaryReader(stream);
byte[] content = br.ReadBytes(500000);
br.Close();
string[] imagetype = url.Split('.');
Response.ContentType = "image/" + imagetype[imagetype.Length-1];
//Response.ContentType = "image/jpeg";
Response.BinaryWrite(content);
response.Close();
//string file_name = Server.MapPath(".") + "\\logo.jpg";
//FileStream fs = new FileStream(file_name, FileMode.Create);
//BinaryWriter bw = new BinaryWriter(fs);
//try
//{
// bw.Write(content);
//}
//finally
//{
// fs.Close();
// bw.Close();
//}
01 March 2011
CTE
CTE (Common Table Expression):
WITH name (Alias name of the retrieve result set fields)
AS
(
//Write the sql query here
)
SELECT * FROM name
CTE 1: Simple CTE
WITH ProductCTE
AS
(
SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
FROM Products
)
SELECT * FROM ProductCTE
WITH name (Alias name of the retrieve result set fields)
AS
(
//Write the sql query here
)
SELECT * FROM name
CTE 1: Simple CTE
WITH ProductCTE
AS
(
SELECT ProductID AS [ID],ProductName AS [Name],CategoryID AS [CID],UnitPrice AS [Price]
FROM Products
)
SELECT * FROM ProductCTE
Update group of records
SqlDataAdapter daAuthors = new SqlDataAdapter("Select Id,Name From ttt", DA.Data.SqlConnectionString.Conn);
DataSet ds = new DataSet("Pubs");
daAuthors.Fill(ds, "ttt");
ds.Tables[0].TableName = "ttt";
DataRow dr=ds.Tables[0].NewRow();
dr["Name"]="Arun";
ds.Tables[0].Rows.Add(dr);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(daAuthors);
daAuthors.InsertCommand = cmdBuilder.GetInsertCommand(true);
daAuthors.UpdateCommand = cmdBuilder.GetUpdateCommand(true);
daAuthors.DeleteCommand = cmdBuilder.GetDeleteCommand(true);
daAuthors.Update(ds, "ttt");
DataSet ds = new DataSet("Pubs");
daAuthors.Fill(ds, "ttt");
ds.Tables[0].TableName = "ttt";
DataRow dr=ds.Tables[0].NewRow();
dr["Name"]="Arun";
ds.Tables[0].Rows.Add(dr);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(daAuthors);
daAuthors.InsertCommand = cmdBuilder.GetInsertCommand(true);
daAuthors.UpdateCommand = cmdBuilder.GetUpdateCommand(true);
daAuthors.DeleteCommand = cmdBuilder.GetDeleteCommand(true);
daAuthors.Update(ds, "ttt");
Mobile call when click a link
brokerPro.append(CreateBrokerElements('Email: ', '' + result.Items[i].Email + ''));
Pivot table eg: (SQL)
Create Table #TempResult(Sno int,AllocationMonthYear varchar(100),Efforts numeric(18,2),
Location varchar(100),Release nvarchar(100), Category nvarchar(100),
Name nvarchar(50),Mon Int, Ye int)
Insert Into #TempResult
SELECT
Sno
,cast(DateName(mm,DATEADD(mm,ActualAllocationInMonthsDtl.Month,-1)) as varchar) +' '+
cast(ActualAllocationInMonthsDtl.Year as varchar) AllocationMonthYear
,Sum(ActualAllocationInMonthsDtl.Efforts)Efforts
,ActualAllocationInMonthsDtl.Location
,PlannedAllocationHdr.Release
,PlannedAllocationHdr.Category
,Designation.Name AS Designation
,ActualAllocationInMonthsDtl.Month
,ActualAllocationInMonthsDtl.Year
FROM
ActualAllocationInMonthsDtl
INNER JOIN
ActualAllocationInMonthsHdr ON ActualAllocationInMonthsDtl.AllocationHdrUid = ActualAllocationInMonthsHdr.Uid
INNER JOIN
ActualVsPlanned ON ActualAllocationInMonthsHdr.Uid = ActualVsPlanned.ActualAllocationId
INNER JOIN
Designation ON ActualVsPlanned.DesignationUid = Designation.Uid
INNER JOIN
PlannedAllocationHdr ON ActualVsPlanned.PlannedAllocationId = PlannedAllocationHdr.Uid WHERE ActualAllocationInMonthsHdr.ProjectId=@projectUid
GROUP By
Sno,ActualAllocationInMonthsDtl.Month,
ActualAllocationInMonthsDtl.Year,
ActualAllocationInMonthsDtl.Location,
PlannedAllocationHdr.Release,
PlannedAllocationHdr.Category,
Designation.Name
Order By ActualAllocationInMonthsDtl.Year,ActualAllocationInMonthsDtl.Month
Declare @TblMonthYear Table(Mon int,Yea int)
Insert Into @TblMonthYear Select Distinct Mon,Ye From #TempResult Order By Ye,Mon
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(
@PivotColumnHeaders + ',[' + cast(DateName(mm,DATEADD(mm,Mon,-1)) as varchar) +' '+ cast(Yea as varchar) + ']',
'[' + cast(DateName(mm,DATEADD(mm,Mon,-1)) as varchar) +' '+ cast(Yea as varchar) + ']'
)
FROM (Select Mon,Yea From @TblMonthYear) as test
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
SELECT *
FROM
(SELECT Sno,AllocationMonthYear,Efforts,Release,Category,Location,Name AS Designation
FROM #TempResult) AS DataTable
PIVOT
(
Max(Efforts)
FOR AllocationMonthYear IN ('+ @PivotColumnHeaders +')
) AS PivotTable;
'
EXECUTE(@PivotTableSQL)
Location varchar(100),Release nvarchar(100), Category nvarchar(100),
Name nvarchar(50),Mon Int, Ye int)
Insert Into #TempResult
SELECT
Sno
,cast(DateName(mm,DATEADD(mm,ActualAllocationInMonthsDtl.Month,-1)) as varchar) +' '+
cast(ActualAllocationInMonthsDtl.Year as varchar) AllocationMonthYear
,Sum(ActualAllocationInMonthsDtl.Efforts)Efforts
,ActualAllocationInMonthsDtl.Location
,PlannedAllocationHdr.Release
,PlannedAllocationHdr.Category
,Designation.Name AS Designation
,ActualAllocationInMonthsDtl.Month
,ActualAllocationInMonthsDtl.Year
FROM
ActualAllocationInMonthsDtl
INNER JOIN
ActualAllocationInMonthsHdr ON ActualAllocationInMonthsDtl.AllocationHdrUid = ActualAllocationInMonthsHdr.Uid
INNER JOIN
ActualVsPlanned ON ActualAllocationInMonthsHdr.Uid = ActualVsPlanned.ActualAllocationId
INNER JOIN
Designation ON ActualVsPlanned.DesignationUid = Designation.Uid
INNER JOIN
PlannedAllocationHdr ON ActualVsPlanned.PlannedAllocationId = PlannedAllocationHdr.Uid WHERE ActualAllocationInMonthsHdr.ProjectId=@projectUid
GROUP By
Sno,ActualAllocationInMonthsDtl.Month,
ActualAllocationInMonthsDtl.Year,
ActualAllocationInMonthsDtl.Location,
PlannedAllocationHdr.Release,
PlannedAllocationHdr.Category,
Designation.Name
Order By ActualAllocationInMonthsDtl.Year,ActualAllocationInMonthsDtl.Month
Declare @TblMonthYear Table(Mon int,Yea int)
Insert Into @TblMonthYear Select Distinct Mon,Ye From #TempResult Order By Ye,Mon
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(
@PivotColumnHeaders + ',[' + cast(DateName(mm,DATEADD(mm,Mon,-1)) as varchar) +' '+ cast(Yea as varchar) + ']',
'[' + cast(DateName(mm,DATEADD(mm,Mon,-1)) as varchar) +' '+ cast(Yea as varchar) + ']'
)
FROM (Select Mon,Yea From @TblMonthYear) as test
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
SELECT *
FROM
(SELECT Sno,AllocationMonthYear,Efforts,Release,Category,Location,Name AS Designation
FROM #TempResult) AS DataTable
PIVOT
(
Max(Efforts)
FOR AllocationMonthYear IN ('+ @PivotColumnHeaders +')
) AS PivotTable;
'
EXECUTE(@PivotTableSQL)
16 November 2009
Enable disable validators
function EnableValidator()
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
function disableValidator()
{
var myval = document.getElememtById('validator.ClientId');
myval.style.cssText="";
myval.style.display='none';
myval.style.accelerator=true;
}
{
var myVal = document.getElementById('myValidatorClientID');
ValidatorEnable(myVal, false);
}
function disableValidator()
{
var myval = document.getElememtById('validator.ClientId');
myval.style.cssText="";
myval.style.display='none';
myval.style.accelerator=true;
}
Scrolbar transparent
background-color: #FFFFFF;
scrollbar-shadow-color: #FFFFFF;
scrollbar-highlight-color: #FFFFFF;
scrollbar-face-color: #FFFFFF;
scrollbar-3dlight-color: #FFFFFF;
scrollbar-darkshadow-color: #FFFFFF;
scrollbar-track-color: #FFFFFF;
scrollbar-arrow-color: #FFFFFF;
scrollbar-shadow-color: #FFFFFF;
scrollbar-highlight-color: #FFFFFF;
scrollbar-face-color: #FFFFFF;
scrollbar-3dlight-color: #FFFFFF;
scrollbar-darkshadow-color: #FFFFFF;
scrollbar-track-color: #FFFFFF;
scrollbar-arrow-color: #FFFFFF;
21 October 2009
Prevent Copy paste
You can prevent copy, paste and cut using this for controls like textbox
oncopy="return false" onpaste="return false" oncut="return false"
oncopy="return false" onpaste="return false" oncut="return false"
Prevent Copy paste
You can prevent copy, paste and cut using this for controls like textbox
oncopy="return false" onpaste="return false" oncut="return false"
oncopy="return false" onpaste="return false" oncut="return false"
13 August 2009
18 June 2009
02 April 2009
09 March 2009
25 February 2009
Preventing right click in websites
var message="Sorry, Right Click is disabled.";
function click(e)
{
if (document.all)
{
if (event.button == 2)
{
alert(message);
return false;
}
}
if (document.layers)
{
if (e.which == 3)
{
alert(message);
return false;
}
}
}
if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
function click(e)
{
if (document.all)
{
if (event.button == 2)
{
alert(message);
return false;
}
}
if (document.layers)
{
if (e.which == 3)
{
alert(message);
return false;
}
}
}
if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
12 February 2009
Filter dataset
Dataset.Tables[0].DefaultView.RowFilter = "Id not in(" + tmpItemIds + ") and Name like '%" + txtSearch.Text + "%'";
BusinessCommon.FillDataBoundControl(grvItem, Dataset.Tables[0].DefaultView);
BusinessCommon.FillDataBoundControl(grvItem, Dataset.Tables[0].DefaultView);
Set cursor position Last ( TextBox )
function setCursorPosition(elementRef, cursorPosition)
{
if ( typeof elementRef == 'string' )
elementRef = document.getElementById(elementRef);
if ( elementRef != null )
{
if ( elementRef.createTextRange )
{
var textRange = elementRef.createTextRange();
textRange.move('character', cursorPosition);
textRange.select();
}
else
{
if ( elementRef.selectionStart )
{
elementRef.focus();
elementRef.setSelectionRange(cursorPosition, cursorPosition);
}
else
{
elementRef.focus();
}
}
}
}
--------------------
ScriptManager.RegisterStartupScript(this, this.GetType(), "k", "setCursorPosition('" + TextBox2.ClientID + "'," + TextBox2.Text.Length + ");", true);
{
if ( typeof elementRef == 'string' )
elementRef = document.getElementById(elementRef);
if ( elementRef != null )
{
if ( elementRef.createTextRange )
{
var textRange = elementRef.createTextRange();
textRange.move('character', cursorPosition);
textRange.select();
}
else
{
if ( elementRef.selectionStart )
{
elementRef.focus();
elementRef.setSelectionRange(cursorPosition, cursorPosition);
}
else
{
elementRef.focus();
}
}
}
}
--------------------
ScriptManager.RegisterStartupScript(this, this.GetType(), "k", "setCursorPosition('" + TextBox2.ClientID + "'," + TextBox2.Text.Length + ");", true);
27 January 2009
Creating a dataset structure manually
protected DataSet CreatePurchaseRequestStructure()
{
DataSet dsPurchaseRequestItem = new DataSet();
DataTable dt = new DataTable();
dsPurchaseRequestItem.Tables.Add(dt);
DataColumn dcItemId = new DataColumn("ItemId");
DataColumn dcItem = new DataColumn("Item");
DataColumn dcSupplierId = new DataColumn("SupplierId");
DataColumn dcSupplier = new DataColumn("Supplier");
DataColumn dcUnitId = new DataColumn("UnitId");
DataColumn dcUnit = new DataColumn("Unit");
DataColumn dcRequestedQuantity = new DataColumn("RequestedQuantity");
DataColumn dcCurrentStock = new DataColumn("CurrentStock");
DataColumn dcMinimumReorderQuantity = new DataColumn("MinimumReorderQuantity");
DataColumn dcPendingQuantity = new DataColumn("PendingQuantity");
dsPurchaseRequestItem.Tables[0].Columns.Add(dcItemId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcItem);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcSupplierId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcSupplier);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcUnitId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcUnit);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcRequestedQuantity);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcCurrentStock);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcMinimumReorderQuantity);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcPendingQuantity);
return dsPurchaseRequestItem;
}
{
DataSet dsPurchaseRequestItem = new DataSet();
DataTable dt = new DataTable();
dsPurchaseRequestItem.Tables.Add(dt);
DataColumn dcItemId = new DataColumn("ItemId");
DataColumn dcItem = new DataColumn("Item");
DataColumn dcSupplierId = new DataColumn("SupplierId");
DataColumn dcSupplier = new DataColumn("Supplier");
DataColumn dcUnitId = new DataColumn("UnitId");
DataColumn dcUnit = new DataColumn("Unit");
DataColumn dcRequestedQuantity = new DataColumn("RequestedQuantity");
DataColumn dcCurrentStock = new DataColumn("CurrentStock");
DataColumn dcMinimumReorderQuantity = new DataColumn("MinimumReorderQuantity");
DataColumn dcPendingQuantity = new DataColumn("PendingQuantity");
dsPurchaseRequestItem.Tables[0].Columns.Add(dcItemId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcItem);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcSupplierId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcSupplier);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcUnitId);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcUnit);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcRequestedQuantity);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcCurrentStock);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcMinimumReorderQuantity);
dsPurchaseRequestItem.Tables[0].Columns.Add(dcPendingQuantity);
return dsPurchaseRequestItem;
}
Filtering from dataset
public void LoadItems()
{
dsItems = InventoryManager.ListItems();
if (dsItems.Tables[0].Rows.Count.Equals(0))
{
DataRow drNew = dsItems.Tables[0].NewRow();
dsItems.Tables[0].Rows.Add(drNew);
GridView1.DataSource=dsItems;
GridView1.DataBind();
grvItem.Rows[0].Visible = false;
}
else
{
DataView dv;
if (ViewState["sortExpr"] != null)
{
dv = new DataView(dsItems.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
{
dv = new DataView(dsItems.Tables[0]);
}
dv.RowFilter = "Name like '%" + txtSearch.Text + "%'";
GridView1.DataSource=dv;
GridView1.DataBind();
}
}
{
dsItems = InventoryManager.ListItems();
if (dsItems.Tables[0].Rows.Count.Equals(0))
{
DataRow drNew = dsItems.Tables[0].NewRow();
dsItems.Tables[0].Rows.Add(drNew);
GridView1.DataSource=dsItems;
GridView1.DataBind();
grvItem.Rows[0].Visible = false;
}
else
{
DataView dv;
if (ViewState["sortExpr"] != null)
{
dv = new DataView(dsItems.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
{
dv = new DataView(dsItems.Tables[0]);
}
dv.RowFilter = "Name like '%" + txtSearch.Text + "%'";
GridView1.DataSource=dv;
GridView1.DataBind();
}
}
30 December 2008
Time automatically in a web page using javascript
DisplayDate();
setInterval("DisplayDate()",1000);
function DisplayDate()
{
var dt = new Date();
document.getElementById("tdDate").innerHTML=dt.toLocaleString();
}
setInterval("DisplayDate()",1000);
function DisplayDate()
{
var dt = new Date();
document.getElementById("tdDate").innerHTML=dt.toLocaleString();
}
04 December 2008
Export GridView Data To Excel
private void ExportDynamicReportToExcel()
{
string attachment = "attachment; filename=File.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
{
string attachment = "attachment; filename=File.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GridView1.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GridView1);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
DateTime.ToString() Patterns
MM/dd/yyyy 08/22/2006
dddd, dd MMMM yyyy Tuesday, 22 August 2006
dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
MM/dd/yyyy HH:mm 08/22/2006 06:30
MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
MM/dd/yyyy H:mm 08/22/2006 6:30
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
MMMM dd August 22
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
HH:mm 06:30
hh:mm tt 06:30 AM
H:mm 6:30
h:mm tt 6:30 AM
HH:mm:ss 06:30:07
yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
yyyy MMMM 2006 August
MM/dd/yyyy 08/22/2006
dddd, dd MMMM yyyy Tuesday, 22 August 2006
dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
MM/dd/yyyy HH:mm 08/22/2006 06:30
MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
MM/dd/yyyy H:mm 08/22/2006 6:30
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
Eg:
DateTime dt = DateTime.Now;
lblAppDate.Text = dt.ToString("dd MMM yyyy hh:mm:s tt");
dddd, dd MMMM yyyy Tuesday, 22 August 2006
dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
MM/dd/yyyy HH:mm 08/22/2006 06:30
MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
MM/dd/yyyy H:mm 08/22/2006 6:30
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
MMMM dd August 22
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
HH:mm 06:30
hh:mm tt 06:30 AM
H:mm 6:30
h:mm tt 6:30 AM
HH:mm:ss 06:30:07
yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
yyyy MMMM 2006 August
MM/dd/yyyy 08/22/2006
dddd, dd MMMM yyyy Tuesday, 22 August 2006
dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
MM/dd/yyyy HH:mm 08/22/2006 06:30
MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
MM/dd/yyyy H:mm 08/22/2006 6:30
MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
Eg:
DateTime dt = DateTime.Now;
lblAppDate.Text = dt.ToString("dd MMM yyyy hh:mm:s tt");
27 November 2008
How to open a pdf Or image file in a new browser window
In the Default.aspx page, in a button click or any other events
----------------------------------------------------------------
ScriptManager.RegisterStartupScript(this, this.GetType(), "s", "window.open('Default2.aspx?FileName=PO0005_R.pdf',null,'height=500, width=500,status= no,resizable= no, scrollbars=no,toolbar=no,menubar=no');", true);
In the Defult2.aspx page
-------------------------
using System.Net;
protected void Page_Load(object sender, EventArgs e)
{
ReadPdfFile(Request.QueryString["FileName"].ToString());
}
private void ReadPdfFile(string FileName)
{
string path = Server.MapPath("PO0005_R.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
----------------------------------------------------------------
ScriptManager.RegisterStartupScript(this, this.GetType(), "s", "window.open('Default2.aspx?FileName=PO0005_R.pdf',null,'height=500, width=500,status= no,resizable= no, scrollbars=no,toolbar=no,menubar=no');", true);
In the Defult2.aspx page
-------------------------
using System.Net;
protected void Page_Load(object sender, EventArgs e)
{
ReadPdfFile(Request.QueryString["FileName"].ToString());
}
private void ReadPdfFile(string FileName)
{
string path = Server.MapPath("PO0005_R.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}
18 November 2008
How to get datakeyNames ( Gridview )
GridViewRow row = ((GridViewRow)((Control)e.CommandSource).Parent.Parent);
lblPopGRNNo.Text = grvGRNList.DataKeys[row.RowIndex]["GrnNumber"].ToString();
lblGRNDate.Text = (Convert.ToDateTime(grvGRNList.DataKeys[row.RowIndex]["GrnDate"])).ToString("dd MMM yyyy");
lblSupplierName.Text = grvGRNList.DataKeys[row.RowIndex]["SupplierName"].ToString();
lblSuratJalanNumber.Text = grvGRNList.DataKeys[row.RowIndex]["SuratJalanNumber"].ToString();
lblPopGRNNo.Text = grvGRNList.DataKeys[row.RowIndex]["GrnNumber"].ToString();
lblGRNDate.Text = (Convert.ToDateTime(grvGRNList.DataKeys[row.RowIndex]["GrnDate"])).ToString("dd MMM yyyy");
lblSupplierName.Text = grvGRNList.DataKeys[row.RowIndex]["SupplierName"].ToString();
lblSuratJalanNumber.Text = grvGRNList.DataKeys[row.RowIndex]["SuratJalanNumber"].ToString();
06 November 2008
System colors to dropdownlist
using System.Drawing;
string[] names = System.Enum.GetNames(typeof(System.Drawing.KnownColor));
Array values = System.Enum.GetValues(typeof(System.Drawing.KnownColor));
for (int i = 27; i <= names.Length - 8; i++)
{
ListItem item = new ListItem(names[i], values.GetValue(i).ToString());
ddlColorPicker.Items.Add(item);
ddlColorPicker.Items[i - 26].Attributes.Add("style", "background-color :" + values.GetValue(i).ToString() + "");
}
string[] names = System.Enum.GetNames(typeof(System.Drawing.KnownColor));
Array values = System.Enum.GetValues(typeof(System.Drawing.KnownColor));
for (int i = 27; i <= names.Length - 8; i++)
{
ListItem item = new ListItem(names[i], values.GetValue(i).ToString());
ddlColorPicker.Items.Add(item);
ddlColorPicker.Items[i - 26].Attributes.Add("style", "background-color :" + values.GetValue(i).ToString() + "");
}
04 November 2008
Filtering dataset
grvItem.DataSource = dataset1.Tables[0].DefaultView;
DataView myView = dataset1.Tables[0].DefaultView;
myView.RowFilter = "Name like '" + txtSearch.Text + "%'";
grvItem.DataSource = myView;
grvItem.DataBind();
DataView myView = dataset1.Tables[0].DefaultView;
myView.RowFilter = "Name like '" + txtSearch.Text + "%'";
grvItem.DataSource = myView;
grvItem.DataBind();
30 October 2008
Change style of file upload button
<
asp:FileUpload id="File1"
runat="server"
style ="position: relative;text-align: right;-moz-opacity:0 ;
filter:alpha(opacity: 0);opacity: 0;z-index: 2;" />
<
asp:LinkButton ID="ImageButton1"
runat="server"
Text="Attach more"
style ="position: absolute;left: 166px; z-index: 1; " />
asp:FileUpload id="File1"
runat="server"
style ="position: relative;text-align: right;-moz-opacity:0 ;
filter:alpha(opacity: 0);opacity: 0;z-index: 2;" />
<
asp:LinkButton ID="ImageButton1"
runat="server"
Text="Attach more"
style ="position: absolute;left: 166px; z-index: 1; " />
21 October 2008
Convert to byte
System.IO.Stream inputStream = FileUpload1.PostedFile.InputStream;
byte[] buffer = new byte[FileUpload1.PostedFile.ContentLength];
inputStream.Read(buffer, 0, FileUpload1.PostedFile.ContentLength);
byte[] buffer = new byte[FileUpload1.PostedFile.ContentLength];
inputStream.Read(buffer, 0, FileUpload1.PostedFile.ContentLength);
16 October 2008
Select values from dataset
1 . Using Like
---------
foreach (DataRow dr in dsItem.Tables[0].Select("Name like '" + prefixText + "%'"))
{
items.Add(dr["Name"].ToString());
}
2. Using =
-----------
DataRow[] dRow = dsPurchaseRequestItems.Tables[0].Select("ItemId='" + hfItemId.Value + "'");
if (dRow.Length > 0)
{
dRow[0].Delete();
}
dsPurchaseRequestItems.AcceptChanges();
---------
foreach (DataRow dr in dsItem.Tables[0].Select("Name like '" + prefixText + "%'"))
{
items.Add(dr["Name"].ToString());
}
2. Using =
-----------
DataRow[] dRow = dsPurchaseRequestItems.Tables[0].Select("ItemId='" + hfItemId.Value + "'");
if (dRow.Length > 0)
{
dRow[0].Delete();
}
dsPurchaseRequestItems.AcceptChanges();
14 October 2008
Photo Upload
// This code used in Target form
StreamReader strReader = new StreamReader(upPhoto.PostedFile.InputStream);
Stream str = strReader.BaseStream;
BinaryReader brRead = new BinaryReader(str);
byte[] sImage = brRead.ReadBytes(Convert.ToInt32(str.Length));
//Save Function
int photoId = CommonData.SavePhoto(0, upPhoto.PostedFile.ContentType, sImage, "Item");
Image1.ImageUrl = "~/ShowImage.aspx?PhotoId=" + photoId;
//Write byte stream to another Form (ShowImage.aspx)
public int PhotoId;
protected void Page_Load(object sender, EventArgs e)
{
PhotoId = Convert.ToInt32(Request.QueryString["PhotoId"]);
// Used for retrive image from database
Photo objPhoto = CommonManager.GetPhoto(PhotoId);
Response.ContentType = objPhoto.ImageType;
Response.BinaryWrite(objPhoto.Image);
//byte[] Photo1 = (byte[])Session["Photo"];
//Response.ContentType = "image/jpeg";
//Response.BinaryWrite(Photo1);
}
StreamReader strReader = new StreamReader(upPhoto.PostedFile.InputStream);
Stream str = strReader.BaseStream;
BinaryReader brRead = new BinaryReader(str);
byte[] sImage = brRead.ReadBytes(Convert.ToInt32(str.Length));
//Save Function
int photoId = CommonData.SavePhoto(0, upPhoto.PostedFile.ContentType, sImage, "Item");
Image1.ImageUrl = "~/ShowImage.aspx?PhotoId=" + photoId;
//Write byte stream to another Form (ShowImage.aspx)
public int PhotoId;
protected void Page_Load(object sender, EventArgs e)
{
PhotoId = Convert.ToInt32(Request.QueryString["PhotoId"]);
// Used for retrive image from database
Photo objPhoto = CommonManager.GetPhoto(PhotoId);
Response.ContentType = objPhoto.ImageType;
Response.BinaryWrite(objPhoto.Image);
//byte[] Photo1 = (byte[])Session["Photo"];
//Response.ContentType = "image/jpeg";
//Response.BinaryWrite(Photo1);
}
06 October 2008
Split a text using javascript
function splitText()
{
var temp=document.getElementById('TextBox1').value.split(' ',3);
document.getElementById('TextBox1').value=temp[0];
document.getElementById('TextBox2').value=temp[1];
document.getElementById('TextBox3').value=temp[2];
document.getElementById('DropDownList1').value=temp[0];
document.getElementById('DropDownList2').value=temp[1];
document.getElementById('DropDownList3').value=temp[2];
}
{
var temp=document.getElementById('TextBox1').value.split(' ',3);
document.getElementById('TextBox1').value=temp[0];
document.getElementById('TextBox2').value=temp[1];
document.getElementById('TextBox3').value=temp[2];
document.getElementById('DropDownList1').value=temp[0];
document.getElementById('DropDownList2').value=temp[1];
document.getElementById('DropDownList3').value=temp[2];
}
05 October 2008
Change values in gridView Dynamically
protected void grvStore_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text == "True")
{
e.Row.Cells[8].Text = "Active";
}
else
{
e.Row.Cells[8].Text = "Inactive";
}
}
}
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text == "True")
{
e.Row.Cells[8].Text = "Active";
}
else
{
e.Row.Cells[8].Text = "Inactive";
}
}
}
29 September 2008
Update UpdatePanel Using Javascript
var prm=Sys.WebForms.PageRequestManager.getInstance();
prm._doPostBack('ButtonName','');
or
prm._doPostBack('UpdatePanelName','');
prm._doPostBack('ButtonName','');
or
prm._doPostBack('UpdatePanelName','');
Focus Back to that control -C#
ScriptManager sm = ScriptManager.GetCurrent(this);
sm.SetFocus(TextBox2);
sm.SetFocus(TextBox2);
Allow only numeric values in textbox-Javascript
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 &&
(charCode < 48
Or
charCode > 57) )
return false;
return true;
}
----------------------------------------------
onkeypress="return isNumberKey(event);"
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 &&
(charCode < 48
Or
charCode > 57) )
return false;
return true;
}
----------------------------------------------
onkeypress="return isNumberKey(event);"
To Find No Of Days in a month -SQL
DECLARE @date datetime
set @date='1/1/2008'
DECLARE @dayCount int
--To Find No Of Days in a month
SET @dayCount=Day(DateAdd(Month, 1, @date) - Day(DateAdd(Month, 1, @date)))
print @daycount
set @date='1/1/2008'
DECLARE @dayCount int
--To Find No Of Days in a month
SET @dayCount=Day(DateAdd(Month, 1, @date) - Day(DateAdd(Month, 1, @date)))
print @daycount
Date Conversion
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-GB");
String requestTempDate = (Convert.ToDateTime(txtRequestDate.Text, culture)).ToShortDateString();
DateTime requestDate = Convert.ToDateTime(DateTime.Now, culture);
---------------------------------------------------------------
txtRequestDate.Text = DateTime.Now.ToString("dd MMM yyyy");
DateTime Date = Convert.ToDateTime(DateTime.Now.ToShortDateString());
String requestTempDate = (Convert.ToDateTime(txtRequestDate.Text, culture)).ToShortDateString();
DateTime requestDate = Convert.ToDateTime(DateTime.Now, culture);
---------------------------------------------------------------
txtRequestDate.Text = DateTime.Now.ToString("dd MMM yyyy");
DateTime Date = Convert.ToDateTime(DateTime.Now.ToShortDateString());
GridView-Row Identification In TemplateField ( TextBox )
//Getting gridview row in textchange of template field
protected void txtGrnQuantity_TextChanged(object sender, EventArgs e)
{
TextBox txtGrnQuantity = (TextBox)grvGRN.Rows[((GridViewRow)((TextBox)sender).Parent.Parent).RowIndex].FindControl("txtGrnQuantity");
TextBox txtRejectedQuantity = (TextBox)grvGRN.Rows[((GridViewRow)((TextBox)sender).Parent.Parent).RowIndex].FindControl("txtRejectedQuantity");
}
protected void txtGrnQuantity_TextChanged(object sender, EventArgs e)
{
TextBox txtGrnQuantity = (TextBox)grvGRN.Rows[((GridViewRow)((TextBox)sender).Parent.Parent).RowIndex].FindControl("txtGrnQuantity");
TextBox txtRejectedQuantity = (TextBox)grvGRN.Rows[((GridViewRow)((TextBox)sender).Parent.Parent).RowIndex].FindControl("txtRejectedQuantity");
}
21 August 2008
Disable the back functionality of the browser
//disable the back functionality of the browser
window.history.forward(1);
window.history.forward(1);
04 August 2008
How to change a value in GridView
protected void grvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text == "True")
{
e.Row.Cells[8].Text = "Active";
}
else
{
e.Row.Cells[8].Text = "Inactive";
}
}
}
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[8].Text == "True")
{
e.Row.Cells[8].Text = "Active";
}
else
{
e.Row.Cells[8].Text = "Inactive";
}
}
}
Allow only floating point values in textbox
function isNumberPointKey(evt)
{
//alert(event.keyCode);
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48
or
charCode > 57) && charCode!=46 )
return false;
return true;
}
onkeypress="return isNumberPointKey(event
{
//alert(event.keyCode);
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48
or
charCode > 57) && charCode!=46 )
return false;
return true;
}
onkeypress="return isNumberPointKey(event
Assigning a value to textbox when TextMode is Password
TextBox1.Text = "test";
TextBox1.Attributes.Add("value", "test");
TextBox1.Attributes.Add("value", "test");
29 July 2008
Identify GridView RowIndex
//When we Click a grdView Row, then row index stored in a hidden Field
function GetGrvPersonalRowIndex(GRVRowIndex)
{
document.getElementById('ctl00_ContentPlaceHolder1_tbcDailyReporting_TabPanel1_HFGridviewRowIndex').value=GRVRowIndex;
}
-------In server side of asp page----------
protected void grvPersonal_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript:GetGrvPersonalRowIndex(" + e.Row.RowIndex + ")");
}
}
function GetGrvPersonalRowIndex(GRVRowIndex)
{
document.getElementById('ctl00_ContentPlaceHolder1_tbcDailyReporting_TabPanel1_HFGridviewRowIndex').value=GRVRowIndex;
}
-------In server side of asp page----------
protected void grvPersonal_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "javascript:GetGrvPersonalRowIndex(" + e.Row.RowIndex + ")");
}
}
Allow two decimal palace in textBox
function AllowOnlyTwoDecimalPlace(txtBox)
{
var num = parseFloat(txtBox.value);
txtBox.value = num.toFixed(2);
if (txtBox.value == 'NaN'){
txtBox.value = '';}
}
{
var num = parseFloat(txtBox.value);
txtBox.value = num.toFixed(2);
if (txtBox.value == 'NaN'){
txtBox.value = '';}
}
To Identify Gridview Row Index in Row command
GridViewRow row = ((GridViewRow)((Control)e.CommandSource).Parent.Parent);
DropDownList ddlTest= (DropDownList)row.Cells[2].FindControl("ddlTest");
DropDownList ddlTest= (DropDownList)row.Cells[2].FindControl("ddlTest");
Subscribe to:
Comments (Atom)



