Dec 17, 2010

How to change css style in ValidatorCalloutExtender.

You can design validator call out as per your site theme.

please follow when ever required.


/*call out CSS starts */

.customCalloutStyle div, .customCalloutStyle td{
border: solid 1px Black;
background-color:#8B6725;
color:White;
font-family:Tahoma, Geneva, sans-serif;
}
.customCalloutStyle .ajax__validatorcallout_popup_
table{
display: none;
border: none;
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_popup_table_row{
vertical-align: top;
height: 100%;
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_callout_cell{
width: 20px;
height: 100%;
text-align: right;
vertical-align: top;
border: none;
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_callout_table{
height: 100%;
border: none;
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_callout_table_row{
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_callout_arrow_cell
{
padding: 8px 0px 0px 0px;
text-align: right;
vertical-align: top;
font-size: 1px;
border: none;
background-color: transparent;
}
.customCalloutStyle .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv{
font-size: 1px;
position: relative;
left: 1px;
border-bottom: none;
border-right: none;
border-left: none;
width: 15px;
background-color: transparent;
padding: 0px;
}
.customCalloutStyle .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv div{
height: 1px;
overflow: hidden;
border-top: none;
border-bottom: none;
border-right: none;
padding: 0px;
margin-left: auto;
}
.customCalloutStyle .ajax__validatorcallout_error_message_cell
{
font-family: Tahoma;
font-size: 11px;
padding: 5px;
border-right: none;
border-left: none;
width: 100%;
}
.customCalloutStyle .ajax__validatorcallout_icon_cell{
width: 20px;
padding: 5px;
border-right: none;
}
.customCalloutStyle .ajax__validatorcallout_close_button_cell{
vertical-align: top;
padding: 0px;
text-align: right;
border-left: none;
}
.customCalloutStyle .ajax__validatorcallout_close_button_cell .ajax__validatorcallout_innerdiv{
border: none;
text-align: center;
width: 10px;
padding: 1px;
cursor: pointer;
}
/* call out CSS end */


//Call out HTML
RequiredFieldValidator21"
CssClass="customCalloutStyle" WarningIconImageUrl="images/001_111.png" CloseImageUrl="images/001_051.png">
ValidatorCalloutExtender>

//For IE put below

<!--[if IE]>
< link rel="stylesheet" type="text/css" href="css/ie.css" / >
< ![endif]-->

/* css for ie */

.divborder{border:1px solid #d0cece; width:763px; float:left; margin:0 0 0 2px; padding:10px 0 10px 5px;}
.customCalloutStyle .ajax__validatorcallout_close_button_cell .ajax__validatorcallout_innerdiv img{
border: none;
text-align: center;
width: 25px;
padding: 1px;
cursor: pointer;
z-index:9999;
position:absolute;
right:-13px;
background:none;
}

/* end css for ie */

Dec 16, 2010

Get timezone using asp.net

using System;
using System.Collections.ObjectModel;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblLocalTime.Text = DateTime.Now.ToString();
ReadOnlyCollection tzi;
tzi = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo timeZone in tzi)
{
ddlTimeZone.Items.Add(new ListItem(timeZone.DisplayName, timeZone.Id));
}
}
}

protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlTimeZone.SelectedIndex > 0)
{
DateTime dt = DateTime.Now;
lblTimeZone.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt,
TimeZoneInfo.Local.Id, ddlTimeZone.SelectedValue).ToString();
}
}

Dec 9, 2010

detect javascript disabled asp.net

Hello Friends,

I searched for a way to determine if the user's web browser was running JavaScript, but discovered most samples on the net only detected if the browser was capable of running JavaScript. It did nothing to detect (at least from C#) whether JavaScript was currently enabled.

I finally got some good code for detect javascript enable/disable using asp.net.

http://www.sendspace.com/file/zjbbe1

I hope you getting some good output.

Dec 8, 2010

Price format using store procedure in sql server

CREATE FUNCTION [dbo].[format_currency] (@monetary_value money ) returns varchar(20)
as
begin
declare @return_value varchar(20)
declare @is_negative bit
select @is_negative = case when @monetary_value<0 then 1 else 0 end

