Rashim's Blog

Archive for January 2012


I wanna to introduce you with a nice and exciting thing. I assume you will be promoted from it. The web designer always passes his time in pain as his design work sometimes works perfectly in Mozilla but not in IE, or works in latest versions of the browser but not in the previous versions of many browsers and many more … So; will it not be superior for him to trial his work in all browsers with all/possible versions? Is it possible for him to test his design in all browsers with all versions in a single place?

Yes, this is possible. By using Browsershots you could do it.

Browsershots creates screenshots of your web design in diverse operating systems and browsers. It is a  online web application providing developers a convenient way to test their website’s browser compatibility in one place. When you submit your web address, it will be added to the job queue. A number of distributed computers will open your website in their browser. Please have a look on [^]


Last year I was assigned to develop a IoC container for R&D purposes which make me to start working with the IoC Cointainer

Anyway…
I share with you part of it as I think that, it might help you a lot to develop your own container.

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about eliminating dependencies from your code. Dependency injection is also usually well-known as “inversion of control” who’s Principle is – “Don’t call us, we’ll call you”. So simply we can say that IoC is the principle whereas DI is the way of implementation. There are three popular ways of inversion of control namely

  1.  Constructor Injection
  2.  Method Injection
  3.  Property Injection

Well,I am not going to discuss about IoC or DI rather i wanna to show how to implement our own IoC Container. However if you wanna to know in details about IoC and DI please have a look on the Link[^]

Lets move to our code portion,

public static class IoC
{
    private static readonly IDictionary<Type, Type> types = new Dictionary<Type, Type>();
    private static readonly IDictionary<Type, object> typeInstances = new Dictionary<Type, object>();
    public static void Register<TContract, TImplementation>()
    {
        types[typeof(TContract)] = typeof(TImplementation);
    }
    public static void Register<TContract, TImplementation>(TImplementation instance)
    {
        typeInstances[typeof(TContract)] = instance;
    }
    public static T Resolve<T>()
    {
        return (T)Resolve(typeof(T));
    }
    public static object Resolve(Type contract)
    {
        if (typeInstances.ContainsKey(contract))
        {
            return typeInstances[contract];
        }
        else
        {
            Type implementation = types[contract];
            ConstructorInfo constructor = implementation.GetConstructors()[0];
            ParameterInfo[] constructorParameters = constructor.GetParameters();
            if (constructorParameters.Length == 0)
            {
                return Activator.CreateInstance(implementation);
            }
            List<object> parameters = new List<object>(constructorParameters.Length);
            foreach (ParameterInfo parameterInfo in constructorParameters)
            {
                parameters.Add(Resolve(parameterInfo.ParameterType));
            }
            return constructor.Invoke(parameters.ToArray());
        }
    }
}

Now from your bootStrapper class you need to register your class like,

 Service svc = new Service();
 IoC.Register<IService, Service>(svc);

On a subsequent Classes you just need to inject the Interface or class that you register like,

private IService currentSvc = null;
public LoginServices(IService  submittedService)
{
   this.currentSvc =submittedService;
}

Very very Simple!!!! We love simple, don’t we?

Updated:19th March2012

Example: Say this is my Interface,

public interface ILogger
    {
        void Log(string submittedMsg);
    }

The Logger class implements this interface.

public class Logger : ILogger
{
    public void Log(string submittedMsg)
    {
        if (this != null && !string.IsNullOrEmpty(submittedMsg))
        {
            Console.WriteLine(string.Format("[{0}] {1}\r\n", DateTime.Now, submittedMsg));
            Console.Read();
        }
    }
}

In this ConsoleLogger class I inject the ILogger to its constructor,

public class ConsoleLogger
{
    private ILogger logger = null;

    public ConsoleLogger(ILogger submittedLogger)
    {
        this.logger = submittedLogger;
        this.DisplayMessage();
    }

    public void DisplayMessage()
    {
        logger.Log("Hi!!");
    }
}

Register and Resolve options,

class Program
{
    static void Main(string[] args)
    {
        IoC.Register<ILogger, Logger>();

        IoC.Register<ConsoleLogger, ConsoleLogger>();
        ConsoleLogger objCOnsoleLogger = IoC.Resolve<ConsoleLogger>();
    }
}

