Wednesday, June 25, 2008

Speed up your websites Loading speed

Wanna Speed up your website Follow these small steps to improve websites performance .

  • Compress the webpage - If the webpage is big in size then compress the webpage to make it load faster and reduce the bandwith required . G-zip,Deflate are supported by most of the browsers now .
  • Using cache extensively -Cache your webpage make it vary by parameters i.e caching the page and varying it accordingly to changing parameteres .
  • Make javascript and Css external -Put stylesheets to the top and scripts at the bottom .
  • Minimize HTTP request -Most of the time is spend in downloading the components i.e images, stylesheet, script , flash etc ,so minimize such components .
  • Use CDN Content delivery network -If your website is a global website then you can have a network of web servers around the world to improve the loading of website around the world .

Friday, June 20, 2008

Hacking Websites with Sql Injection attacks

Making a website ,using SQL server and never heard of SQL injection attacks .....
Then please read this post before you go ahead with launching your website.

A Small example
Suppose this is your sql statement for your Login control
select * from profiletable where username='Admin' and password ='P@ssword123'

Now when a user enters Admin'-- at the textbox
Then the sql statement becomes
select * from profiletable where username='Admin'--' and password ='P@ssword123'

In Sql -- is used as comment,Hence the SQL statement which is executed is ....
select * from profiletable where username ='Admin'
-- comments the sql query after 'Admin' and hence the user gets the access to the details of the user without the need of the password .

This was a very simple example of SQL injection attacks ,Lets see how a user finds out how the details of program .....

Obtaining Information about database using Error Messages

A User can get information about your database using Error messages .
The Attacker will purposefully enter such entries in the Textbox which might give an error .
For Example:
Line 26:         com.Parameters.Add("@user",SqlDbType.DateTime).Value=TextBox1.Text;
Line 27: //com.Parameters.AddWithValue("user", TextBox1.Text);
Line 28: SqlDataReader dr = com.ExecuteReader();
Line 29: if (dr.Read())

This Error message will give a lot of information about your program and database.....

Advanced SQL injection attacks include use of Extended,Custom Stored Procedures and many new innovative methods .....

Hence follow these set of guidelines when making a website :

*Use of Parametric SQL Queries and if possible use of stored procedures - (Parametric queries validate the input entered and stored procedures donot show the query details on errors )

*Use of Linq if you are building application on .Net 3.5 framework .Linq is safer and faster than SQL .

*Use of TRY,CATCH blocks with sql query and defining error pages .

*Making your application an N-layer application having clearly defined rules in buisness layer to know who all can access the Data Layer.

*Rejecting Bad input ,Accepting Good input : Validation
  • Escape single quotes
function escape( input )
input = replace(input, " ' ", " ' ")
escape = input
end function
  • Reject known bad input
function validate_string( input )
known_bad = array( "select", "insert", "update", "delete", "drop", "--", "'" )
validate_string = true
for i = lbound( known_bad ) to ubound( known_bad )
if ( instr( 1, input, known_bad(i), vbtextcompare ) <> 0 ) then
validate_string = false
exit function
end if
next
end function
  • Allow only good input
function validatepassword( input )
good_password_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
validatepassword = true
for i = 1 to len( input )
c = mid( input, i, 1 )
if ( InStr( good_password_chars, c ) = 0 ) then
validatepassword = false
exit function
end if
next
end function

*SQL Lockdown
  • Determine methods of connection to the server-Verify that only the network libraries you're using are enabled, using the 'Network utility'
  • Verify which accounts exist-Remove unneccessary accounts,Ensure that all accounts have strong password ,Run a password auditing script to against the server on regular basis .
  • Verify which objects exist-Remove the extended stored procedures which are not needed .
There are Tools to determine this which you can find at www.Sqlsecurity.com.

So now rethink about your application and design it using these guidelines .....


Tuesday, June 10, 2008

Dynamically add Controls to webpage

It is important some times to dynamically generate controls for your application .
To do this use the following code given below:

Label l1=new Label();//creating an instance of the control

l1.Text="Code Snippet ";//Defining its properties like text ,width,height ,style etc

l1.Width="100px";

this.Controls.Add(l1);//Adding it to your page or form

This is a very simple code but is as useful .

Monday, June 9, 2008

A Simple Web Service

Today ,we will learn how to create a web service . A web service is supposedly much safer and faster and hence very important to any website project .