if @is_negative = 1
set @monetary_value = -1*@monetary_value

set @return_value = convert(varchar, isnull(@monetary_value, 0))

declare @before varchar(20), @after varchar(20)

if charindex ('.', @return_value )>0
begin
set @after= substring(@return_value, charindex ('.', @return_value ), len(@return_value))
set @before= substring(@return_value,1, charindex ('.', @return_value )-1)
end
else
begin
set @before = @return_value
set @after=''
end
-- after every third character:
declare @i int
if len(@before)>3
begin
set @i = 3
while @i>1 and @i < len(@before)
begin
set @before = substring(@before,1,len(@before)-@i) + ',' + right(@before,@i)
set @i = @i + 4
end
end
set @return_value = @before + @after

if @is_negative = 1
set @return_value = '-' + @return_value

return '$' +@return_value
end

Dec 6, 2010

Auto complete CSS in asp.net

Please find below CSS and HTML for autocompltet extender please use as needed...

also please change color as per your color scheme

For Autoextender CSS

/*auto extender starts */



.AutoCompleteExtender_
CompletionList
{
background-color : window; color : windowtext; padding : 1px; font-size: 12px; background-color:Gray;
/*creates border with autocomplete_completionListElement background-color*/
}

/*AutoComplete flyout */
.AutoCompleteExtender_CompletionListItem
{text-align : left; background-color:White;}

/* AutoComplete highlighted item */
.AutoCompleteExtender_HighlightedItem { background-color: Silver; color: windowtext; font-weight:bold; font-size: small;}




.AutoExtender
{
font-family: arial;
font-size: 12px;
font-weight: normal;
border: solid 1px #419448;
line-height: 20px;
padding: 10px;
background-color: White;
margin-left:0px;
margin:0px;

}
.AutoExtenderList
{
border-bottom: dotted 1px #419448;
cursor: pointer;
color: #144a19;
}
.AutoExtenderHighlight
{
color: White;
background-color: #714F10;
cursor: pointer;
}
#divwidth
{
width: 150px !important;
}
#divwidth div
{
width: 150px !important;
}

/*auto extender CSS ends */


//auto compltet extender HTML
CompletionSetCount="20" EnableCaching="false" FirstRowSelected="True" MinimumPrefixLength="1"
ServiceMethod="GetSuburbTest" ServicePath="WebService.asmx" TargetControlID="txtBillSuburb"
CompletionListCssClass="AutoExtender"
CompletionListItemCssClass="AutoExtenderList"
CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListElementID="divwidth">

Nov 16, 2010

Generate query from excel sheet

How to write query from excel sheet.

it is a very simple method to write query from excel sheet.
for example.

="insert into tablename(code,startdate,enddate,miniamt,amount,type,active) values('"&A1&"','2010-5-24','2011-5-23',300,30,'$',1)"

green text show you this is excel sheet column name.

Nov 12, 2010

Error: Failed to access IIS metabase

This is error occurs when you have installed IIS after installing Microsoft Visual Studio. So to overcome this error you can either run aspnet_regiis utility or re-install .net framework.

If you have installed IIS over .net framework 2.0 then you have to run this utility from following folder.

C:\Windows\Microsoft.Net\Framework\v2.0.50727\aspnet_regiis -i

In some cases this error occurs user account under which web application is running does not have proper permission on the IIS metabase. In that case run following commond.

aspnet_regiis -ga

Nov 11, 2010

Import contact from mail service using asp.net with php

First Download openinviter from http://openinviter.com/download.php and edit example.php to adjust it for your needs

Just like, below php file (example).


include('openinviter.php');
$inviter=new OpenInviter();
$oi_services=$inviter->getPlugins();
if (isset($_POST['provider_box']))
{
if (isset($oi_services['email'][$_POST['provider_box']])) $plugType='email';
elseif (isset($oi_services['social'][$_POST['provider_box']])) $plugType='social';
else $plugType='';
}
else $plugType = '';
function ers($ers)
{
if (!empty($ers))
{
//$contents="
";
foreach ($ers as $key=>$error)
$contents.="{$error}
";

//$contents.="

";

return $contents;
}
}

