Friday, April 30, 2010

Programmatically adding paging in Gridview - ASP.NET

 

In *.aspx page insert a gridview like this:

<asp:GridView ID="courseListGridView" runat="server" CssClass="gridViewStyle2" 
AllowPaging="True" PageSize="20"
onpageindexchanging="courseListGridView_PageIndexChanging">
<PagerSettings FirstPageText="First Page" LastPageText="Last Page"
Mode="NextPreviousFirstLast" NextPageText="Next Page"
PreviousPageText="Previous Page" />
</asp:GridView>


Then in the code behind add this code:


public void LoadAllCourses()
{
// Create MySql Connection
using (MySqlConnection conn = new MySqlConnection())
{
// Configure the connection from the web.config entry
conn.ConnectionString = ConfigurationManager.ConnectionStrings["eraConnectionString"].ConnectionString;

// SQL Command for GridView
string cmdText = "Select * from student.courseinfo";

// Set MySQL Command
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.CommandType = CommandType.Text;

MySqlDataAdapter cmdAdapter = new MySqlDataAdapter();
cmdAdapter.SelectCommand = cmd;
// Create empty DataSet
DataSet resultsDS = new DataSet();
conn.Open();
cmdAdapter.Fill(resultsDS);
conn.Close();

courseListGridView.DataSource = resultsDS;
courseListGridView.DataBind();
}
}

protected void courseListGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
courseListGridView.PageIndex = e.NewPageIndex;
LoadAllCourses();

}

Thursday, April 29, 2010

Rules for Speeding Up Your Web Site

Rules to follow on "How to speed up your website":

Speed up website Rules

Friday, April 23, 2010

Register the 2007 Office system file format MIME types on servers

To see the list of content types for different file format while downloading the file, please go to the following link.

Register the 2007 Office system file format MIME types on servers

Tuesday, April 13, 2010

read, write, save and update XML in Silverlight

using System.Xml.Linq;
using System.IO.IsolatedStorage;
using System.IO;
using System.Linq;

private void CreateXdoc()
{
_xdoc = new XDocument(
new XComment("Created " + DateTime.Now.ToLongTimeString()),
new XElement("Root",
new XElement("Child", "data1",new XAttribute("attr", 1)),
new XElement("Child", "data2", new XAttribute("attr", 2)),
new XElement("Child", "data3", new XAttribute("attr", 3)),
new XElement("Child", "data4", new XAttribute("attr", 4))
)
);

ShowXDoc();
}

private void ReadXDoc()
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream stream = store.OpenFile("MyXmlFile.Xml", FileMode.Open, FileAccess.Read);
_xdoc = XDocument.Load(stream);
ShowXDoc();
stream.Dispose();
}
}

private void SaveXDoc()
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream stream = store.OpenFile("MyXmlFile.Xml", FileMode.Create, FileAccess.Write);
_xdoc.Save(stream);
stream.Dispose();
}
MessageBox.Show("Saved");
}

private void AddChild()
{
if (_xdoc == null)
{
MessageBox.Show("Please create doc first");
return;
}
int nextNumber = _xdoc.Element("Root").Elements("Child").Count()+1;

XElement newChild = new XElement("Child","data" + nextNumber );
newChild.Add(new XAttribute("attr", nextNumber));
_xdoc.Element("Root").Add(newChild);

ShowXDoc();

}

private void ShowXDoc()
{
TextBox1.Text = _xdoc.ToString();
}

private void ModifyXDoc()
{
var item = from c in _xdoc.Element("Root").Elements("Child")
where c.Attribute("attr").Value == TextBox2.Text
select c;

item.Remove();
ShowXDoc();
}

Sunday, April 11, 2010

Relative vs Absolute Path in ASP.NET

Relative and Absolute Path



  • An absolute URL path. An absolute URL path is useful if you are referencing resources in another location
  <img src="http://www.contoso.com/MyApplication/Images/SampleImage.jpg" />

  • A site-root relative path, which is resolved against the site root


     <img src="/Images/SampleImage.jpg" />
If your Web site is http://www.softxen.com, the path would resolve to

http://www.contoso.com/Images/SampleImage.jpg


  • A relative path that is resolved against the current page path.(<img src="Images/SampleImage.jpg" />)



  • A relative path that is resolved as a peer of the current page path.(<img src="../Images/SampleImage.jpg" />)