*To create a web service go to add a new item .
*Add a Web service (.asmx) file to your solution .
*In this File there is a default web method called "Hello World" which returns hello world .
*You can write your methods out here and declare them as a web methods .
*If you dont want to write all the coding on the .asmx page you can write the code in a class file and call those methods in a webmethod

*Now to test the service debug this application and in the window u will see the name of the methods that you have defined .
*Click on the method you want to test ,this will open a window which will have the consist of the specific webmethod and an "Invoke" button .
*Press the Invoke button and You will be able to see the results in an XML file .

*Now to add this service to Your web site application , follow these steps :
1.Add a web reference to your project this will give the below options
  • Web services in the solution
  • Web services on the local machine
  • Browse UDDI Servers on the local network
2.You can select the first option if your webservice is in the same solution else choose the second option .
3. Change the namespace for your service as per your requirements ,by default it is given a name localhost.

4.Now in your webpage (eg:Default.aspx) write the following code
localhost.WebService ws = new localhost.WebService();
Label1.Text= ws.HelloWorld();//I have included a Label also to show the results

That is all you have to do to include a webservice to your website .

Saturday, June 7, 2008

Dynamically adding Meta-Tags

According to SEO's Meta -tags are dead .
Its official now that Search engines now give their own tags to every page instead of reading meta tags on every page .
But still if you want to add meta tags dynamically to your page then here is the code .

At the page_load event write the following code
protected void Page_Load(object sender, EventArgs e)
{
HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keyword";
keywords.Content =" metatag";
Header.Controls.Add(keywords);
}
Well the above code is quiet easy and can be easily understood .

Thursday, June 5, 2008

URL Rewriting

It has become important for websites to provide User friendly URL's to their users and this can be done effectively using Visual web developer.
Today I will tell you about one of the ways of doing it .

We will start a new website and add an App_Code folder to your solution .
App_Code folder is a special folder which contains the code which is executed at the start of our application .
Add a class file to the App_Code folder,I have named it Urlrewitw.cs
Write the following code in this file :

public class urlrewrite:IHttpModule//This class implements IHttpModule which generates two functions called Dispose and Init

{
#region IHttpModule Members

public void Dispose()//the code in this function executes whenever the application disposes
{
// We dont need to write any code in this function
}

public void Init(HttpApplication context)//this code is executed at the start of application
{
context.BeginRequest += new EventHandler(context_BeginRequest);
//We add an event handler which calls the begin_request function at the start of application
}

void context_BeginRequest(object sender, EventArgs e)//Write the url rewriting code here
{
HttpApplication app;
app = (HttpApplication)sender;
if (app.Request.RawUrl.Contains("Default4.aspx"))
{
app.Context.RewritePath("Default3.aspx", "", "itemid=2" + "&name=anand");
//if Default4.aspx is requested then call the page Default3.aspx with two QueryString Parameters itemid and name: Default3.aspx?itemid=2&name=anand
}

}

#endregion
}

Last Thing to be done is to Tweak the Web.config file
In System.Web add this code-snippet
(httpModules)
(add name="urlrewrite" type="urlrewrite"/)
(/httpModules)
Use < > brackets instead of ( )

Isnt it easy ,so go and try this code in your application.....

Monday, June 2, 2008

Linq to sql Tutorial


Language Integrated Query LINQ is a new query language being Introduced in ASP.NET 3.0 .
This language is based on ORM (object relational mapping) to make database queries much faster and safer .
Lets not get into details and get started with linq .........
We will follow a set of steps in implementing Linq to our project .

STEP:1 Open a visual studio project and connect to the required Sql database using the server explorer.

STEP:2 Add an new linq to sql file to your project.
This file has a .dbml extension ,simply drag and drop your database tables to this file.

STEP:3 Add namespace "using System.Data.Linq;" in your .aspx file .

STEP:4 Now start writing the queries to select,insert,update,delete data from the database table.
As you can see that my table contains four fields username,name,blogname and imageurl, the name of my database table is "linqprofile"and that of my .dbml file is "linqtry"
Select Query :
protected void Page_Load(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext();//Create an instance of your linq datacontext
var us = db.linqprofiles.Where(u => u.username == "Learnlinq").Select(u=> u.name);
//var is an implicitly typed variable which has no datatype you can use string ,int etc if you know the datatype
Response.Write(us);
} //select name from the "linqprofiles" table where username is "Learnlinq"