function oks($oks)
{
if (!empty($oks))
{
$contents="
";
foreach ($oks as $key=>$msg)
$contents.="{$msg}
";

$contents.="

";

return $contents;
}
}

if (!empty($_POST['step'])) $step=$_POST['step'];
else $step='get_contacts';

$ers=array();$oks=array();$import_ok=false;$done=false;
if ($_SERVER['REQUEST_METHOD']=='GET')
{
$plugType='email';
if ($step=='get_contacts')
{
if (empty($_GET['email_box']))
$ers['email']="Email missing !";
if (empty($_GET['password_box']))
$ers['password']="Password missing !";
if (empty($_GET['provider_box']))
$ers['provider']="Provider missing !";
if (count($ers)==0)
{
$inviter->startPlugin($_GET['provider_box']);
$internal=$inviter->getInternalError();
if ($internal)
$ers['inviter']=$internal;
elseif (!$inviter->login($_GET['email_box'],$_GET['password_box']))
{
$internal=$inviter->getInternalError();
$ers['login']=($internal?$internal:"Login failed. Please check the email and password you have provided and try again later !");
}
elseif (false===$contacts=$inviter->getMyContacts())
$ers['contacts']="Unable to get contacts !";
else
{
$import_ok=true;
$step='send_invites';
$_GET['oi_session_id']=$inviter->plugin->getSessionID();
$_GET['message_box']='';
}
}
}
elseif ($step=='send_invites')
{
if (empty($_POST['provider_box'])) $ers['provider']='Provider missing !';
else
{
$inviter->startPlugin($_POST['provider_box']);
$internal=$inviter->getInternalError();
if ($internal) $ers['internal']=$internal;
else
{
if (empty($_POST['email_box'])) $ers['inviter']='Inviter information missing !';
if (empty($_POST['oi_session_id'])) $ers['session_id']='No active session !';
if (empty($_POST['message_box'])) $ers['message_body']='Message missing !';
else $_POST['message_box']=strip_tags($_POST['message_box']);
$selected_contacts=array();$contacts=array();
$message=array('subject'=>$inviter->settings['message_subject'],'body'=>$inviter->settings['message_body'],'attachment'=>"\n\rAttached message: \n\r".$_POST['message_box']);
if ($inviter->showContacts())
{
foreach ($_POST as $key=>$val)
if (strpos($key,'check_')!==false)
$selected_contacts[$_POST['email_'.$val]]=$_POST['name_'.$val];
elseif (strpos($key,'email_')!==false)
{
$temp=explode('_',$key);$counter=$temp[1];
if (is_numeric($temp[1])) $contacts[$val]=$_POST['name_'.$temp[1]];
}
if (count($selected_contacts)==0) $ers['contacts']="You haven't selected any contacts to invite !";
}
}
}
if (count($ers)==0)
{
$sendMessage=$inviter->sendMessage($_POST['oi_session_id'],$message,$selected_contacts);
$inviter->logout();
if ($sendMessage===-1)
{
$message_footer="\r\n\r\nThis invite was sent using OpenInviter technology.";
$message_subject=$_POST['email_box'].$message['subject'];
$message_body=$message['body'].$message['attachment'].$message_footer;
$headers="From: {$_POST['email_box']}";
foreach ($selected_contacts as $email=>$name)
mail($email,$message_subject,$message_body,$headers);
$oks['mails']="Mails sent successfully";
}
elseif ($sendMessage===false)
{
$internal=$inviter->getInternalError();
$ers['internal']=($internal?$internal:"There were errors while sending your invites.
Please try again later!");

}
else $oks['internal']="Invites sent successfully!";
$done=true;
}
}
}
else
{
$_POST['email_box']='';
$_POST['password_box']='';
$_POST['provider_box']='';
}


if (!$done)
{
if ($step=='get_contacts')
{

}
else{}

}
if (!$done)
{
if ($step=='send_invites')
{
if ($inviter->showContacts())
{

if (count($contacts)==0){}
else
{
$odd=true;$counter=0;
foreach ($contacts as $email=>$name)
{
$counter++;
if ($odd) {}
$contents.= "{$email}".",";

$odd=!$odd;
}

}

}
}
}

print_r($contents);
?>


Then create one class like that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Data;

///
/// Summary description for ImportsContacts
///

public class ImportsContacts
{
public ImportsContacts()
{
//
// TODO: Add constructor logic here
//
}

public static DataTable GetDataTableFromArray(string url, string provider, string email, string pass)
{

DataTable dt = new DataTable();
///get all contact from url as array format
///split into array
object[] array = TinyEAIPostRequest(+ url +"/example.php?step=get_contacts&provider_box=?step=get_contacts&provider_box=" + provider + "&email_box=" + email + "&password_box=" + pass , string.Empty).Split(',');
dt.Columns.Add(new DataColumn("EmailID"));

for (int i = 0; i <>
{
DataRow dr = dt.NewRow();
dr["EmailID"] = array[i];
dt.Rows.Add(dr);
}
return dt;

}
public static string TinyEAIPostRequest(string strURL, string strRequest)
{

HttpWebResponse objHttpWebResponse = null;
UTF8Encoding encoding;
string strResponse = "";

HttpWebRequest objHttpWebRequest;
objHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
objHttpWebRequest.PreAuthenticate = true;

objHttpWebRequest.Method = "GET";

//Prepare the request stream
if (strRequest != null && strRequest != string.Empty)
{
encoding = new UTF8Encoding();
Stream objStream = objHttpWebRequest.GetRequestStream();
Byte[] Buffer = encoding.GetBytes(strRequest);
// Post the request
objStream.Write(Buffer, 0, Buffer.Length);
objStream.Close();
}
objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();

encoding = new UTF8Encoding();
StreamReader objStreamReader = new StreamReader(objHttpWebResponse.GetResponseStream(), encoding);
strResponse = objStreamReader.ReadToEnd();
objHttpWebResponse.Close();

objHttpWebRequest = null;

return strResponse;
}
}

Then
Call example.php file from your aspx file.
see below code how to call php file using asp.net

DataTable dt = ImportsContacts.GetDataTableFromArray(url +"/example.php", ddlmailoption.SelectedValue, txtusername.Text, txtpass.Text);//GContactsImport.GetGmailContacts(App_Name, txtusername.Text, txtpass.Text);
repgooglecontact.DataSource = dt;
repgooglecontact.DataBind();


I hope you will get good result and help to you.



Convert Array To DataTable in .NET

public static DataTable GetDataTableFromArray(object[] array)

{

DataTable dataTable = new DataTable();

dataTable.LoadDataRow(array, true);//Pass array object to LoadDataRow method

return dataTable;

}

Nov 10, 2010

Export Data into CSV file using Asp.net

How to use below code.

First create one default.aspx page and add below code into code behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] mylist = new string[5]; //Declaring the string array;

//Assigning values to each element in the array
mylist[0] = "Hello";
mylist[1] = "how";
mylist[2] = "are";
mylist[3] = "you";
mylist[4] = "?";

//Creating a new List of type
List StringtoList = new List(mylist.Length);

//AddRange is a method of List objects that enables the conversion.
//We just need to pass the reference to the array.
StringtoList.AddRange(mylist);

CSVExporter.WriteToCSV(StringtoList);
}
}