Absolute and relative path references in a server control have the following disadvantages:

  • Absolute paths are not portable between applications. If you move the application that the absolute path points to, the links will break.

  • Relative paths in the style of client elements can be difficult to maintain if you move resources or pages to different folders.

  • To overcome these disadvantages, ASP.NET includes the Web application root operator (~), which you can use when specifying a path in server controls.
   <asp:image runat="server" id="Image1" ImageUrl="~/Images/SampleImage.jpg" />

Count page load time in asp.net

Put the following code in the asp.net page for which you want to see the page load time.

 



DateTime startTime = DateTime.Now;

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.loadTimeLabel.Text = (DateTime.Now - startTime).TotalMilliseconds.ToString();
this.serverTimeLabel.Text = DateTime.Now.ToString();
}

Anonymous Types in .net

Anonymous Types (var name) :

  • Concisely define inline CLR types within code

  • No need to explicitly define a formal class declaration of the type.

  • Useful when querying and transforming/projecting/shaping data with LINQ.


var resultSet = from details in db.projectRequest_details
where details.rname.StartsWith("D")
select new
{
name = details.rname,
utaid = details.rutaid
};




  • the var keyword always generates a strongly typed variable reference.

  • var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

  • It is not possible to define a variable using "var" key word like var userName;, you have to declare it using some value like var userName="Quazi Mainul Hasan";

ViewState in asp.net

ViewState:

  • viewstate relies on a dictionary collection

  • where each item is indexed with a unique string name

  • Using ViewState: ViewState["id"] = 2;

  • Retrieving the value from ViewState: int number = (int) ViewState["id"];

  • Have to do a type cast to get the value

  • ViewState collection stores all items as generic objects

  • _ViewState is the Page ViewState.


Don't use view state in the following cases:

  • to store mission-critical data that the user cannot be allowed to tamper with.

  • to store information that will be used by multiple pages.

  • to store an extremely large amount of information, which slows down the page transmission


Note: Any data that you put in the view state will be part of the data stream that goes to the client and then comes back to the server, so be very careful while putting large chunks of data in the ViewState!

Serialization or Serializable in asp.net


  • To put a custom object into ViewState in asp.net, the class have to be declared as serializable by using the [Serializable] attribute before the class declaration.



  • Also, to store a object in ViewState, asp.net must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is called serialization.


Example:


[Serializable]

public class Student

{

public string firstName;

public string lastName;
public Student(string fName, string lName)

{

firstName = fName;

lastName = lName;

}

}
//Assigning the value into ViewState
Student std = new Student("Quazi", "Hasan");

ViewState["CurrentStudent"] = std;
//Retrieving the value

Student sampleStudent = (Student) ViewState["CurrentStudent"];

SortedList in .net

SortedList



  • Represents a collection of key-and-value pairs that are sorted by the keys and are accessible by key and by index.

  • In one of my program, I wanted to sort my values based on the keys, so I find out that SortedList is the best way of doing it.

  • SortedList is a hybrid between a Hashtable and an Array.

  • Operations on a SortedList tend to be slower than operations on a Hashtable because of the sorting.

  • SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.


Example:


public SortedList itemSetOneSL;

itemSetOneSL = new SortedList();

for(int i=5;i>0;i--)

{

if (!itemSetOneSL.Contains("C"+i.ToString())
{
itemSetOneSL.Add("C"+i.ToString(), i);
}
}

StreamWriter strWriter = new StreamWriter("test.txt");

foreach (var item in itemSetOneSL.Keys)
{

strWriter.WriteLine(item.ToString() + " " + itemSetOneSL[item.ToString()]);

}

strWriter.Close();
strWriter.Dispose();

Deploying asp.net application in webdav


  • Comment out  the following code from web.config in asp.net application.

  • Your Webdav will not allow you to deploy it  in the server without the modification.


<!--<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>-->

List of Server Variables in asp.net

In the code behind use: Response.Output.WriteLine(Request.ServerVariables[variableName].ToString() to print the output of a particular server variables.











































































































































































































Variable Name
Description
ALL_HTTP All HTTP headers sent by the client.
ALL_RAW Retrieves all headers in raw form. The difference between ALL_RAW and ALL_HTTP is that ALL_HTTP places an HTTP_ prefix before the header name and the header name is always capitalized. In ALL_RAW the header name and values appear as they are sent by the client.
APPL_MD_PATH Retrieves the metabase path for the Application for the ISAPI DLL.
APPL_PHYSICAL_PATHRetrieves the physical path corresponding to the metabase path. IIS converts the APPL_MD_PATH to the physical (directory) path to return this value.
AUTH_PASSWORDThe value entered in the client's authentication dialog. This variable is available only if Basic authentication is used.
AUTH_TYPEThe authentication method that the server uses to validate users when they attempt to access a protected script.
AUTH_USERThe name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. This variable is no different from REMOTE_USER. If you have an authentication filter installed on your Web server that maps incoming users to accounts, use LOGON_USER to view the mapped user name.
CERT_COOKIEUnique ID for client certificate, returned as a string. Can be used as a signature for the whole client certificate.
CERT_FLAGSbit0 is set to 1 if the client certificate is present.bit1 is set to 1 if the cCertification authority of the client certificate is invalid (it is not in the list of recognized CAs on the server).
CERT_ISSUERIssuer field of the client certificate (O=MS, OU=IAS, CN=user name, C=USA).
CERT_KEYSIZENumber of bits in Secure Sockets Layer connection key size. For example, 128.
CERT_SECRETKEYSIZENumber of bits in server certificate private key. For example, 1024.
CERT_SERIALNUMBERSerial number field of the client certificate.
CERT_SERVER_ISSUERIssuer field of the server certificate.
CERT_SERVER_SUBJECTSubject field of the server certificate.
CERT_SUBJECTSubject field of the client certificate.
CONTENT_LENGTHThe length of the content as given by the client.
CONTENT_TYPEThe data type of the content. Used with queries that have attached information, such as the HTTP queries GET, POST, and PUT.
GATEWAY_INTERFACEThe revision of the CGI specification used by the server. The format is CGI/revision.
HTTP_<HeaderName>The value stored in the header HeaderName. Any header other than those listed in this table must be prefixed by HTTP_ in order for the ServerVariables collection to retrieve its value.Note The server interprets any underscore (_) characters in HeaderName as dashes in the actual header. For example if you specify HTTP_MY_HEADER, the server searches for a header sent as MY-HEADER.
HTTP_ACCEPTReturns the value of the Accept header.
HTTP_ACCEPT_LANGUAGEReturns a string describing the language to use for displaying content.
HTTP_COOKIEReturns the cookie string that was included with the request.
HTTP_HOSTReturns the name of the Web server. This may or may not be the same as SERVER_NAME depending on type of name resolution you are using on your Web server (IP address, host header).
HTTP_REFERERReturns a string that contains the URL of the page that referred the request to the current page using an HTML <A> tag. Note that the URL is the one that the user typed into the browser address bar, which may not include the name of a default document.If the page is redirected, HTTP_REFERER is empty.

HTTP_REFERER is not a mandatory member of the HTTP specification.
HTTP_USER_AGENTReturns a string describing the browser that sent the request.
HTTPSReturns ON if the request came in through secure channel (SSL) or it returns OFF if the request is for a non-secure channel.
HTTPS_KEYSIZENumber of bits in Secure Sockets Layer connection key size. For example, 128.
HTTPS_SECRETKEYSIZENumber of bits in server certificate private key. For example, 1024.
HTTPS_SERVER_ISSUERIssuer field of the server certificate.
HTTPS_SERVER_SUBJECTSubject field of the server certificate.
INSTANCE_IDThe ID for the IIS instance in textual format. If the instance ID is 1, it appears as a string. You can use this variable to retrieve the ID of the Web-server instance (in the metabase) to which the request belongs.
INSTANCE_META_PATHThe metabase path for the instance of IIS that responds to the request.
LOCAL_ADDRReturns the Server Address on which the request came in. This is important on multi-homed computers where there can be multiple IP addresses bound to the computer and you want to find out which address the request used.
LOGON_USERThe Windows account that the user is impersonating while connected to your Web server. Use REMOTE_USER orAUTH_US<CODE>ER to view the raw user name that is contained in the request header. The only time LOGON_USER holds a different value than these other variables is if you have an authentication filter installed.
PATH_INFOExtra path information as given by the client. You can access scripts by using their virtual path and the PATH_INFO server variable. If this information comes from a URL, it is decoded by the server before it is passed to the CGI script.
PATH_TRANSLATEDA translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping.
QUERY_STRINGQuery information stored in the string following the question mark (?) in the HTTP request.
REMOTE_ADDRThe IP address of the remote host making the request.
REMOTE_HOSTThe name of the host making the request. If the server does not have this information, it will set REMOTE_ADDR and leave this empty.
REMOTE_USERThe name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. If you have an authentication filter installed on your Web server that maps incoming users to accounts, useLOGON_USER to view the mapped user name.
REQUEST_METHODThe method used to make the request. For HTTP, this is GET, HEAD, POST, and so on.
SCRIPT_NAMEA virtual path to the script being executed. This is used for self-referencing URLs.
SERVER_NAMEThe server's host name, DNS alias, or IP address as it would appear in self-referencing URLs.
SERVER_PORTThe port number to which the request was sent.
SERVER_PORT_SECUREA string that contains either 0 or 1. If the request is being handled on the secure port, then this will be 1. Otherwise, it will be 0.
SERVER_PROTOCOLThe name and revision of the request information protocol. The format is protocol/revision.
SERVER_SOFTWAREThe name and version of the server software that answers the request and runs the gateway. The format is name/version.
URLGives the base portion of the URL.

Making a Service Available Across Domain Boundaries




Using for cross-domain communication requires guarding against several types of security vulnerability that can be used to exploit Web applications. Cross-site forgery is a class of exploits that becomes a threat when allowing cross-domain calls. This exploit involves a malicious Silverlight control transmitting unauthorized commands to a third-party service, without the user's knowledge. To prevent cross-site request forgery, Silverlight only allows site-of-origin communication by default for all requests other than images and media. For example, a Silverlight control hosted at http://contoso.com/mycontrol.aspx can only access services on that same domain by default – for example http://contoso.com/service.svc, but not a service at http://fabrikam.com/service.svc. This prevents a malicious Silverlight control hosted on the http://contoso.com domain from calling unauthorized operations on a service hosted on the http://fabrikam.com domain.

To enable a Silverlight control to access a service in another domain, the service must explicitly opt-in to allow cross-domain access. By opting-in, a service states that the operations it exposes can safely be invoked by a Silverlight control, without potentially damaging consequences to the data the service stores.

Silverlight 2 supports two different mechanisms for services to opt-in to cross-domain access:

  • Place a clientaccesspolicy.xml file at the root of the domain where the service is hosted to configure the service to allow cross-domain-access.

  • Place a valid crossdomain.xml file at the root of the domain where the service is hosted. The file must mark the entire domain public. Silverlight supports a subset of the crossdomain.xml schema.


To use a clientaccesspolicy.xml file to allow cross-domain access




  1. Build a service than enables access by a Silverlight client. For more information about how to do this, see How to: Build a Service for Silverlight Clients.

  2. Create a clientaccesspolicy.xml file that allows access to the service. The following configuration allows access from any other domain to all resources on the current domain.


    <?xml version="1.0" encoding="utf-8"?>
    <access-policy>
    <cross-domain-access>
    <policy>
    <allow-from http-request-headers="*">
    <domain uri="*"/>
    </allow-from>
    <grant-to>
    <resource path="/" include-subpaths="true"/>
    </grant-to>
    </policy>
    </cross-domain-access>
    </access-policy>



  3. Save the clientaccesspolicy.xml file to the root of the domain where the service is hosted. If, for example, the service is hosted in http://fabrikam.com then the file must be located at http://fabrikam.com/clientaccesspolicy.xml.

  4. The valid values for the headers attribute are the wildcard (“*”) which allows all headers that have not been blacklisted and a comma separated list of allowed headers. These allowed headers may use a wildcard suffix, for example, “X-CUSTOM-*”.

  5. Alternatively, if you want to allow access form only one other domain, such as http://contoso.com, the clientaccesspolicy.xml should contain the following configuration.


    <?xml version="1.0" encoding="utf-8"?>
    <access-policy>
    <cross-domain-access>
    <policy>
    <allow-from http-request-headers="*">
    <domain uri="http://contoso.com"/>
    </allow-from>
    <grant-to>
    <resource path="/" include-subpaths="true"/>
    </grant-to>
    </policy>
    </cross-domain-access>
    </access-policy>



  6. Test that the access is enabled by invoking the service from the other domain.



To use a crossdomain.xml file to allow cross-domain access




  1. Build a service than enables access by a Silverlight client. For more information about how to do this, see How to: Build a Service for Silverlight Clients.

  2. Create a crossdomain.xml file that contains the following configuration. The file must be configured to allow access to the service from any other domain, or it is not recognized by Silverlight 2.


    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
    <allow-http-request-headers-from domain="*" headers="*"/>
    </cross-domain-policy>



  3. Save the crossdomain.xml file to the root of the domain where the service is hosted. If, for example, the service is hosted in http://fabrikam.com then the file must be located at http://fabrikam.com/crossdomain.xml.

  4. Test that the service is enabled by invoking the service from the other domain.


* This article is collected from MSDN.


Purpose of ScriptManager in asp.net

Why Use the ScriptManager Control


You must use a ScriptManager control on a page to enable the following features of ASP.NET AJAX:

  • Client-script functionality of the Microsoft AJAX Library, and any custom script that you want to send to the browser. For more information, see ASP.NET AJAX and JavaScript.

  • Partial-page rendering, which enables regions on the page to be independently refreshed without a postback. The ASP.NET AJAX UpdatePanel, UpdateProgress, and Timer controls require a ScriptManagercontrol to support partial-page rendering.

  • JavaScript proxy classes for Web services, which enable you to use client script to access Web services by exposing Web services as strongly typed objects.

  • JavaScript classes to access ASP.NET authentication and profile application services.

chart in asp.net - Setting image source property

Set ImageStorageMode to ImageStorageMode.UseHttpHandler and modify the webconfig file according to the following code.



Export to pdf using iTextSharp in asp.net

sesReportingDataSetTableAdapters.ed_GetHeadcountDataTableAdapter ta = new ed_GetHeadcountDataTableAdapter();
sesReportingDataSet.ed_GetHeadcountDataDataTable dt = ta.GetHeadcountData();

//setting table properties
PdfPTable table = new PdfPTable(6);
table.TotalWidth = 700f;
float[] widths = new float[] { .8f, 1.5f,.5f,1f,1.5f,.7f };
table.SetWidths(widths);
PdfPCell cell = new PdfPCell(new Phrase("Headcount Data driven Report"));
cell.Colspan = 6;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
cell.Border = 0;
cell.HorizontalAlignment = 1;
table.AddCell(cell);

//adding column headers
table.AddCell(new PdfPCell(new Phrase("Term Descr")));
table.AddCell(new PdfPCell(new Phrase("Career Descr")));
table.AddCell(new PdfPCell(new Phrase("RegistrationDayNbr")));
table.AddCell(new PdfPCell(new Phrase("RegistrationDate")));
table.AddCell(new PdfPCell(new Phrase("PopulationCategory")));
table.AddCell(new PdfPCell(new Phrase("Headcount")));

Paragraph p = new Paragraph();

//adding rows in the table
for (int i = 0; i < dt.Rows.Count; i++)
{
PdfPCell cell1 = new PdfPCell(new Phrase(dt.Rows[i]["termDescr"].ToString()));
table.AddCell(cell1);

PdfPCell cell2 = new PdfPCell(new Phrase(dt.Rows[i]["careerDescr"].ToString()));
table.AddCell(cell2);

PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i]["registrationDayNbr"].ToString()));
table.AddCell(cell3);