We always need to work with images to display it on the landscape or portrait mode. To do that we need to calculate the image size also need to generate the image dimension. This is very easy stuff though we are fighting a lot!!!

private Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
    {
        double multiplier = 0;
        string layout;
        if (currH > currW)
        {
            layout = "portrait";
        }
        else
        {
            layout = "landscape";
        }

        switch (layout.ToLower())
        {
            case "portrait":
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }
                break;
            case "landscape":
                if (destH > destW)
                {
                    multiplier = (double)destW / (double)currW;
                }
                else
                {
                    multiplier = (double)destH / (double)currH;
                }

                break;
        }

        return new Size((int)(currW * multiplier), (int)(currH * multiplier));
    }

Say i have a Database table name Employee and has 4 columns like ID, Firstname, Lastname,Email etc. That is, there is no Fullname Column but we need it to display it on the UI. So what we usually do?
We fetch all data; iterate over the list of data to make the Fullname String, right?
But there is another nice way to do that, if we get the property Fullname like Firstname or Lastname then it might help us a lot for further processing.
What I did for that, I have an Employee class in my dbml file. So I have created a partial Class name Employee in which I have define a Property Fullname as read-only. So when we get the Object Employee we will get the property Fullname also.

public partial class Employee
{
    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", this.Firstname, this.LastName);
        }
    }
}

Very Simple but Handy !!!!!!


Sometimes we need to save data to Excel file using Microsoft Excel. To do that we might need to create the Excel file, need to create table on that with some columns and then save data to the table of Excel file. This is pretty easy enough. Have a look on that.

Save Data to Excell Table,


        private void InsertDataOnExcellTable(string submitttedExcellPath, Test submittedExcellData)
        {
            if (!string.IsNullOrEmpty(submitttedExcellPath) && submittedExcellData != null)
            {
                if (!string.IsNullOrEmpty(submittedExcellData.FileName))
                {
                    var fullFileName = submitttedExcellPath + Path.DirectorySeparatorChar + submittedExcellData.FileName;

                    var xlFileExtension = ".xls";

                    if (!fullFileName.Contains(xlFileExtension))
                    {
                        fullFileName = fullFileName + xlFileExtension;
                    }

                    string connectionString = ConnectionString.GetConStr(fullFileName);

                    if (!string.IsNullOrEmpty(connectionString))
                    {
                        if (this.CreateTableOnExcell(fullFileName, connectionString) == true)
                        {
                            lock (new object())
                            {
                                System.Data.OleDb.OleDbConnection myConnection;
                                var myCommand = new System.Data.OleDb.OleDbCommand();
                                string sql = null;

                                myConnection = new System.Data.OleDb.OleDbConnection(connectionString);
                                myConnection.Open();
                                myCommand.Connection = myConnection;
                                sql = "Insert into [Sheet1$] "
                                + "( "
                                + "[Title],[FirstName],[Surname],[Email],[TelePhoneNumber],[OrderNumber],[SubmissionDate]"
                                + " )"
                                + " values "
                                + "('" + submittedExcellData.Title + "','" + submittedExcellData.FirstName + "','" + submittedExcellData.SurName + "','" + submittedExcellData.Email + "','" + submittedExcellData.TelePhoneNumber + "','" + submittedExcellData.OrderNumber + "','" + submittedExcellData.SubmissionDate + "')";

                                myCommand.CommandText = sql;
                                myCommand.ExecuteNonQuery();
                                myConnection.Close();
                            }
                        }
                    }
                }
            }
        }