Then create one CSVExporter.cs file into app_code and add below code into class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

///
/// Summary description for CSVExporter
///

public class CSVExporter
{
public static void WriteToCSV(List personList)
{
string attachment = "attachment; filename=PersonList.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName();
foreach (String person in personList)
{
WriteUserInfo(person);
}
HttpContext.Current.Response.End();
}

private static void WriteUserInfo(String person)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(person);
//AddComma(person.Name, stringBuilder);
//AddComma(person.Family, stringBuilder);
//AddComma(person.Age.ToString(), stringBuilder);
//AddComma(string.Format("{0:C2}", person.Salary), stringBuilder);
HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private static void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private static void WriteColumnName()
{
string columnNames = "Name, Family, Age, Salary";
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}
}

Then press f5 and you will get result.

Oct 21, 2010

Redirect not www to www in asp.net website.

the following goes in the web.config file in <system.webServer> section :


<rewrite>
<rules>
<rule name="Redirect domain.com to www" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="domain.com.au" />
</conditions>
<action type="Redirect" url="http://www.domain.com.au/{R:0}" />
</rule>
</rules>
</rewrite>

Oct 8, 2010

Split function in sql server

Below function useful in sql server from split string.

create function dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (id bigint identity(1,1),items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1>

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)
insert into @temptable(Items) values(@slice)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end


