Saturday, April 24, 2010

Retrive all logical drives of a machine in ASP .NET

Here is a simple code for this:
System.IO.Directory.GetLogicalDrives()

Friday, April 23, 2010

Cross-Page Posting in ASP .NET

Whenever you send a request to the server it sends request to the same page. Cross_page posting means it will send request to the another page. we can achieve. this through postback url property.

When we have to post data from one page to another in application. we used server.transfer method but in this the URL remains the same but in cross page posting there is little different there is normal post back is done but in target page we can access values of server control in the source page.This is quite simple we have to only set the PostBackUrl property of Button,LinkButton or imagebutton which specifies the target page.In target page we can access the PreviousPage property.And we have to use the @PreviousPageType directive.We can access control of PreviousPage by using the findcontrol method.When we set the PostBackURL property ASP.NET framework bind the HTML and Javascript function automatically.

Wednesday, April 21, 2010

The Basic Difference between Silverlight and WPF

Silverlight and Windows Presentation Foundation (WPF) are 2 different products from Microsoft, but has lot of overlap. Silverlight is a sub set of WPF in terms of features and functionality.

Silverlight is a Microsoft technology, competing with Adobes Flash and is meant for developing rich browser based internet applications.

Silverlight’s architecture is interesting. It includes parts of Windows Presentation Foundation (WPF), but runs on more operating systems.

WPF and Silverlight are both XAML based platforms but there are some important functionality and implementation differences between the two.

WPF is a Microsoft technology meant for developing enhanced graphics applications for desktop platform. In addition, WPF applications can be hosted on web browsers which offers rich graphics features for web applications. Web Browser Appliactions (WBA) developed on WPF technology uses XAML to host user interface for browser applications. XAML stands for eXtended Application Markup Language which is a new declarative programming model from Microsoft. XAML files are hosted as descrete files in the Web server, but are downloaded to the browsers and converted to user interface by the .NET runtime in the client browsers.

WPF runs on .NET runtime and developers can take advantage of the rich .NET Framework and WPF libraries to build really cool windows applications. WPF supports 3-D graphics, complex animations, hardware acceleration etc.

Tuesday, April 20, 2010

Adobe Creative Suite 5 Release

Last week on 12 April, 2010 new Adobe Creative Suite 5 is released.
Here is official website: Adobe Creative Suite 5


Here is a video which shows you the new features in Adobe CS5.

What's new in Visual Studio 2010 and .NET 4

Last week Microsoft had launched many of its products. I am most exciting about Visual Studio 2010. I have heard it had got many new features. Well Microsoft can do many things in 2 years. Let's see what's new in Visual Studio 2010 and how can Visual Studio 2010 is different from other versions

One of the first things to note is that Visual Studio 2010 allows you to write code against multiple versions of the .NET Framework and CLR; this means that, even if you still need to work on .NET 3.X or 2.0 code, you can upgrade from Visual Studio 2008 to Visual Studio 2010 and still be able to work on .NET 3.X applications and .NET 2.0 applications.
Some of the features in Visual Studio 2010 and .NET 4 that look really useful are:

New Microsoft Visual Studio 2010 and .NET 4.0 Launched

Microsoft had just lanched Visual Studio 2010 and .NET 4.0 last week.
Now you can do more pleasant work in ASP .NET and you don't feel like you are fighting with the system.

Here is official Microsoft Visual Studio 2010 link

Friday, April 16, 2010

List the name of all EXcel Sheets in ASP .NET with OLEDB

When manipulating data with Excel file with ADO .NET there is always limitation with the name of the sheets. Basically if you don't change the name of the sheets it comes in specific order. But when you have all the sheets with different names, you will be in trouble.


Here is a simple example that will provide you all the sheets in an Excel file. This method will return string array of sheetnames.



private String[] GetExcelSheetNames(string excelFile)
{
    OleDbConnection objConn = null;
    System.Data.DataTable dt = null;

    try
    {
        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            "Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";

        objConn = new OleDbConnection(connString);
        objConn.Open();

        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        if (dt == null)
        {
            return null;
        }

        String[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        // Add the sheet name to the string array.

        foreach (DataRow row in dt.Rows)
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        return excelSheets;
    }
    catch
    {
        return null;
    }
    finally
    {
        // Clean up.

        if (objConn != null)
        {
            objConn.Close();
            objConn.Dispose();
        }
        if (dt != null)
        {
            dt.Dispose();
        }
    }
}

Thursday, April 15, 2010

Add Meta Tags in Blogger or Wordpress or any blog easily

Meta tags are useful for the SEO purpose. You can add it easily in your website. But when you are using third party blogs like blogger, wordpress you find it difficult to add meta tags.

Besause you can only add meta tags in your main page by adding meta tags in your blog's html layout. What about adding meta to each page. It's a little bit tricky but not impossible and ya easy to..

If you have a little bit knowledge of javascript you can do it easily. Here are some steps that will help you to add meta tags in blogger in every page.

first of all you have to add meta tags in your html layout.
  • add "keyword" meta and "description" meta but leave content in description meta blank.
  • now you need to add a javascript that can replace the content of description with your desired meta content.
  • I'll give you a hint. try to replace meta tag with your page title. that will be useful.
That's all guys. Now each page of your blog will have different meta depending up on your page title.

Monday, April 5, 2010

Change the culture settings for a Calendar

Just add this little code which will change the culture of your calender

private void Page_Load(object sender, System.EventArgs e)
{
    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("ens");
    System.Threading.Thread.CurrentThread.CurrentCulture = culture; 
    System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}

Why upload fails when uploading large files in ASP .NET FileUpload Control

For security reasons, ASP.NET is limited in terms of an uploaded file size. The default maximum file size is 4 MB but this can be changed by modifying the MaxRequestLength attribute of Machine.config's element.

<httpRuntime executionTimeout="240" maxRequestLength="20480" />

Upload Multiple Files at Ones in ASP .NET

There are serveral time when you have come acrossed a situation in which you have to upload more than one files at ones. For example, attachments in mail or photos in album online.

This is possible easily. I was crawling on internet and i have found very easy and effective example of uploading more than one files, posted by Haissam Abdul Malak on CodeSnip.

He have attached all the files at ones and shown in listbox. You can modify your selection from listbox and then one click and your all the files listed in listbox will be uploaded at once.

Nice post by him. Cheersss!!!

Clear the session when the user closes a window in ASP .NET

You can write you code of Clearing the Session in the exit.aspx page and you have to request the page when user closes the window. This will clear the session.

<script type= "text/javascript">
function window.onbeforeunload()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
    try
    {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            alert("Your browser does not support AJAX!");
            return false;
        }
    }
    if(event.clientX>document.body.clientWidth&&event.clientY< 0||event.altKey)
    {
        xmlhttp.open("GET","exit.aspx",false);
        xmlhttp.send();
    }
 }
