Monday, December 27, 2010

What is Index?

An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.

Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.

e.g. sp_helpdb, sp_renamedb, sp_depends etc.

List All Tables of Database


USE YourDBName
GO
SELECT *
FROM sys.Tables
GO

Monday, December 6, 2010

How to Add CSS dynamically to controls in C#, ASP.NET

To add style Dynamically just add this code snippet.
Control_ID.Style.Add("color","#FFFF99");
As in the above example I had just given a example to change the font color dynamically. You can use another method to add the style to the control dynamically... Like
Control_ID.Attribute.Add("Style='color:#FFFF99;'");

How to Encrypt and Decrypt the Query string automatically by C#, Asp.Net

Just Create a Businesslogic class in App_code folder with the name QueryStringModule.cs
and then add the below given code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// 
/// Summary description for QueryStringModule
/// 
public class QueryStringModule : IHttpModule
{
    ///   
    /// Summary description for QueryStringModule  
    ///   
    
        //  private ILog m_Logger = LogManager.GetLogger(typeof(QueryStringModule));  
        #region IHttpModule Members

        public void Dispose()
        {
            // Nothing to dispose  
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        private const string PARAMETER_NAME = "enc=";
        private const string ENCRYPTION_KEY = "key";

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = HttpContext.Current;
            string query = string.Empty;
            string path = string.Empty;

            try
            {
                if (context.Request.Url.OriginalString.Contains("aspx") && context.Request.RawUrl.Contains("?"))
                {
                    query = ExtractQuery(context.Request.RawUrl);
                    path = GetVirtualPath();

                    if (query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase))
                    {
                        // Decrypts the query string and rewrites the path.  
                        string rawQuery = query.Replace(PARAMETER_NAME, string.Empty);
                        string decryptedQuery = Decrypt(rawQuery);
                        context.RewritePath(path, string.Empty, decryptedQuery);
                    }
                    else if (context.Request.HttpMethod == "GET")
                    {
                        // Encrypt the query string and redirects to the encrypted URL.  
                        // Remove if you don't want all query strings to be encrypted automatically.  
                        string encryptedQuery = Encrypt(query);
                        context.Response.Redirect(path + encryptedQuery, false);
                    }
                }
            }
            catch (Exception ex)
            {
                // m_Logger.Error("An error occurred while parsing the query string in the URL: " + path, ex);  
                context.Response.Redirect("~/Home.aspx");
            }

        }

        ///   
        /// Parses the current URL and extracts the virtual path without query string.  
        ///   
        /// The virtual path of the current URL.  
        private static string GetVirtualPath()
        {
            string path = HttpContext.Current.Request.RawUrl;
            path = path.Substring(0, path.IndexOf("?"));
            path = path.Substring(path.LastIndexOf("/") + 1);
            return path;
        }

        ///   
        /// Parses a URL and returns the query string.  
        ///   
        /// The URL to parse./// The query string without the question mark.  
        private static string ExtractQuery(string url)
        {
            int index = url.IndexOf("?") + 1;
            return url.Substring(index);
        }

        #region Encryption/decryption

        ///   
        /// The salt value used to strengthen the encryption.  
        ///   
        private readonly static byte[] SALT = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString());

        ///   
        /// Encrypts any string using the Rijndael algorithm.  
        ///   
        /// The string to encrypt./// A Base64 encrypted string.  
        private static string Encrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();
            byte[] plainText = Encoding.Unicode.GetBytes(inputText);
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainText, 0, plainText.Length);
                        cryptoStream.FlushFinalBlock();
                        return "?" + PARAMETER_NAME + Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }

        ///   
        /// Decrypts a previously encrypted string.  
        ///   
        /// The encrypted string to decrypt./// A decrypted string.  
        private static string Decrypt(string inputText)
        {
            RijndaelManaged rijndaelCipher = new RijndaelManaged();

            byte[] encryptedData = Convert.FromBase64String(inputText);
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(ENCRYPTION_KEY, SALT);

            using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        return Encoding.Unicode.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }

        #endregion

    }


