Monday, September 27, 2010
how to get the returned value from stored procedure in asp.net
{
SqlConnection connection = new SqlConnection(connectionString);
// Command - specify as StoredProcedure
SqlCommand command = new SqlCommand(storedProcedureName, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@orgID", System.Data.SqlDbType.NVarChar).Value = paramValue;
// Return value as parameter
SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);
// Execute the stored procedure
connection.Open();
command.ExecuteNonQuery();
connection.Close();
return Convert.ToInt32(returnValue.Value);
}
Wednesday, August 11, 2010
Counting Number of Files in a directory - UNIX/ Linux
Command: ls | wc -l
Tuesday, August 10, 2010
jQuery UI CSS List in Google CDN
- UI Lightness: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css
- UI Darkness: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-darkness/jquery-ui.css
- Smoothness: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css
- Start: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/start/jquery-ui.css
- Redmond: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css
- Sunny: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/sunny/jquery-ui.css
- Overcast: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/overcast/jquery-ui.css
- Le Frog: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/le-frog/jquery-ui.css
- Flick: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css
- Pepper Grinder: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/pepper-grinder/jquery-ui.css
- Eggplant: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/eggplant/jquery-ui.css
- Dark Hive: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/dark-hive/jquery-ui.css
- Cupertino: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/cupertino/jquery-ui.css
- South Street: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/south-street/jquery-ui.css
- Blitzer: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/blitzer/jquery-ui.css
- Humanity: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/humanity/jquery-ui.css
- Hot Sneaks: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/hot-sneaks/jquery-ui.css
- Excite Bike: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/excite-bike/jquery-ui.css
- Vader: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/vader/jquery-ui.css
- Dot Luv: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/dot-luv-grinder/jquery-ui.css
- Mint Choc: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/mint-choc/jquery-ui.css
- Black Tie: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/black-tie/jquery-ui.css
- Trontasic: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/trontastic/jquery-ui.css
- Swanky Purse: http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/swanky-purse/jquery-ui.css
Sunday, July 18, 2010
Finding Full Size of a Directory in Human readable format - UNIX/LINUX
here, -s, --summarize => display only the total of the specified directory
Monday, July 12, 2010
Running a background process - Using the nohup command in UNIX
nohup command &
For example:
If you want to run a java program as a background process you can do the following:
nohup java -cp ./wikify/bin:./wikify/mysql-connector-java-3.1.13-bin.jar:./wikify/trove.jar:./wikify/weka.jar:/usr/share/tomcat6/lib/servlet-api.jar:./wikify/src/org/wikipedia/miner/service/ org.wikipedia.miner.service.WikipediaMiner &
You r program will be running in the background even if you logout from your terminal. Use Kill command to terminate the nohup command
Wednesday, June 16, 2010
Thursday, June 3, 2010
A generic error occurred in GDI+.
Got the following error when one of client was trying to upload a picture in his website after publishing the website in godaddy.com. It was a easy fix. Just give the “write” permission to the “image” directory of your solution folder in the godaddy domain where all the files resides. More specifically,
[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630
System.Drawing.Image.Save(String filename, ImageFormat format) +69
iTalk.Controllers.AccountController.ChangePicture() in AccountController.cs:306
lambda_method(ExecutionScope , ControllerBase , Object[] ) +39
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.<InvokeActionMethodWithFilters>b__7() +53
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +258
System.Web.Mvc.<>c__DisplayClassc.<InvokeActionMethodWithFilters>b__9() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +193
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +382
System.Web.Mvc.Controller.ExecuteCore() +123
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +23
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +144
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +54
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Solution: Login to godaddy.com –>on the top, Content tab –> Click File manager –> check the folder which contains the images –> Click permission tab on the top – uncheck the already checked items –> check the read and write from the check box list –> Click ok at the bottom and you are done!
Thursday, May 27, 2010
Open Source HTML Editor
Wednesday, May 26, 2010
jQuery listnav plugin - javascript list navigation control
jQuery listnav plugin - javascript list navigation control
Tuesday, May 25, 2010
Stop Words Removal using Windows 7 Training Kits
1. Status bar in the icon during processing
2. Thumbnail preview
2. Jumplist customization
Please email me at sunnyhasan at gmail dot com for the source code and more details.
Fix: "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed"
Step 1: Enable User Instances for SQL Server installation.
a. Go to Query Window in SQL Server Management Studio and type this:
exec sp_configure 'user instances enabled', 1.
b. Then type this: Reconfigure and run.
c. Restart the SQL Server.
Step 2. Deleting old old User Instances.
a. Go to the following path in your local machine and DELETE all files and folder under that folder:
C:\Documents and Settings\YOUR_USERNAME\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS
Here, YOUR_USERNAME indicates the current username in your computer.
FIXing : "MSDTC on server 'servername' is unavailable"
MSDTC service needs to be turned on in the server where the trigger resides. You can start this service in 2 ways:
1. Start the service from "Run": press ( Windows key+ R )and then type "net start msdtc" and press enter.
2. Go to START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called "Distributed Transaction Coordinator" and RIGHT CLICK on it and select Start.
Solving the issue of running MSDTC where the hosting service doesn't support it:
Godaddy.com doesn't support MSDTC in their shared hosting. But, if you want to deploy you web site to their server and you don't have the permission to start that service, the work around is using ";Enlist=false" at the end of your connectionString in webConfig file. For Example:
connectionString="Data Source=sunnyhasan.resource.com;Initial Catalog=sunnyhasan;User ID=sunnyhasan;Password=scars123;Enlist=false"
Saturday, May 8, 2010
url decode in MySQL
--------------------------------------Function Starts--------------------------------
DELIMITER $$
DROP FUNCTION IF EXISTS `typing_wikipedia`.`url_decode`$$
CREATE FUNCTION `typing_wikipedia`.`url_decode`(original_text text) RETURNS text CHARSET latin1
BEGIN
declare new_text text default null;
declare pointer int default 1;
set new_text = replace(original_text,'+',' ');
while (LOCATE("%",new_text,pointer) <> 0 )&& (pointer < length(new_text)) do
set pointer = LOCATE("%",new_text,pointer);
set new_text = concat(left(new_text,pointer-1),char(conv(mid(new_text,pointer+1,2),16,10)),right(new_text,length(new_text)-(pointer+2)));
set pointer = pointer + 1;
end while;
return new_text;
END;
$$
DELIMITER ;
------------------------------------Function ends-------------------------------
Reference: MySQL Forge
Tuesday, May 4, 2010
How to use autocomplete extender in AJAX toolkit
Drag and drop a textbox in asp.net page and then wired your textbox with a autocomplete extender like below:
<div id="siteSearch">
<br />
<asp:TextBox ID="searchAutoCompleteTextBox" runat="server" CssClass="textBoxStyle"></asp:TextBox>
<div id="divwidth">
</div>
<ajaxControlToolkit:AutoCompleteExtender ID="searchAutoCompleteTextBox_AutoCompleteExtender"
runat="server" DelimiterCharacters="" Enabled="True" ServicePath="~/assets/services/autoComplete.asmx"
ServiceMethod="GetCompletionList" MinimumPrefixLength="1" EnableCaching="true"
TargetControlID="searchAutoCompleteTextBox" CompletionListCssClass="AutoExtender"
CompletionListItemCssClass="AutoExtenderList" CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListElementID="divwidth">
</ajaxControlToolkit:AutoCompleteExtender>
</div>
Then add a web service and with the following method. Please note that the return type, params should be same as the following otherwise the autocomplete will nto work. You can only change the name of the method name:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
/// <summary>
/// Summary description for autoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class autoComplete : System.Web.Services.WebService {
public autoComplete () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionList(string prefixText, int count)
{
string[] suggestions = new string[10];
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("~/App_Data/AcademicUnitHierarchy.xml"));
DataView collegeDV = ds.Tables[0].DefaultView;
collegeDV.RowFilter = "h2=0 and acad_status=0";
for (int i = 0; i < 10; i++)
{
suggestions[i] = collegeDV[i]["name"].ToString();
}
return suggestions;
}
}
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
Friday, April 23, 2010
Register the 2007 Office system file format MIME types on servers
Register the 2007 Office system file format MIME types on servers
Monday, April 19, 2010
Tuesday, April 13, 2010
read, write, save and update XML in Silverlight
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
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
- 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 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.
- A 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
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_PATH | Retrieves the physical path corresponding to the metabase path. IIS converts the APPL_MD_PATH to the physical (directory) path to return this value. |
AUTH_PASSWORD | The value entered in the client's authentication dialog. This variable is available only if Basic authentication is used. |
AUTH_TYPE | The authentication method that the server uses to validate users when they attempt to access a protected script. |
AUTH_USER | The 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_COOKIE | Unique ID for client certificate, returned as a string. Can be used as a signature for the whole client certificate. |
CERT_FLAGS | bit0 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_ISSUER | Issuer field of the client certificate (O=MS, OU=IAS, CN=user name, C=USA). |
CERT_KEYSIZE | Number of bits in Secure Sockets Layer connection key size. For example, 128. |
CERT_SECRETKEYSIZE | Number of bits in server certificate private key. For example, 1024. |
CERT_SERIALNUMBER | Serial number field of the client certificate. |
CERT_SERVER_ISSUER | Issuer field of the server certificate. |
CERT_SERVER_SUBJECT | Subject field of the server certificate. |
CERT_SUBJECT | Subject field of the client certificate. |
CONTENT_LENGTH | The length of the content as given by the client. |
CONTENT_TYPE | The data type of the content. Used with queries that have attached information, such as the HTTP queries GET, POST, and PUT. |
GATEWAY_INTERFACE | The 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_ACCEPT | Returns the value of the Accept header. |
HTTP_ACCEPT_LANGUAGE | Returns a string describing the language to use for displaying content. |
HTTP_COOKIE | Returns the cookie string that was included with the request. |
HTTP_HOST | Returns 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_REFERER | Returns 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_AGENT | Returns a string describing the browser that sent the request. |
HTTPS | Returns ON if the request came in through secure channel (SSL) or it returns OFF if the request is for a non-secure channel. |
HTTPS_KEYSIZE | Number of bits in Secure Sockets Layer connection key size. For example, 128. |
HTTPS_SECRETKEYSIZE | Number of bits in server certificate private key. For example, 1024. |
HTTPS_SERVER_ISSUER | Issuer field of the server certificate. |
HTTPS_SERVER_SUBJECT | Subject field of the server certificate. |
INSTANCE_ID | The 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_PATH | The metabase path for the instance of IIS that responds to the request. |
LOCAL_ADDR | Returns 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_USER | The 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_INFO | Extra 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_TRANSLATED | A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping. |
QUERY_STRING | Query information stored in the string following the question mark (?) in the HTTP request. |
REMOTE_ADDR | The IP address of the remote host making the request. |
REMOTE_HOST | The 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_USER | The 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_METHOD | The method used to make the request. For HTTP, this is GET, HEAD, POST, and so on. |
SCRIPT_NAME | A virtual path to the script being executed. This is used for self-referencing URLs. |
SERVER_NAME | The server's host name, DNS alias, or IP address as it would appear in self-referencing URLs. |
SERVER_PORT | The port number to which the request was sent. |
SERVER_PORT_SECURE | A 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_PROTOCOL | The name and revision of the request information protocol. The format is protocol/revision. |
SERVER_SOFTWARE | The name and version of the server software that answers the request and runs the gateway. The format is name/version. |
URL | Gives the base portion of the URL. |
- Reference: Fernando Finelli
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
- 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.
- 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> - 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.
- 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-*”.
- 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> - 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
- 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.
- 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> - 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.
- 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
Export to pdf using iTextSharp in asp.net
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
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
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); }