Friday, January 18, 2008

SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005

SqlCacheDependency using Asp.net 2.0 and sqlserver 2005 is a beautiful thing :) Although getting SqlCacheDependency to work with SQL Server 2000 have to add some additional step.

Now we will go with Asp.net 2.0 with sqlserver 2005

Enable Service Broker


Before SqlCacheDependency will work with SQL Server 2005, you first have to enable Service Broker, which is reponsible for the notification services that let the web cache know a change has been made to the underlying database and that the item in the cache must be removed.
ALTER DATABASE Store SET ENABLE_BROKER;
GO

--SqlCacheDependency.Start() in Global.asax


In ASP.NET, you need to run SqlCacheDependency.Start(connectionString) in the Global.asax:

Example:


void Application_Start(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
SqlDependency.Start(connectionString);
}

SqlCacheDependency in ASP.NET 2.0 Example
Now you can just create your SqlCacheDependency as normal in your ASP.NET 2.0 page. Here is a simple example:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable categories = (DataTable)Cache.Get("Categories");
if (categories == null)
{
categories = GetCategories();
Label1.Text = System.DateTime.Now.ToString();
}
GridView1.DataSource = categories.DefaultView;
GridView1.DataBind();
}
private DataTable GetCategories()
{
string connectionString = WebConfigurationManager.
ConnectionStrings["Catalog"].ConnectionString;
DataTable categories = new DataTable();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID,Code,Title
FROM dbo.Categories", connection);
SqlCacheDependency dependency =
new SqlCacheDependency(command);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataSet dataset = new DataSet();
adapter.Fill(dataset);
categories = dataset.Tables[0];
Cache.Insert("Categories", categories, dependency);
}
return categories;
}
}

Wednesday, January 16, 2008

Scrapping using C#.Net

using System.net;
using System.io;

WebRequest request = WebRequest.Create("http://localhost:4733/strings.aspx");
WebResponse response = request.GetResponse();
Stream s=response.GetResponseStream();
StreamReader sr = new StreamReader(s);
string line = sr.ReadLine();
while ((line=sr.ReadLine()) !=null)
{
Response.Write(line);
}

Datatable Load option in Dotnet Framework 2.0

Definition

Using datatable.load you can load the sqldatareader value directly

Example


DataTable dt = new DataTable();
string connectionstring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection myconn = new SqlConnection(connectionstring);
SqlCommand mycomm = new SqlCommand("select * from FA_contactdetails", myconn);
myconn.Open();
SqlDataReader sqldataread = mycomm.ExecuteReader();
dt.Load(sqldataread);////
myconn.Close();
dggrid.DataSource = dt;
dggrid.DataBind();

Thursday, January 10, 2008

.NET BEST PRACTICES

.NET BEST PRACTICES
# Use Master Pages for common content across pages.
# Use the “@” prefix for string literals instead of using escaped strings.
# Avoid Empty Catch-blocks# In the .NET framework 2.0: use the New AppendDataBoundItems property in ListControls.
# Close DataReaders and Connections as soon as possible.
# All important graphics should have tool tip and alternate text.
# Use Typed Datasets wherever possible and required.
# Use Validators / Validator Groups for validation.
# Include exception handling in the Application_Error event of global.asax file for unhandled exceptions – implement a Global.asax error handler.
# Choose the most appropriate data type. It is advisable to stop using the “image” data type in SQL Server for any fresh development. Microsoft is planning to phase it out in future versions of SQL Server. You should use the “varbinary(max)” data type instead.

.NET Security Tips

.NET Security Tips
# Keep “Persist Security Info” as false in the connection string.
# Remove the authentication cookie in Session_End event or application specific logout event.
# Security decisions should not rely only on client-side validations – they should be verified on the server side too!
# Hashed password format should be specified in provider configuration.
# The website should be partitioned into public access areas and restricted areas that require authentication access. Navigation between these areas should not flow sensitive credentials information.
# Protect your website against Cross-Site Scripting or XSS attacks
# Dynamic queries that accept user input should be used only if stored procedures cannot be used. Even these queries should use parameters.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.
# Set mode attribute in customErrors to On to prevent displaying detailed error messages to the caller.
# Ensure that utilizing the “View source” option does not divulge any sensitive information.

Performance Boosting .NET coding tips

Performance Boosting .NET coding tips
# Instantiate Objects only if really needed { will NOT use up memory unnecessarily }
# Prefer using String.Empty instead of "" for string initialisation
# Prefer using StringBuilder for dynamic creation of Strings.
# Avoid String datatype while using Switch Case programming-construct
# Use Server.Transfer() instead of Response.Redirect() method.
# Avoid use of Page.DataBind() method
# Define the four most frequently used local variables as the first four variables.
# Even inside vb.net OR c# code, Avoid using the “select * from table” syntax.
# Use proper column case in queries.dr[“ProductName”] vs dr[“PRODUCTNAME”]
# Use Page.IsPostBack to minimize redundant processing in page load.
# Avoid server round trips (by using client scripts, validator controls, html controls, caching techniques (for pages, user controls and objects)).
# Disable view state on a control-level / page-level if you do not need it.DataGrid with ViewState disabled is 66% faster than DataGrid with ViewState enabled.
# Minimize the number of objects you store in view state.
# Use a DataReader for fast and efficient data binding.
# Prefer to Use try/finally on disposable resources.
# Minimize calls to DataBinder.Eval

