Friday, June 21, 2013

Saving changes not permitted

If you try to use the SQL Server designer for making changes to the table you just created, then you will get a dialog box that tells you that you cannot save the changes.One work around this issue is to disable the option "Prevent saving changes that require the table to be re-created".

To disable this option see the screenshots below.
































































HTH

Friday, May 31, 2013

asp.net - OutputCache, page level caching dynamically

I wanted to setup page level caching for one of the web application I was building since the content of the site came from a database and the content was not updated frequently.
Instead of using the declarative syntax
<%@ OutputCache Duration="20" VaryByParam="param1;param2"%> 
I use the following CachePage() method that enables caching based on configuration entries.

More on various caching techniques here (http://msdn.microsoft.com/en-us/library/y18he7cw(v=vs.100).aspx)

The following configuration entries help control how often the pages are to be cached and the query string parameter values that would invalidate the cache.

Web.Config

<add key="ENABLE_PAGE_CACHE" value="true"/>
<add key="CACHE_DURATION_UNIT" value="SECONDS"/><!--SECONDS,MINUTES,DAYS,HOURS-->
<add key="CACHE_DURATION_VALUE" value="10"/>
 <add key="CACHE_CLEAR_PARAMS" value="param1;param2"/><!--query string parameters separated by ; -->

ASPX Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CachingExample
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
       {
           if(!IsPostback)
          {
               //GetPageContentFromDB
               if(Convert.ToBoolean(ConfigurationManager.AppSettings["ENABLE_PAGE_CACHE"]) 
               CachePage();
            }
            
        }
    }
}

CachePage() Method

protected void CachePage()
        {
            try
            {
                string sCacheDurationUnit = ConfigurationManager.AppSettings["CACHE_DURATION_UNIT"];
                int iCacheDurationValue = Convert.ToInt32(ConfigurationManager.AppSettings["CACHE_DURATION_VALUE"]);
                string [] saCacheVaryParam = ConfigurationManager.AppSettings["CACHE_CLEAR_PARAMS"].Split(';');

                switch (sCacheDurationUnit)
                {
                    case "SECONDS":
                        Response.Cache.SetExpires(DateTime.Now.AddSeconds(iCacheDurationValue));
                        break;
                    case "MINUTES":
                        Response.Cache.SetExpires(DateTime.Now.AddMinutes(iCacheDurationValue));
                        break;
                    case "HOURS":
                        Response.Cache.SetExpires(DateTime.Now.AddHours(iCacheDurationValue));
                        break;
                    case "DAYS":
                        Response.Cache.SetExpires(DateTime.Now.AddDays(iCacheDurationValue));
                        break;
                    default:
                        Response.Cache.SetExpires(DateTime.Now.AddSeconds(iCacheDurationValue));
                        break;
                }
                
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetValidUntilExpires(true);

                foreach(string sCacheVaryParam in saCacheVaryParam)
                    Response.Cache.VaryByParams[sCacheVaryParam] = true;

            }
            catch (Exception ex)
            {
                LogError("Caching error " + _oSessionInfo.sMachineId + ".", _oSessionInfo, null, ex);
            }
        }

Monday, April 1, 2013

c# - StreamWriter Performance

I have written several programs that read data from raw input text files,extract required fields and write to tab delimited output text files.The files are usually few GB in size.I wanted to test the performance of the StreamWriter class and below are the results.

StreamWriter when used with a buffer size greater than the default buffer size of 1024 KB performed better.

Run 1: 350 MB Input file with default buffer


using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace FileWriterPerf

{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            try
            {
                using (StreamWriter oWriter = new StreamWriter(@"c:\File1.txt"))
                {
                    foreach (string sLine in File.ReadLines(@"c:\File.txt"))
                        oWriter.WriteLine(sLine);

                    oWriter.Flush();

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds);
            Console.WriteLine("RunTime " + elapsedTime);
            Console.Read();
        }
    }
}














Run 2: 350 MB Input file with 64MB buffer size
using (StreamWriter oWriter = new StreamWriter(@"c:\File1.txt",true,Encoding,ASCII,65536))