table.AddCell(Convert.ToDateTime(dt.Rows[i]["registrationDate"].ToString()).ToShortDateString());
table.AddCell(dt.Rows[i]["populationCategory"].ToString());
table.AddCell(dt.Rows[i]["headcount"].ToString());
}

this.Response.ContentType = "application/pdf";

Document doc = new Document(PageSize.LETTER);

PdfWriter writer = PdfWriter.GetInstance(doc, this.Response.OutputStream);

try
{
doc.Open();
doc.Add(table);
doc.Add((iTextSharp.text.Image.GetInstance(originalData)));
}
finally
{
doc.Close();
writer.Flush();
writer.Close();

}

Impersonation solves Access Denied Problem in asp.net

Add the following code in you code behind file where you need this.

WindowsIdentity currentUserIdentity = (WindowsIdentity)User.Identity;

WindowsImpersonationContext impersonationContext = currentUserIdentity.Impersonate();

try{

// do Something that requires saving, creating, or deleting files in the server.

}

catch(Exception ex){

if (impersonationContext != null)

{

impersonationContext.Undo();

}

}

Error Handling In Asp.Net By Overriding OnError Function

add the following code in your code behind to show the errors if there is any:
protected override void OnError(EventArgs e)
{
HttpContext context= HttpContext.Current;
Exception exception = context.Server.GetLastError();
string errorInfo =
"
Offending URL: " + ctx.Request.Url.ToString() +
"
Source: " + exception.Source.toString() +
"
Message: " + exception.Message.toString() +
"
Stack trace: " + exception.StackTrace.toString();
context.Response.Write(errorInfo);
// To let the page finish running we clear the error
context.Server.ClearError();
base.OnError(e);
}
protected override void OnError(EventArgs e) { // At this point we have information about the error HttpContext ctx = HttpContext.Current;
Exception exception = ctx.Server.GetLastError();
string errorInfo = "
Offending URL: " + ctx.Request.Url.ToString() + "
Source: " + exception.Source + "
Message: " + exception.Message + "
Stack trace: " + exception.StackTrace;
ctx.Response.Write(errorInfo);
// -------------------------------------------------- // To let the page finish running we clear the error // -------------------------------------------------- ctx.Server.ClearError();
base.OnError(e); }