Thursday, 22 November 2012

Dynamic Sort Object

In the development it is always require to sort grids that has dynamic data source. Here is the code to sort with any property of object that is generic type.

/* Pass object to sort */
  public static List<T> DynamicSort<T>(List<T> genericList, string sortExpression, string sortDirection)
        {
            if (genericList != null)
            {
                int sortReverser = sortDirection.ToLower().StartsWith("asc") ? 1 : -1;

                Comparison<T> comparisonDelegate =
                    new Comparison<T>(delegate(T x, T y)
                    {
                        MethodInfo compareToMethod = GetCompareToMethod<T>(x, sortExpression);

                        object xSortExpressionValue = x.GetType().GetProperty(sortExpression).GetValue(x, null);
                        object ySortExpressionValue = y.GetType().GetProperty(sortExpression).GetValue(y, null);
                        object result = compareToMethod.Invoke(xSortExpressionValue, new object[] { ySortExpressionValue });
                        return sortReverser * Convert.ToInt16(result);
                    });

                genericList.Sort(comparisonDelegate);
            }
            return genericList;
        }

/* Get compare to method */
        public static MethodInfo GetCompareToMethod<T>(T genericInstance, string sortExpression)
        {
            Type genericType = genericInstance.GetType();
            object sortExpressionValue = genericType.GetProperty(sortExpression).GetValue(genericInstance, null);
            Type sortExpressionType = sortExpressionValue.GetType();
            MethodInfo compareToMethodOfSortExpressionType = sortExpressionType.GetMethod("CompareTo", new Type[] { sortExpressionType });

            return compareToMethodOfSortExpressionType;
        }

Preserve file in post back

Tuesday, 15 May 2012

SVN Repository


Start with SVN

· Download SVN win32SVN Server from : http://www.codeproject.com/Articles/18106/Subversion-TortoiseSVN-Installed-and-started-on-Wi
Or you can download VisualSVN and follow installation process.
o    Follow the instructions given in the page to install serve
  Download SVN Client tortoise from: http://tortoisesvn.net/downloads.html

Repository Structure

We will use Branch, Tags and Trunk folder structure as shown in Figure 1:

Figure 1
  • Trunk: Trunk is the main branch of development where current copy of working folder will be kept.
  • Branch: Isolating changes onto a separate line of development is called Branching. Branches are used to try out new feature without disturbing the main line of development. And as the new feature becomes stable the development branch is merged back into the main branch (trunk).
  • Tag: Tagging is to mark particular revisions (e.g. release version), so that you can recreate a certain build or environment at any time. Tags are used to create a static snapshot of the project at a particular stage. Tagging of the project is mostly done along with the successful build and generally it is done by the automated build process.
We are following version control mechanism. i.e.
        <major>.<minor>.<maintenance>
·         Major Release: Major releases introduce major new technologies and changes that render previous production releases obsolete.
·         Minor Release: Minor releases depict feature level enhancements. Addition of features between releases result in incremented minor release.
·         Maintenance Release:  This can include bug fix or any work for maintenance purpose.
Tentatively this structure can be change as per Requirement. E.g.
For Research & Development, folder structure can be:
·         Project Name
·         Documents

Back Up

From Command prompt run:
svnadmin dump "C:\SvnData\MyProject" > "C:\BackupMyProject.dump"

Restore

From Command prompt run:
svnadmin load "C:\SvnData\MyProject2" <  "C:\BackupMyProject.dump"

Set Folder wise authentication

Notes:

·         Always write comments while do any operation on SVN
·         Release new version to Tag
·         Use SVN standard folder structure

Thursday, 1 March 2012

Upload file in Silverlight


Create ashx file to Web Application and add below code. Store this file where client bin folder is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace UtilizationReport.Web
{
    /// <summary>
    /// Summary description for FileUpload
    /// </summary>
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string filename = context.Request.QueryString["filename"].ToString();
            using (FileStream fs = File.Create(context.Server.MapPath("~/UtilizationReport/"+filename)))
            {
                SaveFile(context.Request.InputStream, fs);
            }
        }

        private void SaveFile(Stream stream, FileStream fs)
        {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

From Silverlight application when you open a dialog box:

private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "All files|*.xls";
            dlg.Multiselect = false;

            if ((bool)dlg.ShowDialog())
            {
               UploadFile.UploadFiles(dlg.File.Name, dlg.File.OpenRead());
                txtSdataStatus.Text = "File uploaded successfully!";
            }
        }

In Silverlight application create class that will read file and convert to binary and send to ashx file which will save it:

public static class UploadFile
    {
        public static void UploadFiles(string filename, Stream data)
        {
            UriBuilder ub = new UriBuilder(App.Current.Host.Source.AbsoluteUri.Replace("ClientBin/YourFile.xap", "") + "FileUpload.ashx");
            ub.Query = string.Format("filename={0}", filename);
            WebClient client = new WebClient();
            client.OpenWriteCompleted += (sender, e) =>
            {
                pushdata(data, e.Result);
                e.Result.Close();
                data.Close();
            };
            client.OpenWriteAsync(ub.Uri);
        }

       public static void pushdata(Stream input, Stream output)
        {
            byte[] buffer = new byte[20000];
            int bytesRead;
            while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
            {
                output.Write(buffer, 0, bytesRead);
            }
        }
    }

To Upload heavy files update web.config:
   <httpRuntime maxRequestLength="2097151" />