Example

select * from dbo.Split('abc efg', ' ')

OutPut
---------
abc
efg

Oct 6, 2010

Redirect Permanent from a non-www to a www using ASP.NET in CMS

Please add below code into your global.aspx file

protected void Application_BeginRequest(object sender, EventArgs e)
{
string server = Request.ServerVariables["SERVER_NAME"];
if (server != "localhost")
{
if (!Request.Url.ToString().ToLower().Contains("www.") || !Request.Url.ToString().ToLower().Contains("http://"))
{
Response.Redirect("http://www." + server + Request.Path, true);
}
}

}

Sep 30, 2010

How To Add ToolTip on DropDownlist

Just add attributes into your dropdownlist

for(int i=0; i<=DDL.items.count-1; i++)
{
DDL.Item[i].Attributes.Add("Title", DDL.Item[i].Text)
}

Sep 15, 2010

Redirect Permanent from a non-www to a www using ASP.NET

Please add below code into your global.aspx file

protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;

var url = string.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.PathAndQuery);

Response.Redirect(url,true);
}

Aug 31, 2010

Problem displaying asp .net menu control in Google Chrome

Hello Friends,

I have developed one website using menu control, its working fine in all browser except Google Crome. i have facing this problem.

But i have found some good idea and work for me.

just add below script (function) into your page.

protected override void AddedControl(Control control, int index)
{
// This is necessary because Safari and Chrome browsers don't display the Menu control correctly.
// Add this to the code in your master page.
if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)
this.Page.ClientTarget = "uplevel";

base.AddedControl(control, index);
}

I hope
this answer helpful to you.

Aug 25, 2010

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same

I have facing same problem with url rewriting.
but i got solution for this problem.

Added Below code into your master page page load event.

form.Action = request.rawURL

Jun 22, 2010

Page.IsValid and Validate

ASP.net declarative programming approach, the Page.IsValid method is something easy to forget.



<
asp:TextBox ID="TextBox1" runat="server" ValidationGroup="MyValidationGroup">asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
ErrorMessage="This 
field is required!" ValidationGroup="MyValidationGroup">asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" 
ValidationGroup="MyValidationGroup" CausesValidation="true" />
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server" ValidationGroup="AnotherValidationGroup">asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2"
ErrorMessage="This 
field is required!" ValidationGroup="AnotherValidationGroup">asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="AnotherValidationGroup" 
OnClick="Button2_Click" /> 
 
protected void Button2_Click(object sender, EventArgs e) {
 
    Page.Validate("MyValidationGroup");
 
    if (!Page.IsValid) {
         return;
    }
 
    Response.Write("Button was clicked at " + DateTime.Now.ToShortTimeString());
} 

Jun 19, 2010

Don't redirect after setting a Session variable (or do it right)

A problem I see over and over again on the ASP.NET forums is the following:
In a login page, if the user and password have been validated, the page developer wants to redirect to the default page. To do this, he writes the following code:

Session["Login"] = true;
Response.Redirect("~/default.aspx");

Well, this doesn't work. Can you see why? Yes, it's because of the way Redirect and session variables work.

When you create a new session (that is, the first time you write to a Session variable), ASP.NET sets a volatile cookie on the client that contains the session token. On all subsequent requests, and as long as the server session and the client cookie have not expired, ASP.NET can look at this cookie and find the right session.
Now, what Redirect does is to send a special header to the client so that it asks the server for a different page than the one it was waiting for. Server-side, after sending this header, Redirect ends the response. This is a very violent thing to do. Response.End actually stops the execution of the page wherever it is using a ThreadAbortException. What happens really here is that the session token gets lost in the battle.