Run 3: 2 GB Input file with default buffer size
using (StreamWriter oWriter = new StreamWriter(@"c:\RawFile1.txt"))














Run 4: 2 GB Input file with 64MB buffer size
using (StreamWriter oWriter = new StreamWriter(@"c:\RawFile1.txt",true,Encoding,ASCII,65536))













Friday, March 29, 2013

c# - StreamReader vs File.ReadLines

Performance testing
Machine Configuration: Dell E6420 4 GB Ram 32- Bit i-7 Core (cores dont matter in this case.Parallel test for later)
Input File: 350+ MB tab delimited txt file

StreamReader


using System;
using System.Diagnostics;
using System.IO;

namespace FileReaderPerf

{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            try
            {
                  using (StreamReader oReader = new StreamReader(@"c:\File.txt"))
                  {
                      string sLine = oReader.ReadLine();
                      while (sLine != null)
                      {
                          Console.WriteLine(sLine);
                          sLine = oReader.ReadLine();
                      }
                  }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",

                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds);
            Console.WriteLine("RunTime " + elapsedTime);
            Console.Read();
        }
    }
}


























StreamReader using a larger buffer size

using (StreamReader oReader = new StreamReader(@"c:\File.txt",Encoding.ASCII,false,8092))
























File.ReadLines

using System;
using System.Diagnostics;
using System.IO;

namespace FileReaderPerf
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            try
            {
                 foreach(string sLine in File.ReadLines(@"c:\File.txt"))
                            Console.WriteLine(sLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;

            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds);
            Console.WriteLine("RunTime " + elapsedTime);
            Console.Read();
        }
    }
}


Friday, March 22, 2013

c# - Managed Parallelism,Threading using Task Parallel Library

One of my recent task was to migrate the .Net 2.0 code for processing a few thousand files.The original code used Managed Threading using ThreadPool. I wanted to update this code using .Net4.0 Task Parallel Library's Parallel.Foreach for this task.(Source: http://msdn.microsoft.com/en-us/library/ff477033.aspx)


Below is a very very trivial example.

In the code below I am getting all the folders in a given directory and processing them in parallel using Parallel.Foreach. I am using Environment.ProcessorCount(Source: http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx ) to get the total number of core processors on my server to control the total number of cores being used for processing.In the first example I am using all the 8 cores on my server.

using System;
using System.Threading.Tasks;
using System.IO;

namespace ManagedParallelism
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DirectoryInfo oDirectoryInfo = new DirectoryInfo(@"C:\MyFolder");
                Parallel.ForEach(oDirectoryInfo.GetDirectories(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (oDirectory) =>
                {
                        Console.WriteLine("TIMESTAMP: {0} INFO: PROCESSING DIRECTORY:{1}", DateTime.Now, oDirectory.Name);
                        ProcessDirectory(oDirectory);
                        Console.WriteLine("TIMESTAMP: {0} INFO: COMPLETED DIRECTORY:{1}", DateTime.Now, oDirectory.Name);
                        
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            Console.Read();
        }
        /// <summary>
        /// Function to process each of the sub directories
        /// </summary>
        /// <param name="oDirectory"></param>
        private static void ProcessDirectory(DirectoryInfo oDirectory)
        {
            //ToDo: Add code to process each sub directory in the Raw Files Folder
            //throw new NotImplementedException();
        }
    }
}
















By changing the above code to 