Moving Listitem from left Listbox to right Listbox

protected void btnmoveright_Click(object sender, EventArgs e)
{
ArrayList arrfirst = new ArrayList();
foreach (ListItem lstfirstitem in lstfirst.Items)
{

if (lstfirstitem.Selected == true)
{
arrfirst.Add(lstfirstitem);
}

}
for (int i = 0; i < arrfirst.Count; i++)
{
ListItem tst = (ListItem)arrfirst[i];
if (lstsecond.Items.Contains(tst) == false)
{ lstsecond.Items.Add(tst);
lstfirst.Items.Remove(tst);
}
}
}


protected void btnmoveleft_Click(object sender, EventArgs e)
{
lstfirst.SelectionMode = ListSelectionMode.Multiple;
lstfirst.Attributes.Add("SelectionMode", "Multiple");
ArrayList arrsecond= new ArrayList();
foreach (ListItem lstseconditem in lstsecond.Items)
{ if (lstseconditem.Selected == true)
{ arrsecond.Add(lstseconditem); }
} for (int i = 0; i < arrsecond.Count; i++)
{ ListItem tst = (ListItem)arrsecond[i];
if (lstfirst.Items.Contains(tst) == false)
{ lstfirst.Items.Add(tst);
lstsecond.Items.Remove(tst);
}
}
lstfirst.SelectedItem.Selected = false;
lstfirst.SelectionMode = ListSelectionMode.Single;
}

Maxlength checking in Textarea Using Javascript

function maxcheck()

{
var maxval=1000;
var maxtxtlength=window.document.myform.Description.value.length;
if(parseInt(maxtxtlength)>parseInt(maxval))
{
alert("This Description field accept only 1000 characters");
window.document.myform.Description.innerText=window.document.myform.Description.value.substring(0,1000);
return false;
}
}

Friday, January 4, 2008

Defend Your Code with Top Ten Security Tips Every Developer Must Know

http://msdn.microsoft.com/msdnmag/issues/02/09/securitytips/default.aspx

Web Parts in ASP.NET

http://www.beansoftware.com/ASP.NET-Tutorials/Web-Parts.aspx

Encrypting Connection Strings in web.config file

http://www.beansoftware.com/ASP.NET-Tutorials/Encrypting-Connection-String.aspx

What is the purpose of AppendDataBoundItems for dropdown


AppendDataBoundItems

Definition:

Using this you can append dynamically.

Example

string[] sdss ={ "test", "test1" };
this.myDropDown.AppendDataBoundItems = true;
this.myDropDown.Items.Add(new ListItem("Bitte wählen...", ""));
this.myDropDown.DataSource = sdss;
this.myDropDown.DataBind();

output

Bitte wählen
test
test1


IDictionary

Hashtable ht = new Hashtable();
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionary idic = (IDictionary)ht;
foreach (DictionaryEntry de in idic)
{
Response.Write(de.Key);
Response.Write(de.Value);
Response.Write("
");
}

out put

2bala1
1bala

IDictionaryEnumerator

Hashtable ht = new Hashtable();
ht.Add(1, "bala");
ht.Add(2, "bala1");
IDictionaryEnumerator ss = ht.GetEnumerator();
while (ss.MoveNext())
{
Response.Write(ss.Key);
Response.Write(" "+ss.Value);
Response.Write("
");
}

output:
2 bala1
1 bala

Inbuilt Interface Using Dotnet

1) IEnumerator


Definition:

Using this interface you can read the array,string, Performance is good.


Example:1

string[] sdss ={ "test", "test1" };

IEnumerator enumerator = sdss.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");
}

output

test
test1

Example:2

string s="dd";
IEnumerator enumerator = s.GetEnumerator();
while (enumerator.MoveNext())
{
Response.Write(enumerator.Current.ToString() +"
");

}

output

d
d

Thursday, January 3, 2008

Retrieving Selected Text Using Javascript

function copy()

{

var selectedText = document.selection;

if (selectedText.type == 'Text')

{

var newRange = selectedText.createRange();

form1.txtTest.focus();alert(newRange.text)}else{alert('Please Select The Text');

}}

Tuesday, January 1, 2008

Interop Services

Definition

>>handling unmanaged code we have to use Interop services.

The Microsoft .NET Framework promotes interaction with COM components,
COM+ services, external type libraries, and many operating system services. Data types, method signatures, and error-handling mechanisms vary between managed and unmanaged object models. To simplify interoperation between .NET Framework components and unmanaged code and to ease the migration path, the common language runtime conceals from both clients and servers the differences in these object models.
Code executing under the control of the runtime is called managed code. Conversely, code that runs outside the runtime is called unmanaged code.

Example of Unmanaged code

COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.