You can do to solve this problem.

you can do is use the overloaded version of Redirect:
Response.Redirect("~/default.aspx", false);
This does not abort the thread and thus conserve the session token. Actually, this overload is used internally by RedirectFromLoginPage. As a matter of facts, I would advise to always use this overloaded version over the other just to avoid the nasty effects of the exception. The non-overloaded version is actually here to stay syntactically compatible with classic ASP.

Jun 5, 2010

Enum bind into dropdownlist using HasTable

You can create a method to help you convert your enum into a hashtable and then bind it to the ddl:



protected void Page_Load(object sender, EventArgs e)
{
Hashtable ht = GetEnumForBind(typeof(Salutations));
DropDownList1.DataSource = ht;
DropDownList1.DataTextField = "value";
DropDownList1.DataValueField = "key";

DropDownList1.DataBind();

}

public Hashtable GetEnumForBind(Type enumeration)
{
string[] names = Enum.GetNames(enumeration);
Array values = Enum.GetValues(enumeration);
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
}
return ht;
}

Apr 26, 2010

url rewriting in asp.net 3.5

Refer this link for url rewriting in asp.net 3.5

http://msdn.microsoft.com/en-us/library/system.web.routing.aspx
http://www.codeproject.com/KB/aspnet/url_rewriting_routing.aspx
http://priyanonnet.com/Blogs/Posts/3418505412246356805/url-rewriting-with-asp-net-3-5-using-system-web-routing-urlroutingmodule.aspx

Apr 20, 2010

Attach Double Quotes into c#

example

label.Text = "\""+ [variable] +"\"";

Result = "abc"

What is Web Service

The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Used primarily as a means for businesses to communicate with each other and with clients, Web services allow organizations to communicate data without intimate knowledge of each other's IT systems behind the firewall.

What is the difference between Session and Cookies. Can we use both in the same webpage. when we should go for cookies.. What are the advantages and d

As far as my knowledge is concerned, cookies are stored on client side where as sessions are server variables. The storage limitations are also there (like IE restricts the size of cookie to be not more than 4096 bytes). We can store only a string value in a cookie where as objects can be stored in session variables. The client will have to accept the cookies in order to use cookies, there is no need of user's approval or confirmation to use Session variables cos they are stored on server. The other aspect of this issue is cookies can be stored as long as we want(even for life time) if the user accepts them, but with session variables we can only store something in it as long as the session is not timed out or the browser window is not closed which ever occurs first.

Coming to usage you can use both cookies and session in the same page.

We should go for cookies to store something that we want to know when the user returns to the web page in future (eg. remember me on this computer check box on login pages uses cookies to remember the user when he returns). Sessions should be used to remember something for that particular browser session (like the user name, to display on every page or where ever needed).

how to write and read cookies.

This eample code belongs to web site www.gotdotnet.com visit the following link for full example code and demo.

http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx

Protected Sub Page_Load(sender As Object, e As EventArgs)
If Request.Cookies("preferences1") = Null Then
Dim cookie As New HttpCookie("preferences1")
cookie.Values.Add("ForeColor", "black")
...
Response.AppendCookie(cookie)
End If
End Sub

Protected Function GetStyle(key As String) As String
Dim cookie As HttpCookie = Request.Cookies("preferences1")
If cookie <> Null Then
Select Case key
Case "ForeColor"
Return(cookie.Values("ForeColor"))
Case ...
End Select
End If
Return("")
End Function

How to write and read session variables.

This example belongs to www.eggheadcafe.com visit the following link for quick summary and list of FAQs on Session State.

http://www.eggheadcafe.com/articles/20021016.asp

Basic use of Session in ASP.NET (C#):

STORE:
DataSet ds = GetDataSet(whatever parameters);
Session["mydataset")=ds;

RETRIEVE:
DataSet ds = (DataSet)Session["mydataset"];

How to give Execute Permission to SQL UDF

Generally when UDF created to online(web) database
then Execute Permission is needed for each functions.

e.g.
Grant Execute on dbo.function_name to [public]