</script>

register the JavaScript function at Code-Behind in ASP .NET

There are two ways you can register javascript from codebehind.

First: You can use the RegisterScript method

this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","alert(‘hello’);",true);

Second: You can use the Literal Control

private void Button2_Click(object sender, System.EventArgs e)
{
    string str;
    str="<script language='JavaScript'>"; 
    str+="selectRange()";
  str+="<script>";
    Literal1.Text=str;
}

Retrieve server side variables using JavaScript code in ASP .NET

Sometimes you have to use the value of server side variable in javascript.
You can not directly access the server side variable in javascript.
Here is a demo how you can use server variable value in javascript.
First take a hiddenfield in aspx side.
<asp:HiddenField ID="HiddenField1" runat="server" />

You can assign the value you want to use to that hiddenfield before you use the javascript.
public partial class LoginDemo : System.Web.UI.Page
{   
    private string str="hello";
    protected void Page_Load(object sender, EventArgs e)
    {
        HiddenField1.Value=str;
    }
}

Now our hiddenfield has the value we want to use, just get that value from hiddenfield and then use it
<script type="text/JavaScript">
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
script>

Invoke a server-side function with JavaScript in ASP .NET

It is very easy once you define any event on control..
IF you want to call your private method, you can create a temporary button
and hide it with "diplay:none" and just write its click event. In that click event
you can call your private function. As easy as that.
 

ASP .NET Code: 

protected void Button1_Click(object sender, EventArgs e)
{
   FunctionName();
}
 
Javascript Code to call Button1 Event: 
 
document.getElementById("Button1").click();
It will call the Button1_Click event and click event will call your function.
 

Access a control by using JavaScript in ASP .NET

ASP Code: 
btn.Attributes.Add("onclick", "pop(this)");
 
Javascript :
 
function pop(InputBox)
{
    alert(InputBox.value);
}

Get Client Date Time in Javascript


<script type="text/javascript">
    function displayTime()
    {
        var localTime = new Date();
        var year= localTime.getYear();
        var month= localTime.getMonth() +1;
        var date = localTime.getDate();
        var hours = localTime .getHours();
        var minutes = localTime .getMinutes();
        var seconds = localTime .getSeconds();    
        var div=document.getElementById("div1");
        div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
    } 
script>

The Differenct Between "==" and Equals i.e a.Equals(b) and a == b

For value types: “==” and Equals() works same way : Compare two objects by VALUE
Example:
    int i = 5;
    int k= 5;
    Here “==” and Equals() is as:
    i == k >> True
    i.Equals(k) >> True
 For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:
    StringBuilder objSb1 = new StringBuilder("Elias");
    StringBuilder objSb2 = new StringBuilder("Elias");
    Here “==” and Equals() is as:
    objSb1 == objSb2 >> False
    objSb1.Equals(objSb2) >> True

But now look at following issue:
    string s1 = "Elias";
    string s2 = "Elias";
    Here “==” and Equals() is as:
    In above case the results will be,
    s1 == s2 >> True
    s1.Equals(s2) >> True
String is actually reference type: its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)
Now another interesting case:
    int i = 0;
    byte b = 0;
    Here “==” and Equals() is as:
    i == b >> True
    i.Equals(b) >> False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation:
For value types: use “==”
For reference types:
use Equals method.

How to avoid SQL Injection


What Is SQL Injection?

SQL injection is security vulnerability, a serious security threat that enables an attacker to execute unauthorized SQL commands by embedding them in the SQL statements by taking advantage of non-validated input in Web applications that attempt to build SQL queries dynamically.


When Does It Occur?

This typically happens in situations where your application accepts user input and builds SQL statements dynamically without a proper input validation mechanism. How? Let s assume there is a login form where the user needs to fill in the user name and the password and then click the Submit button to log in to an application. Suppose the user fills out the form as shown below:

Login: OR =

Password: OR =

The resultant query is:

SELECT userName FROM Users WHERE userName = '' OR ''='' AND Password = '' OR ''=''

This, of course, will always return true.

A smart intruder can inject SQL statements into a SQL query that is built dynamically in your application and can turn the query into the form, as shown below:

SELECT * FROM products WHERE productID = 1 or 1=1

This would always return true, irrespective of the value of the product id. Hence, your data is under threat!


How Do I Prevent It?

The following points highlight the effective measures that can be adopted to prevent SQL injection attacks:

  • Prevent unauthorized access to the database and limit the permissions that are granted to the database user account that the application uses.
  • Validate user input properly before using it, stripping off the potentially malicious characters.
  • Always use parameterized SQL queries and stored procedures rather than building the SQL statements dynamically.
  • Avoid displaying the actual database errors or messages to the end users.