Insert Query :
protected void Button1_Click(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext();
linqprofile lp = new linqprofile { username = "newuser", name ="seconduser" ,blogname="insert",imageurl="C:\\blog.bmp" };

db.linqprofiles.InsertOnSubmit(lp);
db.SubmitChanges();

}

Delete Query :
protected void Button2_Click(object sender, EventArgs e)
{
linqtryDataContext db = new linqtryDataContext(); linqprofile lp = db.linqprofiles.First(p => p.username == "Learnlinq");
db.linqprofiles.DeleteOnSubmit(lp);
db.SubmitChanges();
}
//Delete the first record in "linqprofile" where username is "Learnlinq"

Update Query:
protected void Button3_Click(object sender, EventArgs e)
{

linqtryDataContext db = new linqtryDataContext(); linqprofile lp = db.linqprofiles.First(p => p.username == "Learnlinq");
lp.name = "anand";
db.SubmitChanges();

} //Update the first record in "linqprofile" table where username is "learnlinq"
//Update the name field to "anand"

I hope you now know how to update,insert,delete and select from the sql database .
Linq is even more intresting and we will talk more about linq in my later blogposts.

Sunday, June 1, 2008

Customizing Fckeditor


Ah!!! Fck-editor again .....,I have already made two BlogEntries over Integrating Fck-editor and enabling its connector in Visual Studio Enviornment .
well todays blogpost is about customizing its Toolbar set and changing its skins........
So gets Started......
Most of the functionality of any application can be configured at its config file and for this editor too will tweak the same file( fckconfig.js).
For changing the skins open the fckconfig.js file and look for
FCKConfig.ToolbarSets["Default"]=[
['Source','Save','Preview'],
['Cut','Copy','Paste','PasteText','PasteWord'],
'/',
['Bold','Italic','Underline','StrikeThrough','Subscript','Superscript'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link'],
['Image','Flash','Table','Smiley','SpecialChar'],
'/',
['FontFormat','FontName','FontSize'],
['TextColor','BGColor'] // No comma for the last row.
] ;
Out here you can Delete the controls which you dont require ,as you can see that I hav already chipped of a few controls , So its easy isnt it .........
Now about changing skins ,look for
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ;(In fckconfig.js)
Just look for the avialable skins in your fckconfig skins folder and change the above "default" with the name of the skin which best suits your application . FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/silver/' ;
(I have changed the skin to silver and it looks great)

Fckeditor is a great application and Integrating it to your application makes it even better.....


Thursday, May 29, 2008

Using List View Control

If you ever wished that the Datalist control of Visual Studio 2005 could have paging enabled with it ,then it has come true but in the form of a new control named ListView.
ListView Control of Visual Studio 2008 is Quiet interesting ,Lets see how can we use this control in our project .

Now fire up Visual Studio 2008 and open a new website project .
Suppose that you have a SQL database table with three columns as First name ,Last name ,email .
Drag and drop an Sqldatasource control from the toolbox and configure it to your SQL database table .
Now drag and drop a ListView Control from the Toolbox and declare its DatasourceID to be the above datasource .
A listview control has a list of 11 Templates for configuring the Look and Feel of the listview control .But the most important part of the control is that it requires a Placeholder whose ID needs to be exactly the same as "itemplaceholder" like the code below.........

(asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1")
(LayoutTemplate)
(asp:PlaceHolder ID="itemplaceholder" runat="server")(/asp:PlaceHolder)
(/LayoutTemplate)
(use the <> brackets instead of ( ) in the code )

Now add an item template to show your data like the code below ..........

(ItemTemplate )
(asp:Label ID="label1" runat="server" Text='(%#Eval("Firstname") %)'/)(br /)
(asp:Label ID="label2" runat="server" Text='(%#Eval("Lastname") %)'/)(br /)
(asp:Label ID="label3" runat="server" Text='(%#Eval("email") %)'/)(br /)
(/ItemTemplate)

You can the use other templates to make it look better.......
Now about adding the paging element to the listview control .
Drag and drop the paging control from the toolbox and set its PageControlID to the above Listview control as below ........
(asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1"
PageSize="5")
(Fields)
(asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
ShowLastPageButton="True" /)
(/Fields)
(/asp:DataPager)
Using this control you can set the paging style and also the number of data to be shown on the page .
The Listview control has some more intresting templates like the GroupTemplate which can be used to group data elements together but we may talk about that later in some other Blogpost.
For now you play with this new control of visual studio 2008.

Uploading Images using Fckeditor

In my previous Blog ,I did write about integrating Fckeditor in Visual studio Projects .
Today ,I will guide you about enabling the Image,Flash file upload in fckeditor.
Due to security reasons this feature is disabled by default .
Once you get the Editor working follow these steps to get upload working .....

1.Create a Folder named "userfiles" in the root directory and add two subfolders to it named image and flash .

2.Go to the web.config file ,In the appSettings write the following code .....

(appSettings)
( add key="FCKeditor:UserFilesPath" value="~/userfiles/"/)
(/appSettings)

3. Go to fckeditor/fckconfig.js and search for
var _FileBrowserLanguage and var _QuickUploadExtension
change the file type to 'aspx' like the below code

var _FileBrowserLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'aspx' ; // asp | aspx | cfm | lasso | perl | php | py

4. Now move to fckeditor/editor/filemanager/connectors/aspx/config.ascx
find the private bool Check_Authenticate () function
Here you need to tweak the code according to your needs .
If you want only authenticated users to access your browserfiles then add this code
return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//else you can make use of your own custom made function .

else an easy but a bad option is
return true;//not suggested

5. In the same file you need to define the path of your userfile folder .


// URL path to user files.
UserFilesPath = "/userfiles/";
//Absolute path to userfiles
UserFilesAbsolutePath = "C:\\Users\\Documents\\Visual Studio 2008\\WebSites\\ Website\\userfiles\\";

6. The Final Step ,pray to god that it works at last

It took me a week to figure out the way to integrate it and make it work finally ,I hope this Blog will make it a lot more simpler for you now .
I have used version 2.6 of Fckeditor , Visual studio 2008 and .net fx 3.5 for my project.
I hope it works the same with visual studio 2005 and .net fx 2.0.

If you still face any problem with it ,do mail me your problem and I will try to Fix it .


Tuesday, May 27, 2008

Uploading File using C#


You may have seen many complex programs regarding uploading a file ,but in this post ,I will show you a very simple program for uploading a file .
This program is written using C# and Visual Studio 2008.
So Lets get started...................................................................

Fire up visual studio and open a new ASP.NET website

In this webpage add a FileUpload control from toolbox and a button.
Your webpage should look like the above image....................................

At the uploadbutton_click event Write the following code

protected void uploadbutton_Click(object sender, EventArgs e)
{
string strFileName = FileUpload1.PostedFile.FileName;\\Gets the wholepath of the file
string c = System.IO.Path.GetFileName(strFileName);
\\Gets the filename from the whole pathname

FileUpload1.PostedFile.SaveAs("C:\\images\\" + c);
\\ Saves the file in the desired directory (Instead of "C:\\images \\" ,Give the path where
you want to save the file.

Response.write("File uploaded successfully");
}

The above three line code is enough to upload a file,isnt it easy.
But if you want some extra information about the file being uploaded then you can use the following code

string filesize=FileUpload1.PostedFile.ContentLength.ToString();
\\ Gets the size of the file
string Content=FileUpload1.PostedFile.ContentType;
\\Gets the content type of file whether the file is an image or text

Using this additional code you can make your website more safe by restricting the kind of content being uploaded to the web server.

And the most Important thing
try testing this code on a seperate hard drive first before using it directly on your web server or on your Computers primary Hard drive ..................

Sunday, May 25, 2008

Integrating Fck-Editor


There are Quiet a few HTML -Editors or WYSIWYG(What you see is What you get) Editors avialable on net but I found this a lot more suitable for my website as it is totally free and a full featured Editor. Well this blog is About Integrating Fck-Editor with Visual-Studio to be used on .Net framework.
For Integrating Fck-editor you need to download Fck-editor.net and Fck-Editor script from here.
Then Fire up visual studio 2005/2008 version .
Open the website project you want to integrate this into
Right Click on the project name in Solution Explorer
Add Existing Item
Browse to Folder of Fckeditor.net
Bin->Release->version number(2.0)->FredCK.FCKeditorV2.dll

After adding the binary
Add the fckeditor folder to the project website folder .

And now when you Debug Your program it will show an Error .

The Most Important thing to be done is to change the 'Basepath 'of Fckeditor to '~/fckeditor/'in the properties window .
Adding the ~ sign specifies its location in the root folder.

After this your Editor will work perfectly.