After then in web.config file add this code...

 


Thats it, now get the Querystring on any page in encripted manner,
For example:
LblQuery.Text=Request.QueryString["id"].ToString();

Friday, December 3, 2010

Disable Right Click to secure your webpage by JavaScript, ASP.Net

 


Searching All columns in one table one by one for a particular data in SQL Server

SELECT 
        * 
FROM 
        testview
WHERE 
        Username like '%' + @search + '%' 
OR 
        Description like '%' + @search + '%' 
OR  
        Title like '%' + @search + '%'

How to add two different columns data in one columns from SQL server and C#

By using LTRIM();

string commnd = "select id,(LTRIM(FirstName)+' '+Ltrim(LastName)) as [Name],Date_of_Birth,Email_id,Phone_no,Postal_Address,imgURL from Candidate_Info where id=" + id;

Thats all...

How to make corp and thumbnail of any size of image in C#, ASP.NET

With out loosing clarity of the image you can get it by given two method, In my case I had to upload the image in the server and show them in the gallery...

protected void btnUpload_Click(object sender, EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;

// Set constant values

sSavePath = "uploadedImages/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;

// If file field is not empty

if (fileUploader.PostedFile != null)
{
// Check file size (must not be 0)

HttpPostedFile myFile = fileUploader.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Visible = true;
lblOutput.Text = "No file was uploaded.";
return;
}

// Check file extension (must be JPG)

if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Visible = true;
lblOutput.Text = "The file must have an extension of JPG";
return;
}

// Read file into a data stream

byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);

// Make sure a duplicate file does not exist.  If it does, keep on appending an 

// incremental numeric until it is unique

string sFilename = System.IO.Path.GetFileName(myFile.FileName);

int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}

// Save the stream to disk

System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();

// Check whether the file is really a JPEG by opening it

System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

// If jpg file is a jpeg, create a thumbnail filename that is unique.

file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}

// Save thumbnail and output it onto the webpage

System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
filename = sThumbFile;
imgUser.ImageUrl = sSavePath + sThumbFile;
fileURL = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Visible = true;
lblOutput.Text = "File uploaded successfully!";

// Destroy objects

myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Visible = true;
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}

}

Next...

public bool ThumbnailCallback()
{
return false;
}

Thats all...

Friday, November 26, 2010

How to Read and Get Data From XML Document in C#

By this Method we can easily get Data from XML Database. For this first of all create a "ContactsList.xml" XML file and under root section add your recoreds.

