|
protected void btnUpload_Click(object sender, EventArgs e)
{
if (IsValidFile())
{
DataSet dsAlumniList = null;
string strFileName = DateTime.Now.Ticks.ToString() + "_" + fuList.FileName;
if (System.IO.Path.GetExtension(fuList.FileName) == ".xls" || System.IO.Path.GetExtension(fuList.FileName) == ".xlsx")
fuList.SaveAs(Server.MapPath("~/UploadedFiles/") + (strFileName));
string strNewFilePath = Server.MapPath("~/UploadedFiles/") + (strFileName);
IExcelDataReader excelReader = null;
FileStream stream = null;
stream = File.Open(strNewFilePath, FileMode.Open, FileAccess.Read);
if (System.IO.Path.GetExtension(fuList.FileName) == ".xls")
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
else if (System.IO.Path.GetExtension(fuList.FileName) == ".xlsx")
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
dsAlumniList = excelReader.AsDataSet();
string strXmlData = dsAlumniList.GetXml();
string strSheetName = dsAlumniList.Tables[0].TableName;
using (SqlConnection sqlConn = new SqlConnection(sqlConString))
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand("InsertDetailsInExcel", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add(new SqlParameter("@SheetName", strSheetName));
sqlCmd.Parameters.Add(new SqlParameter("@XmlList", strXmlData));
sqlCmd.ExecuteScalar();
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Files uploaded successfully.');", true);
}
else
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Invalid file.');", true);
}
--------------------------------------------------------------------------------------
ALTER PROCEDURE [dbo].[InsertDetailsInExcel]
@XmlList VARCHAR(MAX)=null,
@SheetName VARCHAR(100)=null,
@idoc INT=null
AS
BEGIN
EXEC sp_xml_preparedocument @idoc OUTPUT, @XMLList
DECLARE @ParentNodes VARCHAR(100)
SET @ParentNodes= '/NewDataSet/'+@SheetName
IF(@XMLList IS NOT NULL)
BEGIN
INSERT INTO ExcelDetails (EmpID,EmpName,EmailID)
--SELECT * FROM OPENXML (@idoc, '/NewDataSet/Sheet1',2)
SELECT * FROM OPENXML (@idoc, @ParentNodes,2)
WITH (ID INT,[Employee Name] VARCHAR(200),[Email ID] VARCHAR(200))
END
END
|
|
|
|
|
1) ControlChars class
2)Passing gridview integer column value and a string as parameters of a javascript function
3)Passing gridview 2 string column values as parameters of a javascript function
4)Include linkbutton and label in same column of a gridview
5) To hide imagebutton if comment text is not present
-------------------------------------------------------------------------------------------------
1) ControlChars class
Add below class,
using System;
namespace Proj.Utils
{
public sealed class ControlChars
{
public ControlChars()
{
}
public const char Back = '\u0008';
public const char Cr = '\r';
public const String CrLf = "\r\n";
public const char FormFeed = '\u000C';
public const char Lf = '\n';
public const String NewLine = "\r\n";
public const char NullChar = '\0';
public const char Quote = '"';
public const char Tab = '\t';
public const char VerticalTab = '\u000B';
}
}
------------------------------------------------------------------------------------------------
2)Passing gridview integer column value and a string as parameters of a javascript function
onClientClick='<%# " return submitfrm("+ (DataBinder.Eval(Container.DataItem,"PK_SolutionID")) + "," + Proj.Utils.ControlChars.Quote + "ViewSolution.aspx" + Proj.Utils.ControlChars.Quote + "," + Proj.Utils.ControlChars.Quote + "POST" + Proj.Utils.ControlChars.Quote + ");" %>'
------------------------------------------------------------------------------------------------
3)Passing gridview 2 string column values as parameters of a javascript function
<asp:ImageButton ID="imgSelect" runat="server" OnClientClick='<%#"return handleActionPopUp(" + Proj.Utils.ControlChars.Quote + System.Web.HttpUtility.HtmlDecode(DataBinder.Eval(Container.DataItem,"PersonID").ToString()) + Proj.Utils.ControlChars.Quote + "," + Proj.Utils.ControlChars.Quote + System.Web.HttpUtility.HtmlDecode(DataBinder.Eval(Container.DataItem,"EmpName").ToString()) + Proj.Utils.ControlChars.Quote + ");" %>' />
-----------------------------------------------------------------------------------------------
4)Include linkbutton and label in same column of a gridview
<asp:TemplateField ItemStyle- HeaderText="Example">
<ItemTemplate>
<a href="#" onclick='<%# " return submitfrm("+ (DataBinder.Eval(Container.DataItem,"PK_SolutionID")) + "," + CHD.Utils.ControlChars.Quote + "ViewSolution.aspx" + CHD.Utils.ControlChars.Quote + "," + CHD.Utils.ControlChars.Quote + "POST" + CHD.Utils.ControlChars.Quote + ");" %>'>
<%# System.Web.HttpUtility.HtmlEncode((string)Eval("ProblemDesc"))%></a>
<br />
<asp:Label ID="lblSolution" runat="server" Text='<%# System.Web.HttpUtility.HtmlEncode((string)Eval("Solution"))%>' ></asp:Label>
<br />
</ItemTemplate>
</asp:TemplateField>
------------------------------------------------------------------------------------------------
5) To hide imagebutton if comment text is not present
<igtbl:TemplatedColumn Width="30%" Key="comments">
<Header Caption="Comments">
</Header>
<CellTemplate>
<asp:label id="lblName" class="normalTextBold" runat="server" style="text-align: left"
="" text="<%# Server.HtmlEncode(Convert.ToString(DataBinder.Eval(Container.DataItem, "Comments"))) %>">
<asp:imagebutton id="ibtnComment" runat="server" imageurl="~/_includes/_img/info.gif"
="" style="cursor: hand;" causesvalidation="False" tooltip="Click here to view comment" visible="<%# Convert.ToString(DataBinder.Eval(Container.DataItem, "Comments")) == string.Empty ? false:true %>" onclientclick="<%#"return ViewComment("+DataBinder.Eval(Container.DataItem,"id")+");"%>">
</CellTemplate>
</igtbl:TemplatedColumn>
-------------------------------------------------------------------------------------------------
modified 12-Apr-12 10:36am.
|
|
|
|
|
1)To close browser window without confirmation
2)Clear page cache
3)To set values in textbox txtPassword after a postback, include below code in page load
4)To include SessionState
5)To disable 'Enter' press in a web page (except multiline textboxes)
6)Javascript to find out which control has the focus
7)To maximise the window size
8)Using Submit().
9)Delay using javascript
10)Disable right click and ctrl+A
11)Replace \ with \\
12)To get folder names in a folder
--------------------------------------------------------------------------------------------------
1)To close browser window without confirmation
In .aspx.cs page,
MessageBox.Show("Already expired");
Page.ClientScript.RegisterStartupScript(this.GetType(), "closePage", "javascript: funClose();", true);
In .aspx page,
function funClose()
{
window.opener = 'Self';
window.open('','_parent','');
window.close();
}
OR
In .aspx.cs page,
string script = "window.opener = 'Self';window.open('','_parent',''); window.close();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Close Window", script, true);
--------------------------------------------------------------------------------------------------
2)Clear page cache
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
//will not save the file to temp internet files
Response.Cache.SetNoStore();
//will not save the request or the response to and from the server anywhere
Response.Cache.SetNoServerCaching();
--------------------------------------------------------------------------------------------------
3)To set values in textbox txtPassword after a postback, include below code in page load
txtPassword.Attributes.Add("Value", txtPassword.Text.Trim());
--------------------------------------------------------------------------------------------------
4) To include SessionState
<system.web>
<sessionState mode="InProc" timeout="20"/>
</system.web>
--------------------------------------------------------------------------------------------------
5)To disable 'Enter' press in a web page (except multiline textboxes)
function BlockEnterPress(e)
{
var id=window.status=event.srcElement.id;
if(id=="txtCurrentAddress" || id=="txtPermanentAddress") //multiline textboxes
return true;
else
{
var key;
if(window.event)
key=window.event.keyCode;
else
key=e.which;
return (key!=13);
}
}
<body onkeydown="return BlockEnterPress(event)">
--------------------------------------------------------------------------------------------------
6)Javascript to find out which control has the focus
var id=window.status=event.srcElement.id;
--------------------------------------------------------------------------------------------------
7)To maximise the window size
window.moveTo(0,0);
window.resizeTo(screen.availWidth, screen.availHeight);
--------------------------------------------------------------------------------------------------
8)Using Submit()
Step 1:
Code in .aspx page (let function is called from a gridview column),
<asp:TemplateField ItemStyle- HeaderText="Example">
<ItemTemplate>
<a href="#" onclick='<%# " return submitfrm("+ (DataBinder.Eval(Container.DataItem,"SolutionID")) + "," + Proj.Utils.ControlChars.Quote + "ViewSolution.aspx" + Proj.Utils.ControlChars.Quote + "," + Proj.Utils.ControlChars.Quote + "POST" + Proj.Utils.ControlChars.Quote + ");" %>'>
<%#Eval("Problem") %></a>
</ItemTemplate>
</asp:TemplateField>
Step 2:
Include submitfrm() and a form in master page,
function submitfrm(itemId, UrlPath, actionMode)
{
document.forms[1].hfItemId.value = itemId;
document.forms[1].action = UrlPath;
document.forms[1].method = actionMode;
document.forms[1].submit();
}
<form name="frm2" id="frm2" method="post">
<input type="hidden" name="hfItemId" id="hfItemId" value="" />
<input type="hidden" name="hidMode" id="hidMode" value="" />
</form>
Step 3:
Include below code in .aspx.cs page in which query string is to be used
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["ID"] = Convert.ToString(Request.Form["hfItemId"]);
}
}
-------------------------------------------------------------------------------------------------
9)Delay using javascript
function Func1Delay()
{
// alert('Will wait for one second');
wait(3000);
alert('Finished waiting');
}
function wait(msecs)
{
var start = new Date().getTime();
var cur = start
while(cur - start < msecs)
{
cur = new Date().getTime();
}
}
-----------------------------------------------------------------------------------
10)Disable right click and ctrl+A
<script language="JavaScript" type="text/javascript">
function disableselect(e) {
return false
}
function reEnable() {
return true
}
document.onselectstart = new Function("return false")
document.oncontextmenu = new Function("return false")
if (window.sidebar) {
document.onmousedown = disableselect
document.onclick = reEnable
}
</script>
------------------------------------------------------------------------------------
11)Replace \ with \\
string new = old.Replace(@"\", @"\\");
------------------------------------------------------------------------------------
12)To get folder names in a folder
string[] strFoldersWithPath;
string[] strFolderDetails;
strFoldersWithPath = Directory.GetDirectories(Server.MapPath("~\\images\\"));
string[] strFolderName = new string[strFoldersWithPath.Count()];
for (int i = 0; i < strFoldersWithPath.Count(); i++)
{
strFolderDetails = strFoldersWithPath[i].Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
strFolderName[i] = strFolderDetails[strFolderDetails.Length - 1];
}
--------------------------------------------------------------------------------------
modified on Monday, September 19, 2011 8:36 AM
modified 13-Oct-12 15:08pm.
|
|
|
|
|
1) Upload File
2) To restrict usage of backbutton
3) To pass xml data as a parameter of an SP
4) To change actual URL
5) Dropdown list selected index changed event not fired after page validation failure
6)Return multiple values from a popup
7)Javascript to enable a disabled checkbox
8)CommandName, CommandArgument and Text properties of a linkbutton (in gridview)
9)To delete a row in a datatable
10)To find and change properties of a control in master page
11)Hide an image in a gridview column based on another column text
12)Set super admin in web.config
------------------------------------------------------------------------------------------
1)Upload File
a) Add below code in web.config to avoid problems related to uploading files greater than 4MB,
<system.web>
<httpRuntime maxRequestLength="2097151" requestLengthDiskThreshold="2097151"/>
</system.web>
b)Validate file to upload
i)Method 1:
public Boolean ValidateFile()
{
if (fupload.FileName = = string.Empty)
{
lblErrorMessage.Text = "Please select a file to upload";
return false;
}
else if (Convert.ToInt64(fupload.PostedFile.ContentLength) > 5242880)
{
lblErrorMessage.Text = "File size should be less than 5 MB";
return false;
}
else
{
string strExtension = Path.GetExtension(fupload.PostedFile.FileName).ToString().ToUpper();
string[] validfiles = new string[] { ".PNG", ".JPG" };
foreach (string s in validfiles)
{
if (s == strExtension)
return true;
}
return false;
}
}
ii)Method 2:
Add below code in web.config,
<appSettings>
<add key="ValidFiles" value=".TXT,.DOC,.DOCX,.XLS,.PDF,.JPG,.PNG" />
</appSettings>
Add below code in .aspx.cs page,
public Boolean ValidateFile()
{
string strExtension = "," + Path.GetExtension(fupload.PostedFile.FileName).ToString().ToUpper() + ",";
string strValidFiles = ","+ConfigurationManager.AppSettings["ValidFiles"].ToString()+",";
if (strValidFiles.IndexOf(strExtension.Trim().ToUpper()) != -1)
return true;
else
return false;
}
c) Store uploaded file in folder with a unique name
Method 1:
string strGuid = Convert.ToString(Guid.NewGuid());
string strOriginalFilename, strUniqueFilename;
strOriginalFilename = Path.GetFileName(fupload.FileName);
strUniqueFilename = strGuid + "." + Path.GetExtension(fupload.FileName);
fupload.PostedFile.SaveAs(Server.MapPath("~\\UploadedFiles") + "\\" + strUniqueFilename);
Method 2:
string strOriginalFilename, strUniqueFilename;
strOriginalFilename = Path.GetFileName(fupload.FileName);
strUniqueFilename = DateTime.Now.Ticks.ToString() + "_" + Path.GetFileName(fupload.FileName);
fupload.PostedFile.SaveAs(Server.MapPath("~\\UploadedFiles") + "\\" + strUniqueFilename);
d)View uploaded file
protected void lbnFilename_OnClick(object sender, EventArgs e)
{
string strFilePath = Server.MapPath("~//UploadedFiles") + "\\" + hfUniqueFilename.Value;
if (System.IO.File.Exists(strFilePath) == true)
{
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + hfFilename.Value);
Response.ContentType = "application/href";
Response.WriteFile(Server.MapPath("~//UploadedFiles") + "\\" + hfUniqueFilename.Value);
Response.Flush();
Response.End();
}
}
e) Delete an uploaded file from the local folder
string strFolderPath = Server.MapPath("~//UploadedFiles ") + "\\" + strUniqueFilename;
if (System.IO.File.Exists(strFolderPath))
System.IO.File.Delete(strFolderPath);
----------------------------------------------------------------------------------------
2)To restrict usage of backbutton
<script type="text/javascript">
function noBack(){window.history.forward()}
noBack();
window.onload=noBack;
window.onpageshow=function(evt){if(evt.persisted)noBack()}
window.onunload=function(){void(0)}
</script>
----------------------------------------------------------------------------------------
3)To pass xml data as a parameter of an SP
Step 1:
Create a datatable with needed columns and add it to a dataset and add its contents to a string
string[] strHoliday=new string[1];
DataTable dt = new DataTable();
dt.Columns.Add("DocID");
dt.Columns.Add("FromDate");
dt.Columns.Add("ToDate");
DataRow dr;
for(int i=0;i<lbxHolidays.Items.Count;i++)
{
dr = dt.NewRow();
strHoliday = lbxHolidays.Items[i].ToString().Split(new string[] { "to" }, StringSplitOptions.None);
dr["DocID"] = hfSelectedID.Value;
dr["FromDate"] = strHoliday[0];
dr["ToDate"] = strHoliday[1];
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
string strXmlHolidayList = ds.GetXml();
(pass strXmlHolidayList as parameter of SP)
Step 2: Insert XML datas to SQL table
@HolidayList VARCHAR(MAX)=null,
@idoc INT=null
AS
BEGIN
EXEC sp_xml_preparedocument @idoc OUTPUT, @HolidayList
INSERT INTO Tutorial_InsertXmlData
SELECT * FROM OPENXML (@idoc, '/NewDataSet/Table1',2)
WITH (DocID int,FromDate datetime,ToDate datetime)
-----------------------------------------------------------------------------------------
4)To change actual URL
Step 1:
Add Global Application Class and include below code,
void Application_BeginRequest(object sender, EventArgs e)
{
Rewriter.Process();
}
Step 2:
Add a class Rewriter.cs and include below code
public class Rewriter
{
protected XmlNode _oRules = null;
private const int Id=0;
public Rewriter(string url, int value)
{
HttpContext.Current.Response.Redirect(url);
}
protected Rewriter()
{
}
public string GetSubstitution(string zPath)
{
if (zPath.EndsWith("a")) //here 'a' is the duplicate path and it is given inside response.redirect
return zPath.Replace(zPath, "ImageUpload.aspx?id=1");
if (zPath.EndsWith("b"))
return zPath.Replace(zPath, "FileUpload.aspx?id=1");
return zPath;
}
public static void Process()
{
Rewriter oRewriter = new Rewriter();
string zSubst = oRewriter.GetSubstitution(HttpContext.Current.Request.Path);
if (zSubst.Length > 0)
{
HttpContext.Current.RewritePath(zSubst);
}
}
}
----------------------------------------------------------------------------------------
5) Dropdown list selected index changed event not fired after page validation failed.
Include onchange="Page_BlockSubmit = false;"
----------------------------------------------------------------------------------------
6)Return multiple values from a popup
In .aspx main page,
<script language="javascript" type="text/javascript">
function OpenPersonList()
{
var urlPath = 'Persons.aspx?';
var height = 155;
var width = 400;
var sizestring = 'dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;center:Yes;scroll:No;status:No;edge:Raised;';
var retValue = window.showModalDialog(urlPath, '', sizestring);
var retvalues = new Array();
retvalues = retValue;
if (retvalues != null && retvalues.length >= 1) {
document.getElementById('<%=hfPersonID.ClientID %>').value = retvalues[0];
document.getElementById('<%=hfPersonName.ClientID %>').value = retvalues[1];
return true;
}
else
return false;
}
</script>
In .aspx.cs main page,
protected void btnSearch_Click(object sender, EventArgs e)
{
string[] strName = hfPersonName.Value.Split(',');
string[] strIDs = hfPersonID.Value.Split(',');
for (int i = 0; i < strName.Length; i++)
{
ListItem item = new ListItem(strName[i], strIDs[i]);
if (lbxSelectedPersons.Items.Contains(item) == false)
{
lbxSelectedPersons.Items.Add(item);
}
else
MessageBox.Show("Designtaed Person is already added to the list.");
}
hfPersonName.Value = "";
hfPersonID.Value = "";
}
In .aspx of popup page,
<script language="javascript" type="text/javascript">
function handleActionPopUp(id, name)
{
if (form1.hfAction.value == "Y")
{
var retvalues = new Array();
retvalues[0] = document.getElementById('hfPersonID').value;
retvalues[1] = document.getElementById('hfPersonName').value;
window.returnValue = retvalues;
window.close();
}
}
</script>
<body onload="handleActionPopUp(0,0);">
In .aspx.cs of popup page,protected void btnSelectClose_Click(object sender, EventArgs e)
{
string strIDs = "", strNames = "";
for (int i = 0; i < gvPersons.Rows.Count; i++)
{
CheckBox cbox = gvPersons.Rows[i].FindControl("chkSelect") as CheckBox;
if (cbox.Checked)
{
strIDs += (gvPersons.Rows[i].Cells[1].Text + ",");
strNames += (gvPersons.Rows[i].Cells[2].Text + ",");
}
}
if (strNames.Length > 0)
{
strNames = strNames.Substring(0, strNames.Length - 1);//to remove last comma
strIDs = strIDs.Substring(0, strIDs.Length - 1);
hfPersonName.Value = strNames;
hfPersonID.Value = strIDs;
hfAction.Value = "Y";
}
else
Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","alert('Please select atleast one person to be added.')",true);
}
------------------------------------------------------------------------------------------
7)Javascript to enable a disabled checkbox
function ChkEnabled()
{
var a = document.getElementById('<%=CheckBox1.ClientID %>');
a.disabled = false;
if(a.parentElement.tagName == 'SPAN' && a.parentElement.disabled == true)
a.parentElement.disabled = false;
}
------------------------------------------------------------------------------------------
8)CommandName, CommandArgument and Text properties of a linkbutton (in gridview)
In .aspx page,
<ItemTemplate>
<asp:LinkButton ID="lbtnAttachments" runat="server" CommandArgument='<%#Eval("UpdatedOn") %>' CommandName='<%#Eval("UniqueFilename") %>' Text='<%#Eval("OriginalFilename") %>'
OnClick="lbtnAttachments_Click"></asp:LinkButton>
</ItemTemplate>
In .aspx.cs page,
protected void lbtnAttachments_Click(object sender, EventArgs e)
{
LinkButton obj = (LinkButton)sender;
string x = obj.CommandName.ToString();
string y = obj.CommandArgument.ToString();
}
------------------------------------------------------------------------------------------
9)To delete a row in a datatable
for (int i = 0; i < dt.Rows.Count; i++)
{
if (Convert.ToString(dt.Rows[i]["ID"].ToString()) == "3") {
dt.Rows[i].Delete();
dt.AcceptChanges();
}
}
------------------------------------------------------------------------------------------
10)To find and change properties of a control in master page
In child page, include below code,
In Page_Load,
Button objMPButton = (Button)FindControlRecursive(this, "btnMapProcess");
if (objMPButton != null)
objMPButton.CssClass = "TConfigSelected";
And add below function,
public Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
--------------------------------------------------------------------------------------------
11)Hide an image in a gridview column based on another column text
protected void gv_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
string strPriority = drv["ColumnName"].ToString();
Image img = (Image)e.Row.FindControl("imgName");
if(strPriority= ="a")
img.visible=false;
}
}
--------------------------------------------------------------------------------------------
12)Set super admin in web.config
In web.config,
<appSettings>
<add key="SuperAdminName" value="n"/>
<add key="SuperAdminPassword" value="nc"/>
</appSettings>
In master.aspx,
string strSuperAdminName = ConfigurationManager.AppSettings["SuperAdminName"].ToString();
string strSuperAdminPassword = ConfigurationManager.AppSettings["SuperAdminPassword"].ToString();
if(Session["Name"]= =strSuperAdminName && Session["Password"] = = strSuperAdminPassword )
{
}
--------------------------------------------------------------------------------------------
modified on Wednesday, August 10, 2011 5:45 AM
modified 11-Oct-11 3:17am.
|
|
|
|
|
include below code in web.config so that user can upload more than 4MB size files,
<system.web>
<httpRuntime maxRequestLength="2097151" requestLengthDiskThreshold="2097151"/>
</system.web>
in c# code page (restrict files above 5MB),
Convert.ToInt64(fupload.PostedFile.ContentLength) > 5242880
---------------------
validate and upload resized file
if (ValidateFile())
{
strFilename = DateTime.Now.Ticks.ToString() + "_" + Path.GetFileName(fupload.FileName);
int intRetValue = AddUploadedFile(strFilename);
if (intRetValue > 0)
{
string strSavePath = Server.MapPath("UploadedFiles") + "\\" + strFilename;
fupload.PostedFile.SaveAs(strSavePath);
//to resize image
ResizeImage(strSavePath, 100, 100, false);
imgPhoto.ImageUrl = "~/UploadedFiles/"+strFilename;
FillIDs();
}
return;
}
public Boolean ValidateFile()
{
string strExtension = Path.GetExtension(fupload.PostedFile.FileName).ToString().ToUpper();
string[] validfiles = new string[] { ".PNG", ".JPG" };
foreach (string s in validfiles)
{
if (s == strExtension)
return true;
}
return false;
}
public int ResizeImage(string FilePath, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
{
System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(FilePath);
// Prevent using images internal thumbnail
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
if (OnlyResizeIfWider)
{
if (FullsizeImage.Width <= NewWidth)
{
NewWidth = FullsizeImage.Width;
}
}
int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
if (NewHeight > MaxHeight)
{
// Resize with height instead
NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
NewHeight = MaxHeight;
}
System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);
// Clear handle to original file so that we can overwrite it if necessary
FullsizeImage.Dispose();
// Save resized picture
NewImage.Save(FilePath);
return 1;
}
----------
Example to remove old uploaded file in the folder,
string strFolderPath = Server.MapPath("UploadedFiles") + "\\" + strOldFileName;
if (System.IO.File.Exists(strFolderPath))
System.IO.File.Delete(strFolderPath);
----------
|
|
|
|
|
|
1) window.showModalDialog
2) Date validation using javascript
3) To fire validation summary before showing an alert (Page_ClientValidate())
4) Javascript to detect browser and screen height to set height of a div
5) Check whether a textbox value is null or ""
6) Export contents in a gridview in excel format
7) To retrieve selected value and text of a dropdownlist using javascript
8) To allow only integer values in an asp textbox
9) To restrict drop and count characters on 'copy paste' in a textbox
10) Encrypt and Decrypt
11) Without 3 tier architecture
------------------------------------------------------------------------------------------
1) window.showModalDialog
function Edit(ID)
{
var height = 140;
var width = 400;
var sizestring = 'dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;center:Yes;scroll:No;status:No;edge:Raised;';
var retValue = window.showModalDialog('AddEditCategory.aspx?CategoryId=' + ID, '', sizestring);
}
------------------------------------------------------------------------------------------
2)Date validation using javascript
a) When we have two dates itself
function ValidateEndDate() {
if (document.getElementById('<%=wdcStartDate.ClientID %>').value != "" && document.getElementById('<%=wdcEndDate.ClientID %>').value != "") {
var StartDate;
var EndDate;
var value = document.getElementById('<%=wdcStartDate.ClientID %>').value;
var year = value.substring(0, value.indexOf("-"));
value = value.substring(value.indexOf("-") + 1);
var smonth = value.substring(0, value.indexOf("-"));
var dt = value.substring(value.indexOf("-") + 1);
StartDate = Date.UTC(year, smonth, dt, 0, 0, 0);
value = document.getElementById('<%=wdcEndDate.ClientID %>').value;
year = value.substring(0, value.indexOf("-"));
value = value.substring(value.indexOf("-") + 1);
smonth = value.substring(0, value.indexOf("-"));
dt = value.substring(value.indexOf("-") + 1);
EndDate = Date.UTC(year, smonth, dt, 0, 0, 0);
if (EndDate < StartDate) {
alert('End Date cannot be before Start Date');
return false;
}
}
return true;
}
b) When we have two dates in string format and check it as dates
<script language="javascript" type="text/javascript">
Date.prototype.toDDMMYYYYString = function ()
{
return isNaN (this) ? 'NaN' : [this.getDate() > 9 ? this.getDate() : '0' + this.getDate(), this.getMonth() > 8 ? this.getMonth() + 1 : '0' + (this.getMonth() + 1), this.getFullYear()].join('/')
}
Date.fromDDMMYYYY = function (s)
{
return (/^(\d\d?)\D(\d\d?)\D(\d{4})$/).test(s) ? new Date(RegExp.$3, RegExp.$2 - 1, RegExp.$1) : new Date (s)
}
function CheckToDate()
{
var FromDate = document.getElementById('<%=hfFromDate.ClientID %>').value;
var ToDate = document.getElementById('<%=hfToDate.ClientID %>').value;
var From = Date.fromDDMMYYYY(FromDate);
var To = Date.fromDDMMYYYY(ToDate);
if(From>To)
{
alert("To Date must be greater than From Date");
return false;
}
}
-----------------------------------------------------------------------------
3) To fire validation summary before showing an alert (Page_ClientValidate())
function ValidateSpecificValidationGroup() {
if (Page_ClientValidate(‘ValidationGroup1′)) {
return confirm(“Are you sure to modify above details?”);
}
}
------------------------------------------------------------------------------
4)Javascript to detect browser and screen height to set height of a div
<script type="text/javascript">
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
if(screen.height!=null)
{
var setHeight;
if(browserName=="Microsoft Internet Explorer")
setHeight = screen.height-260+'px';
else if(browserName=="Firefox")
setHeight = screen.height-240+'px';
else if(browserName=="Chrome")
setHeight = screen.height-160+'px';
else if(browserName=="Opera")
setHeight = screen.height-170+'px';
else
setHeight = screen.height-260+'px';
document.getElementById('<%=divGV.ClientID %>').style.height=setHeight;
}
</script>
----------------------------------------------------------------------------------------
5)Check whether a textbox value is null or ""
document.getElementById('<%=txtName.ClientID%>').value.replace(/\s/g,"") == "";
------------------------------------------------------------------------------------------
6) Export contents in a gridview in excel format
In .aspx page,
<asp:LinkButton ID="lbtnExcelExport" runat="server" Text="Export To Excel" OnClick="lbtnExporttoExcel_Click"
class="linkButton" ToolTip="Click here to export the records to excel document"
Style="font-weight: bold; font-size: 13px; text-decoration: underline; cursor: hand;" />
In .aspx.cs page,
protected void lbtnExporttoExcel_Click(object sender, EventArgs e)
{
gvNonPaidLICReport.AllowPaging = false;
FillEmployees();
ArrayList arr = new ArrayList();
arr.Add("MyHiddenFieldName");
ExportGridView(gvNonPaidLICReport, "Non-Paid LIC Report", arr);
gvNonPaidLICReport.AllowPaging = true;
FillEmployees();
}
protected void ExportGridView(GridView grdView, string filename, ArrayList excludedColumnList)
{
// Clear response content & headers
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
// Add header
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.ContentType = "application/vnd.xls";
// Create stringWriter
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
// Create HtmlTextWriter
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
// Remove controls from Column Headers
if (grdView.HeaderRow != null && grdView.HeaderRow.Cells != null)
{
for (int ct = 0; ct < grdView.HeaderRow.Cells.Count; ct++)
{
// Save initial text if found
string headerText = grdView.HeaderRow.Cells[ct].Text;
// Check for controls in header
if (grdView.HeaderRow.Cells[ct].HasControls())
{
// Check for link button
if (grdView.HeaderRow.Cells[ct].Controls[0].GetType().ToString() == "System.Web.UI.WebControls.DataControlLinkButton")
{
// link button found, get text
headerText = ((LinkButton)grdView.HeaderRow.Cells[ct].Controls[0]).Text;
}
// Remove controls from header
grdView.HeaderRow.Cells[ct].Controls.Clear();
}
// Reassign header text
grdView.HeaderRow.Cells[ct].Text = headerText;
}
}
// Remove footer
if (grdView.FooterRow != null)
{
grdView.FooterRow.Visible = false;
}
// Remove unwanted columns (header text listed in removeColumnList arraylist)
foreach (DataControlField field in grdView.Columns)
{
if (excludedColumnList.Contains(field.HeaderText))
{
field.Visible = false;
}
}
// Call gridview's renderControl
grdView.RenderControl(htmlWrite);
// Write Response to browser
Response.Write(stringWrite.ToString());
Response.End();
}
------------------------------------------------------------------------------------------
7) To retrieve selected value and text of a dropdownlist using javascript
var keyValue =document.getElementById('<%=ddlProcessName.ClientID %>').options[document.getElementById('<%=ddlProcessName.ClientID%>').selectedIndex].value;
var keyValue =document.getElementById('<%=ddlOperators.ClientID %>').options[document.getElementById('<%=ddlOperators.ClientID%>').selectedIndex].text;
------------------------------------------------------------------------------------------
8) To allow only integer values in an asp textbox
<asp:TextBox ID="txtEmpID" runat="server" Width="150px" onChange="intonly(this);"
onkeyUp="intonly(this);" onkeyPress="intonly(this);"></asp:TextBox>
<script language="javascript" type="text/javascript">
function intonly(i)
{
if(i.value.length>0)
{
i.value=i.value.replace(/[^\d]+/g,'');
}
}
</script>
------------------------------------------------------------------------------------------
9) To restrict drop and count characters on 'copy paste' in a textbox
In .aspx page,
function CheckCount(source,maxLimit)
{
var length = document.getElementById(source).value.length;
if(length <= maxLimit-1)
{
return true;
}
else
{
return false;
}
}
function pasteHandler(source,maxLimit,destination)
{
var len= document.getElementById(source).value.length;
var currentData = clipboardData.getData("Text");
var total= parseInt(len) + parseInt(currentData.length);
var stringVal = document.getElementById(source).value + currentData;
if(total > maxLimit)
{
alert('You can enter only 1000 characters.');
}
else
{
insert(document.getElementById(source),currentData);
}
return false;
}
function insert(el, ins)
{
if (el.setSelectionRange)
{
el.value = el.value.substring(0, el.selectionStart) + ins + el.value.substring(el.selectionStart, el.selectionEnd) + el.value.substring(el.selectionEnd, el.value.length);
}
else if (document.selection && document.selection.createRange)
{
el.focus();
var range = document.selection.createRange();
range.text = ins + range.text;
}
}
In .aspx.cs page,
txtDescription.Attributes.Add("ondrop", "return false;");
txtDescription.Attributes.Add("onpaste", "return pasteHandler('" + txtDescription.ClientID + "','" + txtDescription.MaxLength + "');");
txtDescription.Attributes.Add("onkeypress", "return CheckCount('" + txtDescription.ClientID + "','" + txtDescription.MaxLength + "');");
-----------------------------------------------------------------------------------------
10)Encrypt and Decrypt
a) Using Secure Hash Algorithm (Encrypt Only)
public static string HashCode(string str)
{
string rethash = "";
try
{
System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
byte[] combined = encoder.GetBytes(str);
hash.ComputeHash(combined);
rethash = Convert.ToBase64String(hash.Hash);
}
catch (Exception ex)
{
string strerr = "Error in HashCode : " + ex.Message;
}
return rethash;
}
b)Add a class (say Cryptography.cs) and include below code
public static string Encrypt(string plainText)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); ;
}
public static string Decrypt(string cipherText)
{
return (SHA) Encoding.UTF8.GetString(Convert.FromBase64String(cipherText));
}
------------------------------------------------------------------------------------------
11)Without 3 tier architecture
In web.config,
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=10.11.16.32;Initial Catalog=DBName;User ID=sa;Password=sasa" />
</connectionStrings>
In .aspx.cs page,
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("ProcedureName", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@DocID", hfID.Value));
cmd.Parameters.Add(new SqlParameter("@AppDate", txt1.Text));
intTokenNo = (Int32)cmd.ExecuteScalar();
}
------------------------------------------------------------------------------------------
modified on Monday, September 5, 2011 3:31 AM
|
|
|
|
|