setting focus of the modal popup by script
<script language="javascript" type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
var blnReportWinOpen = false;
function BeginRequestHandler(sender, args) {
$find('<%= mpeProgress.ClientID %>').show();
}
function EndRequestHandler(sender, args) {
$find('<%= mpeProgress.ClientID %>').hide();
}
</script>
</body>
RadTreeView.Net2.dll and xml
Telrik and DevExpress |
| Assembly name |
| RadPanelbar.Net2.dll and xml |
| RadChart.dll and xml |
| Global.asax It is use to handle session and application state . when the application loads first it calls The Application_OnStart then Session_Start then Page_Load event |
| TextOnImage.aspx |
| <asp:Image ID="Image1" runat="server" ImageUrl="~/ImageTextFile.aspx"/> |
| ImageTextFile Page_Load event |
| using System.Drawing; |
| using System.Drawing.Imaging; |
| ff |
| protected void Page_Load(object sender, EventArgs e) |
| { |
| Bitmap bitmapImage = new Bitmap(Server.MapPath("Water lilies.jpg")); |
| Graphics g = Graphics.FromImage(bitmapImage); |
| g.DrawString("Hi EveryOne", new Font("Arial", 12, FontStyle.Bold), new SolidBrush(Color.Red), new PointF(10, 10)); |
| Response.ContentType = "image/jpg"; |
| bitmapImage.Save(Response.OutputStream, ImageFormat.Jpeg); |
| } |
| <asp:TextBox ID="txtStaffNumber" Style="width: 220px;" runat="server" ReadOnly="false"TabIndex="1"></asp:TextBox> |
| <asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" ControlToValidate="txtStaffNumber" ErrorMessage="Staff No : Can not be blank" ToolTip="Staff Number: Can not be blank" Display="Dynamic" SetFocusOnError="true" ValidationGroup="Step1"> </asp:RequiredFieldValidator> |
| <asp:ImageButton runat="server" ID="btnUpdate" ImageUrl="~/images/buttons/PHS/submit_1.gif" ValidationGroup="Step1" OnClick="btnUpdate_Click" /> |
| <asp:Button ID="Button1" runat="server" Text="Button" /> |
| NOTE:- |
| ValidationGroup value Validator will work only for that ValidationGroup only |
| On Button1 click the validator will not show error |
| TabIndex if we set the increment +1 for each control then on Tab click it will move according to number but the no |
| control should have TabIndex=0 which is ByDefaullt make it to -1 for control we don't want the focus on tab click |
| Repeater Control |
| In Repeater1_ItemDataBound it takes the Item(Rows) as Item and AlternateItem so |
| Repeater1_ItemDataBound event |
| if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) |
| Adding ......... aftre the 200 character |
| string str_content; |
| Label lblContent=(Label)e.Item.FindControl("lblContent"); |
| For Repeater control |
| Label lblContent=(Label)e.Item.FindControl("lblContent"); |
| str_content = (string)DataBinder.Eval(e.Item.DataItem, "ContentText"); |
| Label lblContent=(Label)e.Item.FindControl("lblContent"); |
| For Gridview control |
| Label lblContent=(Label)e.Row.FindControl("lblContent"); |
| str_content = (string)DataBinder.Eval(e.Row.DataItem, "ContentText"); |
| int count = str_content.Length; |
| if (count > 200) |
| { |
| string sub = str_content.Substring(0, 200); |
| lblContent.Text = sub + "...."; |
| } |
| else |
| { |
| lblContent.Text = str_content; |
| } |
| ff |
| ff |
| BATCH Update |
|
1 table public static int UpdateDataset(DataSet dsData) if (dt != null && dt.GetChanges() != null && dt.GetChanges().Rows.Count > 0) internal static string selectQuery(DataTable dt) Multiple Table Have PK and FK Releationship public int Update(DataSet dsData) |
| Calling Batch Upadate |
| DataSet dsa = new DataSet(); dtCurrentMedication = (DataTable)ViewState["DataTable"]; dsa.Tables.Add(dtCurrentMedication); int id = Common.UpdateDataset(dsa); |
| ff |
| ff |
| Generate the Random value by passing the length of the o/p value |
| public String generateRandomString(int length) |
| { |
| String randomString = ""; |
| int randNumber; |
| Random random = new Random(); |
| Random random = new Random(); |
| for (int i = 0; i < length; i++) |
| { |
| if (random.Next(1, 3) == 1) |
| randNumber = random.Next(97, 123); //char {a-z} |
| else |
| randNumber = random.Next(48, 58); //int {0-9} |
| //append random char or digit to random string |
| randomString = randomString + (char)randNumber; |
| } |
| return randomString; |
| } |
| asp:ImageButton Issue |
| The PostBackUrl cannot call html page |
| PreView The Image Before Saving in aa folder or databaseBut it works only in IE |
| <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImagePreviewFileUpload.aspx.cs" Inherits="ImagePreviewFileUpload" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script language="javascript" type="text/javascript"> </head> |
| 2) |
| <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> <title>Image preview example</title> <script type="text/javascript"> /jpeg|image/pipeg|image/png|image/svg+xml|image/tiff|image/x-cmu-raster|image/x-cmx|image/x-icon|image/x<br/> -portable-anymap|image/x-portable-bitmap|image/x-portable-graymap|image/x-portable-pixmap|image/x-rgb|image<br/> /x-xbitmap|image/x-xpixmap|image/x-xwindowdump)$/i; oFReader.onload = function (oFREvent) { function loadImageFile() { </head> |
| 3) |
| <script type="text/javascript" language="javascript"> function ImageViw(string) { var imgPreview=document.getElementById("imgPreview"); document.getElementById('imgPreview').src='File://' + string; } </script> <asp:FileUpload ID="JFileUp" runat="server" onchange="javascript:ImageViw(this.value);" /> |
|
Only letters: <p>
Only letters and numbers:
Only letters, numbers and underscore:
|
|
retrieving the distinct column values string[] strColumnsManagerArr = { "Acc Manager name", "AccountMangerID" }; |
Thread |
| 1. How to create Thread? |
|
A. Namespace. |
| using System.Threading; |
| Thread t1 = new Thread(new System.Threading.ThreadStart(sendMail)); //sendMail function should be parameterless t1.Start(); |
|
publi void sendMail() {//here your full fletch code } |
| 2. How to work with TWO thread. |
| A. Create two instance of thread. |
|
Thread t1=new Thread(ThreadStart(sendmail)); Thread t2=new Thread(ThreadStart(EnterValue)); t1.start; //initiall it required to start the thread if want to make thread wait use t.Interrupt();--like WaitSleepJoin |
|
public void sendMail() //Here we are using a variable which is running on different thread (str_Success & str_Fail) //So we use this if condition |
| Export gridview to excel |
| <table> <tr> <td> <asp:ImageButton ID="imgExcel" runat="server" ImageUrl="~/ExcelImage.jpg" OnClick="imgExcel_OnClick" /> </td> </tr> <tr> <td> <asp:GridView runat="server" ID="gvdetails" DataSourceID="SqlDataSource1" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false"> <RowStyle BackColor="#EFF3FB" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:BoundField DataField="Fid" HeaderText="Fid" /> <asp:BoundField DataField="User_FirstName" HeaderText="User_FirstName" /> <asp:BoundField DataField="User_LastName" HeaderText="User_LastName" /> <asp:BoundField DataField="User_Email" HeaderText="User_Email" /> <asp:BoundField DataField="User_LoginId" HeaderText="User_LoginId" /> <asp:BoundField DataField="User_Pwd" HeaderText="User_Pwd" /> <asp:CheckBoxField DataField="User_Locked" HeaderText="User_Locked" /> <asp:BoundField DataField="User_RoleId" HeaderText="User_RoleId" /> <asp:BoundField DataField="Pid" HeaderText="Pid" /> </Columns> </asp:GridView> </td> </tr> </table> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:local %>" SelectCommand="SELECT * FROM [Users]"></asp:SqlDataSource> |
| Code |
| protected void imgExcel_OnClick(object sender, ImageClickEventArgs e) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "asd.xls")); HttpContext.Current.Response.ContentType = "application/vn.xls"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { // Create a form to contain the grid Table table = new Table(); // add the header row to the table if (gvdetails.HeaderRow != null) { PrepareControlForExport(gvdetails.HeaderRow); table.Rows.Add(gvdetails.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gvdetails.Rows) { PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gvdetails.FooterRow != null) { PrepareControlForExport(gvdetails.FooterRow); table.Rows.Add(gvdetails.FooterRow); } // render the table into the htmlwriter table.RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { PrepareControlForExport(current); } } } |
| RSSS |
| <asp:XmlDataSource ID="XmlNewsFeed" runat="server" DataFile="http://www.logisticsit.com/feed.rss?tag=Supply+Chain" XPath="rss/channel/item"></asp:XmlDataSource> <asp:GridView ID="gvdnew" runat="server" DataSourceID="XmlNewsFeed" AutoGenerateColumns="false" AllowPaging="true" ShowHeader="false" border="0" BorderWidth="0" OnRowDataBound="gvdnew_OnRowDataBound" Width="95%" PageSize="8" PagerStyle-CssClass="Pg"> <Columns> <asp:TemplateField> <ItemTemplate> <div class="NCont"> <div class="header_05" style="font-family: calibri;"> <a id="lnk1" href='<%# XPath("link")%>' runat="server" target="_blank" style="font-size: 14px;"> <%# XPath("title")%></a></div> <asp:Label ID="Label1" runat="server" Text='<%# XPath("pubDate")%>' Style="text-align: justify; font-size: 13px; color: black; font-family: calibri;"></asp:Label><br /> <asp:Label ID="lblDesc" runat="server" Text='<%# XPath("description")%>' Style="text-align: justify; font-size: 12px; color: black; font-family: calibri;"></asp:Label> </div> <div class="cleaner"> </div> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> |
|
From Code behind http://www.aspsnippets.com/Articles/Fetch-and-Display-RSS-Feeds-using-ASP.Net.aspx |
Asp Char control
Allow Single decimal point Regular expression
d+(.d{1,2})?
Gridview Export to excel (Even if it is nested gridview)
protected void ImgExport_OnClick(object sender, EventArgs e)
{
try
{
gvCompanyListing.AllowPaging = false;
GetValueAndBind();
//table1.BorderStyle = BorderStyle.Solid;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename=ReportPendingPayment" + ".xls", gvCompanyListing));
HttpContext.Current.Response.ContentType = "application/vn.xls";
#region "Add Filter data"
TableRow tRow = new TableRow();
TableCell c1 = new TableCell();
string strComapanyText = ddlCompany.SelectedIndex > 0 ? ddlCompany.SelectedItem.Text : "All";
c1.Text = "Company = " + strComapanyText;
c1.HorizontalAlign = HorizontalAlign.Left;
tRow.Cells.Add(c1);
table1.Rows.Add(tRow);
tRow = new TableRow();
c1 = new TableCell();
string strStartDate = !string.IsNullOrEmpty(datepickerStartDate.Value) ? datepickerStartDate.Value : "N/A";
string strEnddate = !string.IsNullOrEmpty(datepickerEndDate.Value) ? datepickerEndDate.Value : "N/A";
c1.Text = "Start Date = " + strStartDate + " End Date = " + strEnddate;
c1.HorizontalAlign = HorizontalAlign.Left;
tRow.Cells.Add(c1);
table1.Rows.Add(tRow);
#endregion
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
// add the header row to the table
if (gvCompanyListing.HeaderRow != null)
{
PrepareControlForExport(gvCompanyListing.HeaderRow);
table1.Rows.Add(gvCompanyListing.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gvCompanyListing.Rows)
{
PrepareControlForExport(row);
row.BackColor = Color.Yellow;
table1.Rows.Add(row);
TableRow tr = new TableRow();
TableCell cell = new TableCell();
tr.Cells.Add(cell);
table1.Rows.Add(tr);
}
// add the footer row to the table
if (gvCompanyListing.FooterRow != null)
{
PrepareControlForExport(gvCompanyListing.FooterRow);
table1.Rows.Add(gvCompanyListing.FooterRow);
}
// render the table into the htmlwriter
table1.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
catch (Exception ex) { }
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
private void PrepareControlForExport(Control control)
{
try
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
catch (Exception ex) { }
}
Comma seperate in Gridview
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Values">
<ItemTemplate>
<asp:Literal runat="server" id="Values"
Text='<%# string.Join("<br />", Eval("Values").ToString().Split(new []{","},StringSplitOptions.None)) %>'>
</asp:Literal>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Output Direction
string CommandString = @"insert into Kpi_Company values(@cname) set @newid = SCOPE_IDENTITY() ";
Command = new SqlCommand(CommandString, Connection);
Command.Parameters.AddWithValue("@cname", cname);
Command.Parameters.Add("@newid", SqlDbType.Int).Direction = ParameterDirection.Output;
Connection.Open();
Command.ExecuteNonQuery();
id = Convert.ToInt64(Command.Parameters["@newid"].Value.ToString());
Connection.Close();
Connection.Dispose();
public string EncryptData(string Message)
{
try
{
byte[] Results;
string passphrase = "password";
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
catch (Exception ex)
{
return "";
}
}
public string DecryptString(string Message)
{
try
{
byte[] Results;
string passphrase = "password";
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
catch (Exception ex)
{
return "";
}
}
LINQ Standard Deviation
double[] dAverage = new double[8];
double[] dStandardDeviation = new double[8];
Call:
-> dStandardDeviation[0] = CalculateStdDev(d1.AsEnumerable(), dAverage[0]);
private double CalculateStdDev(IEnumerable<double> values, double avg)
{
double ret = 0;
if (values.Count() > 0)
{
//Compute the Average
//double avg = values.Average();
//Perform the Sum of (value-avg)^2
double sum = values.Sum(d => Math.Pow(d - avg, 2));
//Put it all together
ret = Math.Sqrt((sum) / (values.Count() - 1));
}
return ret;
}
Hiding url(.aspx)
Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
namespace WebApplication1
{
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes();
}
private static void RegisterRoutes()
{
System.Web.Routing.RouteTable.Routes.Add("Any Description1",
new System.Web.Routing.Route("home", new
PageRouteHandler("~/Default.aspx")));
System.Web.Routing.RouteTable.Routes.Add("Any Description2",
new System.Web.Routing.Route("About", new
PageRouteHandler("~/About.aspx")));
}
}
}
iText
public void ExportPDF()
{
var titleFont = FontFactory.GetFont("Arial", 14, iTextSharp.text.Font.BOLD);
iTextSharp.text.Font fontWhite = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 11, iTextSharp.text.Color.WHITE);
iTextSharp.text.Font fontSecRow = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 11);
iTextSharp.text.Font fontThirdRow = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD);
iTextSharp.text.Document Doc = new iTextSharp.text.Document(PageSize.A3, 25f, 25f, 25f, 15f);
string path = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["UserKpiDocs"]) + Request.Cookies["proid"].Value;
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
if (File.Exists(path + "StatusLog.pdf"))
{
File.Delete(path + "StatusLog.pdf");
}
var output = new FileStream(path + "/StatusLog.pdf", FileMode.Create);
iTextSharp.text.pdf.PdfWriter.GetInstance(Doc, output);
StringReader readerbg = new StringReader(lblActivity.Text + "<br/>");
StringReader readercs = new StringReader(lblAction.Text + "<br/>");
StringReader readerana = new StringReader(lblRisk.Text + "<br/>");
StringReader readergoal = new StringReader(lblMg.Text + "<br/>");
HTMLWorker parser = new HTMLWorker(Doc);
Doc.Open();
Paragraph pCompanyName = new Paragraph("StatusLog for " + lblCompanyName.Text, titleFont);
Paragraph pActivitiesPerformedthisPeriod = new Paragraph("Activities Performed this Period ", fontThirdRow);
Paragraph pActionsPlannedNextPeriod = new Paragraph("Actions Planned Next Period ", fontThirdRow);
Paragraph pRisks = new Paragraph("Risks/Issues/Concerns ", fontThirdRow);
Paragraph pMitigationActionsPlanned = new Paragraph("Mitigation Actions Planned", fontThirdRow);
pCompanyName.SetAlignment("Center");
pActivitiesPerformedthisPeriod.SetAlignment("left");
pActionsPlannedNextPeriod.SetAlignment("left");
pRisks.SetAlignment("left");
pMitigationActionsPlanned.SetAlignment("left");
Doc.Add(pCompanyName);
Doc.Add(pActivitiesPerformedthisPeriod);
parser.Parse(readerbg);
Doc.Add(pActionsPlannedNextPeriod);
parser.Parse(readercs);
Doc.Add(pRisks);
parser.Parse(readerana);
Doc.Add(pMitigationActionsPlanned);
parser.Parse(readergoal);
Doc.Close();
output.Close();
}
ASP.Net URL re-writing in VS 2010
Start
http://localhost:22333/about
public class Global : System.Web.HttpApplication
{
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("Home", "Home", "~/Default.aspx");
routes.MapPageRoute("About", "About", "~/About.aspx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
}
<a href="Home" />Home</a>
<a href="About" />About</a>
End URL rewriting