Create table on Excell file,


        private bool CreateTableOnExcell(string submittedFullPath, string submittedConnStr)
        {
            if (!string.IsNullOrEmpty(submittedConnStr) && !string.IsNullOrEmpty(submittedFullPath))
            {
                if (this.CreateExcellFile(submittedFullPath))
                {
                    lock (new object())
                    {
                        OleDbConnection connExcel = new OleDbConnection(submittedConnStr);
                        OleDbCommand cmdExcel = new OleDbCommand();
                        cmdExcel.Connection = connExcel;
                        System.Data.DataTable excelSchema = null;

                        try
                        {
                            ////Check if the Sheet Exists
                            connExcel.Open();
                            excelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        }
                        catch
                        {
                        }
                        finally
                        {
                            connExcel.Close();
                        }

                        DataRow[] dr = excelSchema != null ? excelSchema.Select("TABLE_NAME = 'Sheet1'") : null;

                        ////if not Create the Sheet
                        if (dr == null || dr.Length == 0)
                        {
                            string excelCommand = "CREATE TABLE";

                            string sheetName = "[Sheet1]";

                            ////All Column Name
                            StringBuilder tableColumn = new StringBuilder();
                            tableColumn.Append("(");
                            tableColumn.Append("Title varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("FirstName varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("Surname varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("Email varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("TelePhoneNumber varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("OrderNumber varchar(20)");
                            tableColumn.Append(",");

                            tableColumn.Append("SubmissionDate varchar(20)");
                            tableColumn.Append(")");
                            tableColumn.Append(";");

                            StringBuilder exelQuery = new StringBuilder();
                            exelQuery.Append(excelCommand);
                            exelQuery.Append(" ");
                            exelQuery.Append(sheetName);
                            exelQuery.Append(" ");
                            exelQuery.Append(tableColumn.ToString());

                            if (cmdExcel != null)
                            {
                                cmdExcel.CommandText = exelQuery.ToString();
                                connExcel.Open();
                                cmdExcel.ExecuteNonQuery();
                                connExcel.Close();
                            }
                        }
                    }

                    return true;
                }
            }

            return false;
        }

Create Excel file,


        private bool CreateExcellFile(string submittedFullPath)
        {
            if (!string.IsNullOrEmpty(submittedFullPath))
            {
                lock (new object())
                {
                    if (!File.Exists(submittedFullPath))
                    {
                        ////Ex = Microsoft.Office.Interop.Excel;
                        Ex.Application exelApp = null;
                        Ex.Workbook exelWorkBook = null;
                        Ex.Worksheet exelWorkSheet = null;
                        object misValue = System.Reflection.Missing.Value;

                        try
                        {
                            ////Create an Excell Application
                            exelApp = new Ex.ApplicationClass();

                            if (exelApp != null)
                            {
                                if (exelApp.Workbooks != null)
                                {
                                    ////Add an Workbook to the current Excell Application
                                    exelWorkBook = exelApp.Workbooks.Add(misValue);
                                }
                            }

                            if (exelWorkBook != null)
                            {
                                ////Getting Sheet1
                                exelWorkSheet = (Ex.Worksheet)exelWorkBook.Worksheets.get_Item(1);

                                if (exelWorkSheet != null)
                                {
                                    //// Naming the Table Data Column
                                    exelWorkSheet.Cells[1, 1] = "Title";
                                    exelWorkSheet.Cells[1, 2] = "FirstName";
                                    exelWorkSheet.Cells[1, 3] = "Surname";
                                    exelWorkSheet.Cells[1, 4] = "Email";
                                    exelWorkSheet.Cells[1, 5] = "TelePhoneNumber";
                                    exelWorkSheet.Cells[1, 6] = "OrderNumber";
                                    exelWorkSheet.Cells[1, 7] = "SubmissionDate";
                                }

                                ////Save the Excell file to its Specified location
                                exelWorkBook.SaveAs(submittedFullPath, Ex.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Ex.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                            }
                        }
                        catch
                        {
                        }
                        finally
                        {
                            if (exelWorkBook != null)
                            {
                                exelWorkBook.Close(true, misValue, misValue);
                            }

                            if (exelApp != null)
                            {
                                exelApp.Quit();
                            }
                        }

                        this.ReleaseObject(exelWorkSheet);
                        this.ReleaseObject(exelWorkBook);
                        this.ReleaseObject(exelApp);
                    }

                    return true;
                }
            }

            return false;
        }

Release the Object by force,

private void ReleaseObject(object submittedObj)
        {
            try
            {
                //// By force realeasing the Object if the Garbage Collector not doing it right now
                System.Runtime.InteropServices.Marshal.ReleaseComObject(submittedObj);
            }
            catch
            {
            }
            finally
            {
                GC.Collect();
            }
        }

And then the Connection String,


        public static string GetConStr(string submittedPath)
        {
            var connectionString = string.Empty;

            if (!string.IsNullOrEmpty(submittedPath))
            {
                connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + submittedPath + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=0\"";
            }

            return connectionString;
        }


Object Serialization, which is also called deflating or marshaling, is a progression through which an object’s state is converted into some serial data format, such as XML or binary format, in order to be stowed for some advanced use whereas Deserialization is the opposite process of Serialization which is also called inflating or unmarshalling. The code showing the very simple way for serializing and deserializing from XML to any Object and vice versa as well,

Use this method for serialization,


        public static string Serialize<T>(T value)
        {
            if (value == null)
            {
                return null;
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UnicodeEncoding(false, false);
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;

            using (StringWriter textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    serializer.Serialize(xmlWriter, value);
                }

                return textWriter.ToString();
            }
        }

Use this method for Deserialization,


        public static T Deserialize<T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return default(T);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));

            XmlReaderSettings settings = new XmlReaderSettings();

            using (StringReader textReader = new StringReader(xml))
            {
                using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
                {
                    return (T)serializer.Deserialize(xmlReader);
                }
            }
        }

Couple of days ago I was working with excel file manipulation. The requirement was like that the file has to be created on the fly based on the data getting from database and then download it to the client PC. So what I did here is that, I have just created the excel file on the fly and send the data to the client in a chunk way. To do that, I wrote a handler which takes the key as the request, getting the data based on the key from the database, write the excel file and then download it to the chunk way. Fortunately, I have got an excellent article in code project which helped me for generating excel files without using Microsoft Excel.

The Handler class is given below,

public void ProcessRequest(HttpContext context)
        {
            HttpRequest request = context.Request;
            System.IO.MemoryStream currentStream = null;
            var buffer = new Byte[10000];
            int length;
            long dataToRead;
            var fileName = request["FileName"];

            var lstTest = DataAccess.GetDataByFileName(fileName);

            try
            {
                currentStream = new System.IO.MemoryStream();
                ExcelWriter writer = new ExcelWriter(currentStream);
                writer.BeginWrite();

                writer.WriteCell(0, 0, "Title");
                writer.WriteCell(0, 1, "FirstName");
                writer.WriteCell(0, 2, "Surname");
                writer.WriteCell(0, 3, "Email");
                writer.WriteCell(0, 4, "TelePhoneNumber");
                writer.WriteCell(0, 5, "OrderNumber");
                writer.WriteCell(0, 6, "SubmissionDate");

                if (lstTest != null)
                {
                    for (int row = 0; row < lstTest.Count; row++)
                    {
                        writer.WriteCell(row + 1, 0, lstTest[row].Title);
                        writer.WriteCell(row + 1, 1, lstTest[row].FirstName);
                        writer.WriteCell(row + 1, 2, lstTest[row].SurName);
                        writer.WriteCell(row + 1, 3, lstTest[row].Email);
                        writer.WriteCell(row + 1, 4, lstTest[row].TelePhoneNumber);
                        writer.WriteCell(row + 1, 5, lstTest[row].OrderNumber);
                        writer.WriteCell(row + 1, 6, lstTest[row].SubmissionDate);
                    }
                }

                writer.EndWrite();

                currentStream.Position = 0;
                context.Response.AddHeader("Content-Length", currentStream.Length.ToString());
                context.Response.AddHeader("Accept-Ranges", "bytes");
                context.Response.Buffer = false;
                context.Response.AddHeader("Connection", "Keep-Alive");
                context.Response.ContentType = "application/octet-stream";
                context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                dataToRead = currentStream.Length;
                context.Response.ContentType = "application/octet-stream";

                while (dataToRead > 0)
                {
                    if (context.Response.IsClientConnected)
                    {
                        length = currentStream.Read(buffer, 0, 10000);
                        context.Response.OutputStream.Write(buffer, 0, length);
                        context.Response.Flush();
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }

            catch (Exception ex)
            {
                context.Response.Write(ex);
            }
            finally
            {
                if (currentStream != null)
                {
                    currentStream.Close();
                    currentStream.Dispose();
                }
            }
        }

%d bloggers like this: