Thursday, 9 August 2012

.Net Code to Resize images in Directory

The below code help to resize the images within a directories. The code is more self explanatory. I have googled and nothing workout for me. Most of the code in the google are working partially and available in bits and pieces. So I've integrated them and made it work in a fine manner.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;


public class ImageResizer
{
    const string srcpath = "P:\\";
    const string destpath = "N:\\";
    static void Main()
    {
        Console.WriteLine("Processing Image...........");
        int filecount;
        filecount = 1;

        MyImageProcessingClass myobject = new MyImageProcessingClass();
        myobject.ProcessFiles(srcpath, destpath, 1);

        Console.WriteLine("Image Resized Successfully...........");
        Console.Read();
        Console.ReadLine();
    }
}
public class MyImageProcessingClass
{

    public bool CheckJpgFile(string filename)
    {     // add other possible extensions here  
        return Path.GetExtension(filename).Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
        || Path.GetExtension(filename).Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase);
    }

    public void ProcessFiles(string path, string destpath, int filecount)
    {
        string[] files;
        string[] directories;

        string filename;
        files = Directory.GetFiles(path);


        foreach (string file in files)
        {

            // Process each file                    
            bool isJpeg = CheckJpgFile(file);
            Console.WriteLine(isJpeg);
            if (isJpeg == true)
            {
                Image img = Resize(Image.FromFile(file));
                filename = destpath + Convert.ToString(filecount) + ".jpg";
                filecount = filecount + 1;
                SaveJPGWithCompressionSetting(img, filename, 80L);
            }
        }

        directories = Directory.GetDirectories(path);
        foreach (string directory in directories)
        {
            // Process each directory recursively
            ProcessFiles(directory, destpath, filecount);
        }
    }

    /// <summary>
    /// method for resizing an image
    /// </summary>
    /// <param name="img">the image to resize</param>
    /// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param>
    /// <returns></returns>
    public Image Resize(Image img)
    {
        //get the height and width of the image
        int originalW = img.Width;
        int originalH = img.Height;

        // Prevent using images internal thumbnail
        img.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        img.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        //get the new size based on the percentage change
        int resizedW = 196;
        int resizedH = 228;

        if (img.Width <= resizedW)
        {
            resizedW = img.Width;
        }

        resizedH = img.Height * resizedW / img.Width;
        if (resizedH > originalH)
        {
            // Resize with height instead
            resizedW = img.Width * originalH / img.Height;
            resizedH = originalH;
        }

        System.Drawing.Image NewImage = img.GetThumbnailImage(resizedW, resizedH, null, IntPtr.Zero);


        //create a new Bitmap the size of the new image
        Bitmap bmp = new Bitmap(resizedW, resizedH);
        //create a new graphic from the Bitmap
        Graphics graphic = Graphics.FromImage((Image)bmp);

        graphic.SmoothingMode = SmoothingMode.HighQuality;
        graphic.InterpolationMode = InterpolationMode.NearestNeighbor;
        graphic.PixelOffsetMode = PixelOffsetMode.Half;

        //draw the newly resized image

        graphic.DrawImage(NewImage, 0, 0, resizedW, resizedH);

        //dispose and free up the resources
        graphic.Dispose();
        //return the image
        return (Image)bmp;
    }


    public ImageCodecInfo GetEncoderInfo(String mimeType)
    {
        int j;
        ImageCodecInfo[] encoders;
        encoders = ImageCodecInfo.GetImageEncoders();
        for (j = 0; j < encoders.Length; ++j)
        {
            if (encoders[j].MimeType == mimeType)
                return encoders[j];
        }
        return null;
    }

    public void SaveJPGWithCompressionSetting(Image image, string szFileName, long lCompression)
    {
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, lCompression);
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg");
        image.Save(szFileName, ici, eps);
    }

}



Thursday, 21 June 2012

ASP.net Partial Classes


In ASP.net whenever you right click and add file to the solution/project a new file will be created. In the newly created code behind file you can able to see the Partial keyword just before the class name of that file.

Do you know why the class is mentioned as Partial class in the code behind?  The main reason of having the class file as a Partial class because of the same class name can be used across different physical files this will help the developer to develop the own module without affecting the others code.

The complier will treat different physical files of the partial classes with the same class name as a single entity.

Below code is sample example of a partial class.

1 .file1.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

2 .file2.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

3 .file3.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      //Some Code
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
      //Some Code
      
    }
}

Monday, 11 June 2012

SQL Linked Server and Distributed Server


Microsoft SQL Server 2008 provides numerous features for integrating SQL Server databases with other SQL Server databases and with other data sources, including distributed data, linked servers, and replication. Distributed data includes support for distributed queries, distributed transactions, and remote stored procedure execution. These distributed data features are handled through linked servers, which can be computers running SQL Server or computers running other database server software, such as Oracle DB.

