My recipe for a paged list / DataModel with strong type

I needed to create some sort of IList that can handle a data source that supports paging.

Let’s start with the basics –
our class :

public class MyPagedDataModel<T> {
 /// ... code goes here....
}

Let’s continue by allowing us to determine the page size, current page index, and our data source.

        /// <summary>
        /// how many records per page
        /// </summary>
        public virtual int PageSize { get; set; }

        /// <summary>
        /// Current page index - offset 1 (first page is 0)
        /// </summary>
        public virtual int CurrentPageIndex { get; set; }

        public virtual object DataSource { get; set; }

To determine the number of records, and pages, I will have to skip one step, I trust you can keep up, but feel free to contact me if you have questions –


private IEnumerable<T> _list;

 public virtual IEnumerable<T> DisplayItems {
            get {
                ParseData();
                return _list;
            }
        }

internal override void ParseData()
        {

            if (_list == null)
            {
                _list = (IEnumerable<T>) DataSource;
                ApplyFilters();

                if (!PrePaged)
                {
                    TotalRecords = ((IQueryable<T>) DataSource).Count();

                    _list = _list.Skip(CurrentPageIndex * PageSize).Take(PageSize);
                }

            }
            base.ParseData();
        }

/// <summary>
        /// Total data records
        /// </summary>
        public virtual int TotalRecords
        {
            get
            {
                if (_totalRecords>0)
                    return _totalRecords; 

                ParseData();
                return _totalRecords;
            }
            set
            {
                _totalRecords = value;
            }
        }

        /// <summary>
        /// Compute the pages count.
        /// </summary>
        public virtual int TotalPages{
            get {
                if (PageSize == 0)
                    return 0;

                return (int)Math.Ceiling((decimal)TotalRecords / (decimal)PageSize);
            }
        }

Let’s see the complete class

public class MyPagedDataModel<T> {
        /// <summary>
        /// how many records per page
        /// </summary>
        public virtual int PageSize { get; set; }

        /// <summary>
        /// Current page index - offset 1 (first page is 0)
        /// </summary>
        public virtual int CurrentPageIndex { get; set; }

        public virtual object DataSource { get; set; }

private IEnumerable<T> _list;

 public virtual IEnumerable<T> DisplayItems {
            get {
                ParseData();
                return _list;
            }
        }

internal override void ParseData()
        {

            if (_list == null)
            {
                _list = (IEnumerable<T>) DataSource;
                ApplyFilters();

                if (!PrePaged)
                {
                    TotalRecords = ((IQueryable<T>) DataSource).Count();

                    _list = _list.Skip(CurrentPageIndex * PageSize).Take(PageSize);
                }

            }
            base.ParseData();
        }

/// <summary>
        /// Total data records
        /// </summary>
        public virtual int TotalRecords
        {
            get
            {
                if (_totalRecords>0)
                    return _totalRecords; 

                ParseData();
                return _totalRecords;
            }
            set
            {
                _totalRecords = value;
            }
        }

        /// <summary>
        /// Compute the pages count.
        /// </summary>
        public virtual int TotalPages{
            get {
                if (PageSize == 0)
                    return 0;

                return (int)Math.Ceiling((decimal)TotalRecords / (decimal)PageSize);
            }
        }

}
As always, feel free to contact me with suggestions or questions

How to convert an object in C# to JSON

While working on one of my favorites eMagid projects – rentalengine, one of our technicians had to deal with a small hurdle – How to convert custom object into JSON, so it can be consumed by our rich JavaScript UI.

The solution is actually way more simple than you’d imagine – There is a built it serializer just for that in the System.Web.Script.Serialization namespace.

So… let’s see it in action :

First – let’s built our object:

[Serializable()]
public class MyObject {
    public string StringField { get; set; }

    public int[] Numbers { get; set; }

    public String[] Names { get; set; }

}

Now the fun part – Convert to JSON

Step 1. Import the namespace

using System.Web.Script.Serialization;
Guess the namespace implies what assembly to import



Step 2. Let’s JSON it!

Your are going to LOVE how simple it is
JavaScriptSerializer o = new JavaScriptSerializer();
string json = o.Serialize(Images);

Is that all???

YES! that’s all. You just converted your object (custom, ADO, Linq object, or otherwise) to JSON!!

Files and photos storage, Filesystem vs DB

A question that I hear too frequently is “Whether I should save uploaded files, and photos to the DB or to my file-system”

First, let me give you my answer – FileSystem!!! 

… and here is why-

*  Though, wish modern DB engines such as MSSQL 2008, the access to either is as fast, storing your files on the DB requires an extra step of translating the query to a stream output. A step that can be easily avoided by letting the browser and the IIS handle the file fetching .

* Using the same repository to store your files and data will be very costly if you ever decide to improve your application performance by  moving photos to a CDN (Content Delivery Network).