public void GetData()
{
try
{
string path = "ContactsList.xml";
FileStream fs = new FileStream path,FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
DataSet ds = new DataSet();
ds.ReadXml(fs);
if (ds.Tables.Count != 0)
{
DataTable dt = ds.Tables[0];

int a = dt.Rows.Count;

for (int i = 0; i < a; i++)
{
string[] str1 = new string[4];
str1[0] = dt.Rows[i].ItemArray[0].ToString();


str1[1] = dt.Rows[i].ItemArray[1].ToString();
str1[2] = dt.Rows[i].ItemArray[2].ToString();
int count = Convert.ToInt32(dt.Rows[i].ItemArray[7].ToString());
if (count.Equals(1) || count.Equals(0))
{
str1[3] = dt.Rows[i].ItemArray[3].ToString();
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}
else
{
string interests = dt.Rows[i].ItemArray[3].ToString() + "," + dt.Rows[i].ItemArray[4].ToString() + "," + dt.Rows[i].ItemArray[5].ToString() + "," + dt.Rows[i].ItemArray[6].ToString();
str1[3] = interests;
ListViewItem item1 = new ListViewItem(str1);
ldtvw_Contact.Items.Add(item1);
}

}

fs.Close();
}

Thats All....

Thursday, November 25, 2010

How to Generate Random String in C#, ASP.NET

To Generate a Random String is very Tricky and useful stuff to Know as we can use this functionality at the time of Generating Random Password automatically for each User Registering on the website.

I am sure this will help you a lot, here I am writing the Method to Generate the Random String.

private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
Now the above code will generate the Random String. If you want to have a Strong Password then password must contains Number. So lets go to generate Random Numbers:
public string GetRandomNumber()
    {
        StringBuilder strbuild = new StringBuilder();
        strbuild.Append(RandomNumber(1000, 9999));
        return strbuild.ToString();
    }

private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

Now you are ready to generate a random password. for that you have to call these methods as given below:
public string GetPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }

That's All, Please give your comments if the post is helpful.

Sunday, November 21, 2010

Freeze GridView Header While Scrolling

This is very common problem in Web development that we need to freeze the GridView header at the time of scrolling, Here is one simple tips:

Step 1 : Create a CSS class as following
<br />.HeaderFreez <br />{ <br />position:relative ; <br />top:expression(this.offsetParent.scrollTop); <br />z-index: 10; <br />} <br />

Step 2 Set Gridview’s HeaderStyle CssClass as follows
CssClass="HeaderFreez"
That’s all guys ...

How to Save Valuable Code section in your Visual Toolbox

Very useful for re-Usability of the code...


Step 1: Very Simple Just Copy the Code section and Drop on the Toolbox.
thats it...

If you wanna give your unique Identification to the code than Give a Name to that by Right clicking and Renaming that.

Connection Pooling

Creating and establishing a connection with a database server is a high resource consuming process and hence by result more time taking.
If any application needs to fire any query against any database server, we need to first establish a connection with the server and then execute the query against that database server.
So why we will again and again open and close the connection of Database, for that only connection pooling came in feature.
When the first time ADO.Net is stabilizing connection with the database and connection open with the respective credentials the ADO. Net  is  saving the references for the that connection and while closing the connection ADO.Net is not closing total connection and when another request done for the Database action ADO.Net using that references for the Database process so no Hassel for opening and closing connection again and again, and process is more faster .
Sample Connection String with Connection Pooling…..

initial catalog=Northwind; Data Source=localhost; Connection Timeout=30;
User Id=USER; Password=PASS; Min Pool Size=20; Max Pool Size=200;
 Incr Pool Size=10; Decr Pool Size=5;

Delegates:

A delegate is a type-safe object that can point to another method (or possibly multiple methods) in the application, which can be invoked at later time.

What Is A Web Service?

A Web Service is a program that can be invoked in a distributed web envi ronment. Web Service technologies like SOAP, WSDL, and UDDI are standards to describe, publish, discover, and use Web Services; they define a development model  for integrating applications over the web.

Steps to Create a Web Service

1.  Create (or use an existing) virtual directory for any folder on your computer.
2.  Create an empty file called “test.asmx” in the folder.
3.  Edit the file and add the  following text:
<%@ WebService Language="C#" Class="MyMath" %>
using System.Web.Services;
public class MyMath
{
    [WebMethod]
    public int Add(int num1, int num2)
    {
         return num1+num2;
    }
}

Tuesday, October 19, 2010

Model View Controller (MVC)

MVC is not referred to as a design pattern but a “set of classes to build a user interface” that uses design patterns such as Observer, Strategy, and Composite. It also uses Factory Method and Decorator, but the main MVC relationship is defined by the Observer and Strategy patterns.
There are three types of objects. The Model is our application data, the View is a screen, and the Controller defines the way the View reacts to user input. The views and models use the Publish-Subscribe protocol - when Model data is changed, it will update the View. It allows us to attach multiple Views to the same Model [2]. This is achieved by using the Observer design pattern.









The goal of this pattern is to define the one-to-many relationship between the Subject and the Observers; if the Subject is changed all Observers are updated. The Subject maintains the list of the Observers and can attach and detach objects to the list. The Observer in return exposes an Update method on its interface that Subject can use to update all objects it observes. The C# implementation would look like this:


public abstract class Subject 
{ 
    private readonly ICollection<Observer> Observers = 
            new Collection<Observer>(); 

    public void Attach(Observer observer) 
    { 
        Observers.Add(observer); 
    } 
    public void Detach(Observer observer) 
    { 
        Observers.Remove(observer); 
    } 
    public void Notify() 
    { 
        foreach (Observer o in Observers) 
        { 
            o.Update(); 
        } 
    } 
} 

public class ConcreteSubject : Subject 
{ 
    public object SubjectState { get; set; } 
} 

public abstract class Observer 
{ 
    public abstract void Update(); 
} 

public class ConcreteObserver : Observer 
{ 
    private object ObserverState; 
    private ConcreteSubject Subject { get; set; } 

    public ConcreteObserver(ConcreteSubject subject) 
    { 
        Subject = subject; 
    } 
    public override void Update() 
    { 
        ObserverState = Subject.SubjectState; 
    } 
}
 
The other component of the MVC pattern is the View-Controller relationship.
The View uses the Controller to implement a specific type of response.
The controller can be changed to let the View respond differently to user input.
This View-Controller link is an example of the Strategy design pattern.
 

Each ConcreteStrategy encapsulates a particular type of response.
A Context object has a reference to a Strategy object and can
forward the requests to a specific Strategy though the common interface.
Here is a C# code:
 
public abstract class Strategy 
{ 
    public abstract void AlgorithmInterface(); 
} 
public class ConcreteStrategyA : Strategy 
{ 
    public override void AlgorithmInterface() 
    { 
        // code here 
    } 
} 
public class Context 
{ 
    private readonly Strategy Strategy; 

    public Context(Strategy strategy) 
    { 
        Strategy = strategy; 
    } 
    public void ContextInterface() 
    { 
        Strategy.AlgorithmInterface(); 
    } 
}
Now we know that the Model acts as a Subject from the Observer pattern and the View takes on the role of the Observer object. In the other relationship of the MVC, the View  is a Context and the Controller is a Strategy object. Combining our  knowledge of the two diagrams, we can draw the MVC UML class diagram as  below: 
 


 
 
 
Here is the implementation code for the MVC pattern:
public abstract class Model 
{ 
    private readonly ICollection<View> Views = new Collection<View>(); 
    public void Attach(View view) 
    { 
        Views.Add(view); 
    } 
    public void Detach(View view) 
    { 
        Views.Remove(view); 
    } 
    public void Notify() 
    { 
        foreach (View o in Views) 
        { 
            o.Update(); 
        } 
    } 
} 

public class ConcreteModel : Model 
{ 
    public object ModelState { get; set; } 
} 

public abstract class View 
{ 
    public abstract void Update(); 
    private readonly Controller Controller; 
    protected View() 
    { 
    } 
    protected View(Controller controller) 
    { 
        Controller = controller; 
    } 
    public void ContextInterface() 
    { 
        Controller.AlgorithmInterface(); 
    } 
} 

public class ConcreteView : View 
{ 
    private object ViewState; 
    private ConcreteModel Model { get; set; } 
    public ConcreteView(ConcreteModel model) 
    { 
        Model = model; 
    } 
    public override void Update() 
    { 
        ViewState = Model.ModelState; 
    } 
} 

public abstract class Controller 
{ 
    public abstract void AlgorithmInterface(); 
} 

public class ConcreteController : Controller 
{ 
    public override void AlgorithmInterface() 
    { 
        // code here 
    } 
}
If we leave out the concrete classes for simplicity,
we will get a more familiar MVC diagram.
Please note that we use pseudo- rather than proper UML shapes,
where circles represent a group of classes (e.g., Model and ConcreteModel),
not classes as on the UML class diagram on Figure 3.

Monday, October 18, 2010

How to provide application "Admin privilege" in Vista and Windows 7 By C# (Visual Studio)

For giving Administrative privilege we have to make our application UAC compliant,
so that it will ask user to grant your application Administrator access.

To make our application UAC compliant,
Double Click My Project in Solution Explorer and Click UAC Settings button as shown in image.











Then Modify app.manifest file as shown below. Make it 'requireAdministrator' instead of 'asInvoker' and save.
Hoping this post will help you...