Distributed Queries

When you execute a distributed query, SQL Server interprets the command and then breaks it down for the destination OLE DB provider using rowset requests. A rowset is a type of database object that enables OLE DB data providers to support data with a tabular format. As their name implies, rowset objects represent a set of rows and columns of data. After creating the rowset objects, the OLE DB provider calls the data source, opens the necessary files, and returns the requested information as rowsets. SQL Server then formats the rowsets as result sets and adds any applicable output parameters.
You can create simple distributed queries quickly by making your own rowsets. To do this, you use the Openrowset function. When you use this function, you do not need to use linked servers, and you can use the Openrowset function in place of a table in a query if you pass parameters that identify the OLE DB data source and provider.
You use the Openrowset function in the same way that you use virtual tables; simply replace the virtual table reference with an Openrowset reference. shows the syntax and usage of Openrowset.
Syntax for SELECT with Table Alias

SELECT selection FROM OPENROWSET(rowset_options) AS table_alias

Syntax for OPENROWSET

OPENROWSET
( { 'provider_name' , { 'datasource' ; 'user_id' ; 'password'
   | 'provider_string' }
      , { [ catalog. ] [ schema. ] object
   | 'query' }
   | BULK 'data_file' ,
       { FORMATFILE = 'format_file_path' [ <bulk_options> ]
       | SINGLE_BLOB | SINGLE_CLOB | SINGLE_NCLOB }
} )

<bulk_options> ::=
   [ , CODEPAGE = { 'ACP' | 'OEM' | 'RAW' | 'code_page' }]
   [ , ERRORFILE = 'file_name' ]
   [ , FIRSTROW = first_row ]
   [ , LASTROW = last_row ]
   [ , MAXERRORS = maximum_errors ]
   [ , ROWS_PER_BATCH = rows_per_batch ]
   [ , ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) [ UNIQUE ]

Usage

USE pubs
GO
SELECT a.*
FROM OPENROWSET('SQLOLEDB','DBname';'username1';'pwd@123',
'SELECT * FROM pubs.dbo.authors ORDER BY au_lname, au_fname')
AS a


Linked Queries

You also can use remote stored procedures that execute against the linked server or distributed queries that access tables in the linked server through SELECT, INSERT, UPDATE, and DELETE statements that reference the linked server using a four-part name. The syntax for a four-part name is
Format : LinkedServerName.DatabaseName.TableName.ColumnName

In this example, LinkedServerName is the name of a previously defined linked server, DatabaseName is the name of a database, TableName is the name of a database table, and ColumnName is the name of a table column, such as

SELECT * FROM lnkName.Customers.SalesMan.EmployeeID
 
Syntax

sp_addlinkedserver [@server =] 'server'
    [, [@srvproduct =] 'product_name']
    [, [@provider =] 'provider_name']
    [, [@datasrc =] 'data_source']
    [, [@location =] 'location']
    [, [@provstr =] 'provider_string']
    [, [@catalog =] 'catalog']

Usage
EXEC sp_addlinkedserver
        @server='ORADBSVR38',
        @srvproduct='Oracle',
        @provider='OraOLEDB.Oracle',
        @datasrc='ORACLE10';

Thursday, 24 May 2012

SQL COALESCE‏


Coalesce function is a good feature in SQL to concatenate data from multiple columns of that row and return a single field value. During the concatenation the null value will be ignore and it retrieve non null values.

Consider a scenario you need to retrieve contact number of an employee from an employee table. It is not necessary that all type of contact number is available in the employee table. We need to retrieve the employee contact number. So using the coalesce function we can retrieve the employee contact number.

Employee Table
Name
Business_Phone
Cell_Phone
Home_Phone
Marsh
531-2531
622-7813
565-9901
Don
NULL
772-5588
312-4088
Parker
NULL
NULL
594-7477
and we want to find out the best way to contact each person according to the following rules:
1. If a Employee has a business phone, use the business phone number.
2. If a Employee does not have a business phone and has a cell phone, use the cell phone number.
3. If a Employee does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.
We can use the COALESCE function to achieve our goal:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone 
FROM Contact_Info;
Result:
Name
Contact_Phone
Marsh
531-2531
Don
772-5588
Parker
594-7477

Wednesday, 23 May 2012

ASP.net Copy Files and Folder from source to destination with creating backup folder.