* For shared hosting – usually your DB space is limited, storing the files there will increase the DB size significantly.

* The dreadful word, every DBA hates – bottleneck! A major consideration when designing a software is to keep the queries to a minimum. Thus reducing bottlenecks, and ensuring rapid execution of queries. Saving files to your DB will create too many necessary queries, and potentially bottlenecks.

* Caching – though you can cache data fetched from your DB as well, letting the IIS treat files as static will save you a lot of space, code and headache.

* On a more personal note – sometimes we build websites (mostly ecommerce, or photography) that requires images in different sizes (thumbs), re-creating and resizing on the fly may proof very costly, what we usually do is resize the photo upon the first request, and save it as a file in the filesystem, the second time a visitor request for that image in that size, the file already exists, so the IIS will deliver it as an ‘unchanged’ file, reducing execution time, use resources .

Would love to hear your thoughts…

How To: Start a process from c# code

Working for eMagid does require from time to time an original solution for a common, or more frequently non-common problem.

Problem at hand required us to build a Console Application, that intelligently crawl website, and scrap key information.
The follow up was to allow the admin to launch that application directly from their website.
There are three parts for the solution -

  1. Allowing the admin launch the console application
  2. Thread it! make sure that running the process doesn’t throw the website to a timeout .
  3. Ensuring that the application cannot be launch while a previous instance is still running.
Now let’s see how it should be done!



Running the process

In our case we had to provide the application with arguments, but that’s not always the case, so let’s create a method that can support either way.
All the following code does is run the application / process.

public void ExecuteApp(object o)
        {
            try
            {
                ProcessStartInfo ProcessInfo;
                System.Diagnostics.Process Process;

                ProcessInfo = new ProcessStartInfo("C:\MyApp.exe");

                // Check to see if there are arguments to pass along to the app
                if (o != null)
                {
                    ProcessInfo.Arguments = o.ToString();
                }

                // The console application will be launch, 'false' means that it will run without the user seeing a window popping up.
                ProcessInfo.CreateNoWindow = true;
                ProcessInfo.UseShellExecute = false;
                Process = System.Diagnostics.Process.Start(ProcessInfo);

            }catch
            {

            }

        }



Thread it

In this part we are making sure that the process runs as an independent thread (still inside the AppDomain, but it will allow us to continue using the site normally, without waiting for the ‘server side process’ to finish).

public void RunReader(object o)
{
    var ts = new ParameterizedThreadStart(ExecuteApp);

    (new Thread(ts)).Start(o);
}

public void ExecuteApp(object o)
        {
            try
            {
                ProcessStartInfo ProcessInfo;
                System.Diagnostics.Process Process;

                ProcessInfo = new ProcessStartInfo("C:\MyApp.exe");

                // Check to see if there are arguments to pass along to the app
                if (o != null)
                {
                    ProcessInfo.Arguments = o.ToString();
                }

                // The console application will be launch, 'false' means that it will run without the user seeing a window popping up.
                ProcessInfo.CreateNoWindow = true;
                ProcessInfo.UseShellExecute = false;
                Process = System.Diagnostics.Process.Start(ProcessInfo);

            }catch
            {

            }

        }



Last part – One is not necessarily a lonely number

So let’s make sure there is only one single instance of the process running at a time

Shall we start with adding a static flag?!

public static bool AppIsRunning = false;

And let’s put it all together.


        public static bool AppIsRunning = false;

        public void RunProcess(object o)
        {
            // Making sure the process is not already running.
            if(MyController.AppIsRunning)
                return ;

                var ts = new ParameterizedThreadStart(ExecuteReader);

                (new Thread(ts)).Start(o);
        }

        public void ExecuteProcess(object o)
        {
            try
            {
                // changing the 'current running' flag to true
                MyController.AppIsRunning = true;

                ProcessStartInfo ProcessInfo;
                System.Diagnostics.Process Process;

                ProcessInfo = new ProcessStartInfo("C:\MyApp.exe");

                // Check to see if there are arguments to pass along to the app
                if (o != null)
                {
                    ProcessInfo.Arguments = o.ToString();
                }

                // The console application will be launch, 'false' means that it will run without the user seeing a window popping up.
                ProcessInfo.CreateNoWindow = true;
                ProcessInfo.UseShellExecute = false;
                Process = System.Diagnostics.Process.Start(ProcessInfo);

                // Hey, that line wasn't there before !!
                // Well this is where we register the delegate to handle the event fired after the process finished its work.
                Process.Exited += new EventHandler(Process_Exited);
            }catch
            {
                // Obviously the process is no longer running.
                MyController.AppIsRunning = false;
            }

        }

        void Process_Exited(object sender, EventArgs e)
        {
            MyController.AppIsRunning = false;
        }