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...