Parallel.ForEach(oDirectoryInfo.GetDirectories(), new ParallelOptions { MaxDegreeOfParallelism = (Environment.ProcessorCount - 4)}

parallelism can be limited to 4 cores.This value would ideally come from a configuration file.
















Task Parallel Library does make threading easy !

Monday, March 18, 2013

An error has occurred while trying to access the log file. Logging may not function properly - Visual Studio

Recently, I started getting this error when I opened the Visual Studio IDE. After searching for the cause of this error,I found that VMWare installation was the culprit (Actually its me who forgot to uncheck Install VS plugin while installation).VMware installation adds in a plugin to Visual Studio.You can either choose to reinstall VMWare and choose not install the plugin or disable the plugin in Visual Studio IDE.

See below screenshots to disable the plugin from Visual Studio (Note:Run Visual Studio as an admin)

The error























Fix











HTH

Tuesday, March 12, 2013

c# - Multi threading using TPL

In all my previous projects I have used ThreadPool class for managed threading.I wanted to migrate the code to .net 4.5 framework and was looking at Task Parallel Library for threading.Task parallel library makes threading ridiculously easy, especially when the threads do not share resources.
Below are two implementation of parallel processing using the Parallel.Invoke function


using System;
using System.Threading.Tasks;

namespace TaskParallelLibraryExample

{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.Invoke(() => RunMillionIterations1(1), () => RunMillionIterations2(2), () => RunMillionIterations3(3), () => RunMillionIterations4(4), () => RunMillionIterations5(5));
            Console.Read();
        }

        private static void RunMillionIterations1(int i)

        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}",iIndex,i.ToString());
            }
        }

        private static void RunMillionIterations2(int i)

        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}", iIndex, i.ToString());
            }
        }
        private static void RunMillionIterations3(int i)
        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}", iIndex, i.ToString());
            }
        }
        private static void RunMillionIterations4(int i)
        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}", iIndex, i.ToString());
            }
        }
        private static void RunMillionIterations5(int i)
        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}", iIndex, i.ToString());
            }
        }
    }
}



























using System;
using System.Threading.Tasks;

namespace TaskParallelLibraryExample

{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.Invoke(() => RunMillionIterations1(1), () => RunMillionIterations1(2), () => RunMillionIterations1(3), () => RunMillionIterations1(4), () => RunMillionIterations1(5));
            Console.Read();
        }

        private static void RunMillionIterations1(int i)

        {
            for (int iIndex = 0; iIndex < 1000000; iIndex++)
            {
                Console.WriteLine("Iteration:{0} Code:{1}",iIndex,i.ToString());
            }
        }
    }
}



























Below are the screenshots of the processor utilization by the library.I have noticed a significant increase in performance due to a higher and more efficient utilization of the machine resources by the task parallel library.



Monday, March 11, 2013

wpf client for wcf service

In one of the earlier posts I had listed out the steps to create a wcf service and a client to consume the service.The client for consuming the service was a windows console client.In this post I will show the steps to create a wpf client for the consuming the same wcf service.The post is located here http://virtuoso217.blogspot.com/2012/08/windows-communication-foundation.html

Open Visual Studio and select Windows Presentation Project from the list of projects



















In the MainWindow.xaml drag and drop the following controls
TextBlock1,TextBox1 for the seed wcf service is expecting
TextBlock2,TextBox2 for the dange wcf service is expecting
TextBlock3 to display the random number received from the service
Button to invoke the wcf service















In the next step, import the service proxy generated during the creation of the service i.e. proxy.cs and the the app.config with configuration settings (See the link posted at the beginning of this post for service proxy generation)
App.config settings below


<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_IRandomNumberGenerator" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
                    allowCookies="false">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Message">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="Windows" negotiateServiceCredential="true"
                            algorithmSuite="Default" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:12345/ServiceExample/Service/RandomNumberGenerator"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IRandomNumberGenerator"
                contract="IRandomNumberGenerator" name="WSHttpBinding_IRandomNumberGenerator">
                <identity>
                    <userPrincipalName value="myname@office.myoffice.com" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>



In the button click event instantiate the RandomNumberGeneratorClient class of the proxy and call the GetRandomNumber method.


private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                RandomNumberGeneratorClient oClient = new RandomNumberGeneratorClient();

                int iSeed = int.Parse(textBox1.Text);

                int iRange = int.Parse(textBox2.Text);

                textBox3.Text = "Random Number returned from the service: " + oClient.GetRandomNumber(iSeed, iRange);

            }
            catch 
            {
                textBox3.Text = "The service is not responding.Please make sure the service is online.";
            }
        }

Run the service and client.


 Client
Service
Client

Service