The manual deployment of files is applicable in most of the enhancement or maintenance project. This method is applicable only for certain applications that are developed before 2002 for classic asp and other programming languages with no class libraries. Still it is a part of activity performed by the deployment team to transfer the modified file from staging folder to the production folder. Normally the developers copy the files from the development environment or UAT environment and put it in a staging environment. And then after approval process the deployment team takes the code from staging and deployment in production.  The whole process is so cumbersome and difficult for the developer to copy the files from the development or UAT to staging. So the below code is so self explanatory for creating the files and folders in the staging environment with a deployment instruction in the staging location.

The Code accepts various parameters like source location, destination location, backup folder location, ticket name.
Create deployment instruction and rollback instruction along with the files and folders to be copied in the staging environment with the same structure.

This code can used as a part in a web application for creating deployment instruction.

Public Shared Sub CreateFileFolder(ByVal srcFullPath As String, ByVal srcPath As String, ByVal dstPath AsString, ByVal fileName As String, ByVal ticketNo As String, ByVal lastFldr As Boolean, ByVal bkpFolder AsString)
        Dim dstDir, backupDir As DirectoryInfo
        Dim tmpPath As String
        ‘Create instr if it is the last folder 
        If lastFldr = True Then
            If File.Exists(DeployInstrPath & "Instr.txt") Then File.Delete(DeployInstrPath & "Instr.txt")
            WriteFile(DeployInstr, DeployInstrPath & "Instr.txt")
            If File.Exists(DeployInstrPath & "RollbackInstr.txt") Then File.Delete(DeployInstrPath &"RollbackInstr.txt")
            WriteFile(RollbackInstr, DeployInstrPath & "RollbackInstr.txt")
            Exit Sub
        End If

        Try
            If (srcPath.Contains("\")) Then
                tmpPath = srcPath.Substring(0, srcPath.IndexOf("\"))
                srcPath = srcPath.Substring(srcPath.IndexOf("\") + 1)
                lastFldr = False
            Else
                tmpPath = srcPath
                lastFldr = True
            End If
            If ticketNo.Length <> 0 Then
                dstPath += "\" + tmpPath + "\" + ticketNo
                backupDir = New DirectoryInfo(dstPath + "\Backup")
              ‘Create backupFolder 
                backupDir.Create()
                bkpFolder = dstPath + "\Backup"
            Else
                dstPath += "\" + tmpPath
                bkpFolder += "\" + tmpPath
              ‘Create folder inside the structure
                backupDir = New DirectoryInfo(bkpFolder)
                If (Not backupDir.Exists) Then backupDir.Create()
            End If
             ‘Create Main Folder
            dstDir = New DirectoryInfo(dstPath)
            If (Not dstDir.Exists) Then dstDir.Create()
            If lastFldr = True Then
                CopyFiles(srcFullPath, dstPath + "\" + fileName)
                WriteDeployInstruction(fileName, srcPath, bkpFolder & "\", dstPath & "\")
                WriteRollbackInstruction(fileName, srcPath, bkpFolder & "\")
            End If
            CreateFileFolder(srcFullPath, srcPath, dstPath, fileName, String.Empty, lastFldr, bkpFolder)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Tuesday, 22 May 2012

ASP.net to write simple log file in VB.net language

In many applications we may came across lot logging techniques. Like writing log files in text file, some custom log file, log in event viewer, logging information in Databases etc.,

Here we are going to see a simple code in VB.net programming language that will help in logging information for any applications.

1. Use a system.IO namespace for any file handling operations.
2. When a variable is considered as a shared object, it means there is no need for object creation in the instantiation class.
3. The  System.Windows.Forms.Application.StartupPath is a application running folder path
4. Check to see the log folder and log file already exists. If not exist then create one or else concatenate with the existing content in the log file.
5. Create a filestream object and using streamwriter write the content to the log file.



Imports System
Imports System.IO
Public Class Log
    Private Shared LogPath As String = System.Windows.Forms.Application.StartupPath + "\Log\"
    Private Shared fs As FileStream
    Private Shared sw As StreamWriter
    ''' <summary>
    ''' Log result in the log file
    ''' </summary>
    ''' <remarks></remarks>
    Public Shared Sub Log(ByVal logStr As String)
        Dim logDir As DirectoryInfo
        Dim logFileName As String = LogPath + "Log.txt"
        logDir = New DirectoryInfo(LogPath)
        If (Not logDir.Exists) Then logDir.Create()
        If (Not File.Exists(logFileName)) Then File.Create(logFileName)
        If File.Exists(logFileName) Then
            sw = File.AppendText(logFileName)
            sw.WriteLine(logStr.ToString())
            sw.Close()
        Else
            fs = New FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
            sw = New StreamWriter(fs)
            sw.WriteLine()
            sw.WriteLine(logStr.ToString())
            sw.Close()
        End If
    End Sub
End Class