Wednesday, 9 December 2015

Generic Entity Framework CRUD Baseclass

Often a lot of time is done in Entity Framework by doing the same tedious mapping procedure to and from the database to POCO entities that are returned to the consumers, such as data contracts. Let us investigate a way to do this is in a more generic way. First, we create an interface for the CRUD operations we will support.

using System.Collections.Generic;

namespace SomeAcme.Data.EntityFramework
{

    public interface IDefaultDbCrudOperation<TEntity, TDataContract>
        where TEntity : class
        where TDataContract : class
    {

        List<TDataContract> GetAll();

        TDataContract InsertOrUpdate(TDataContract dataContract);

        bool Delete(TDataContract entity);

        List<TDataContract> InsertOrUpdateMany(List<TDataContract> dataContracts); 

    }

}

Next off, we need to provide the implementation itself, I choose here to support DbContext and not ObjectContext in EF:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using SomeAcme.Common;
using System.ComponentModel.DataAnnotations;

namespace Nonline.Data.EntityFramework
{

    public class BaseDataManager<TEntity, TDataContract> : IDefaultDbCrudOperation<TEntity, TDataContract> 
        where TEntity : class, new()
        where TDataContract : class
    {

        public bool Delete(TDataContract dataContract)
        {
            using (var ctx = new SvarrapportEntities())
            {
                var primaryKey = GetPrimaryKey(dataContract); 
                var entityFound = ctx.Set<TEntity>().Find(primaryKey);
                if (entityFound == null)
                    return false; 
                ctx.Set<TEntity>().Remove(entityFound);
                ctx.SaveChanges(); 
                return true;
            }
        }

        public List<TDataContract> GetAll()
        {
            using (var ctx = new SvarrapportEntities())
            {
                return ctx.Set<TEntity>().Project().To<TDataContract>().ToList();
            }
        }

        public TDataContract InsertOrUpdate(TDataContract dataContract)
        {
            using (var ctx = new SvarrapportEntities())
            {
                var primaryKey = GetPrimaryKey(dataContract);
                var foundEntity = ctx.Set<TEntity>().Find(primaryKey);
                bool isNew = foundEntity == null;

                foundEntity = Queryable.AsQueryable(new[] { dataContract }).Project().To<TEntity>().First();

                if (isNew)
                    ctx.Set<TEntity>().Add(foundEntity);

                ctx.SaveChanges();

                return Queryable.AsQueryable(new[] { foundEntity }).Project().To<TDataContract>().First();
            }
        }

        public List<TDataContract> InsertOrUpdateMany(List<TDataContract> dataContracts)
        {
            if (dataContracts == null)
                throw new ArgumentNullException("An empty list was provided!");
            var changesMade = new List<TDataContract>();
            foreach (var dc in dataContracts)
                changesMade.Add(InsertOrUpdate(dc)); //Simple logic in this case 
            return changesMade; 
        }

        private object GetPrimaryKey(TDataContract entity) 
        {
            PropertyDescriptor pDesc = TypeDescriptor.GetProperties(entity).Cast<PropertyDescriptor>().FirstOrDefault(p => p.HasAttribute<KeyAttribute>());
            if (pDesc == null)
                throw new InvalidOperationException("Provided datacontract must have one column with Key attribute!");

            var primaryKey = pDesc.GetValue(entity);
            return primaryKey; 
        }

    }

}



Note here that I use code from another article of mine, Automatic Mapping for Deep Objects in EF, where you see the Project() and To() methods. Here is that code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;

namespace SomeAcme.Data.EntityFramework
{

    /// <summary>
    /// Enables auto mapping features in Entity Framework
    /// </summary>
    /// <remarks>More information here: http://toreaurstad.blogspot.no/2015/02/automatic-mapping-for-deep-object.html </remarks>
    public static class QueryableExtensions
    {
        public static ProjectionExpression<TSource> Project<TSource>(this IQueryable<TSource> source)
        {
            return new ProjectionExpression<TSource>(source);
        }
    }

    public class ProjectionExpression<TSource>
    {
        private static readonly Dictionary<string, Expression> _expressionCache = new Dictionary<string, Expression>();

        private readonly IQueryable<TSource> _source;

        public ProjectionExpression(IQueryable<TSource> source)
        {
            _source = source;
        }

        public IQueryable<TDest> To<TDest>()
        {
            var queryExpression = GetCachedExpression<TDest>() ?? BuildExpression<TDest>();

            return _source.Select(queryExpression);
        }

        private static Expression<Func<TSource, TDest>> GetCachedExpression<TDest>()
        {
            var key = GetCacheKey<TDest>();

            return _expressionCache.ContainsKey(key) ? _expressionCache[key] as Expression<Func<TSource, TDest>> : null;
        }

        private static Expression<Func<TSource, TDest>> BuildExpression<TDest>()
        {
            var sourceProperties = typeof(TSource).GetProperties();
            var destinationProperties = typeof(TDest).GetProperties().Where(dest => dest.CanWrite);
            var parameterExpression = Expression.Parameter(typeof(TSource), "src");

            var bindings = destinationProperties
                                .Select(destinationProperty => BuildBinding(parameterExpression, destinationProperty, sourceProperties))
                                .Where(binding => binding != null);

            var expression = Expression.Lambda<Func<TSource, TDest>>(Expression.MemberInit(Expression.New(typeof(TDest)), bindings), parameterExpression);

            var key = GetCacheKey<TDest>();

            _expressionCache.Add(key, expression);

            return expression;
        }

        private static MemberAssignment BuildBinding(Expression parameterExpression, MemberInfo destinationProperty, IEnumerable<PropertyInfo> sourceProperties)
        {
            var sourceProperty = sourceProperties.FirstOrDefault(src => src.Name == destinationProperty.Name);

            if (sourceProperty != null)
            {
                return Expression.Bind(destinationProperty, Expression.Property(parameterExpression, sourceProperty));
            }

            var propertyNameComponents = SplitCamelCase(destinationProperty.Name);

            if (propertyNameComponents.Length >= 2)
            {
                sourceProperty = sourceProperties.FirstOrDefault(src => src.Name == propertyNameComponents[0]);
                if (sourceProperty == null)
                    return null;

                var propertyPath = new List<PropertyInfo> { sourceProperty };
                TraversePropertyPath(propertyPath, propertyNameComponents, sourceProperty);

                if (propertyPath.Count != propertyNameComponents.Length)
                    return null; //must be able to identify the path 

                MemberExpression compoundExpression = null;

                for (int i = 0; i < propertyPath.Count; i++)
                {
                    compoundExpression = i == 0 ? Expression.Property(parameterExpression, propertyPath[0]) :
                        Expression.Property(compoundExpression, propertyPath[i]);
                }

                return compoundExpression != null ? Expression.Bind(destinationProperty, compoundExpression) : null;
            }

            return null;
        }

        private static List<PropertyInfo> TraversePropertyPath(List<PropertyInfo> propertyPath, string[] propertyNames,
            PropertyInfo currentPropertyInfo, int currentDepth = 1)
        {
            if (currentDepth >= propertyNames.Count() || currentPropertyInfo == null)
                return propertyPath; //do not go deeper into the object graph

            PropertyInfo subPropertyInfo = currentPropertyInfo.PropertyType.GetProperties().FirstOrDefault(src => src.Name == propertyNames[currentDepth]);
            if (subPropertyInfo == null)
                return null; //The property to look for was not found at a given depth 

            propertyPath.Add(subPropertyInfo);

            return TraversePropertyPath(propertyPath, propertyNames, subPropertyInfo, ++currentDepth);
        }

        private static string GetCacheKey<TDest>()
        {
            return string.Concat(typeof(TSource).FullName, typeof(TDest).FullName);
        }

        private static string[] SplitCamelCase(string input)
        {
            return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim().Split(' ');
        }

    }

}


Now, all you have to do create a basic CRUD-supporting Entity Framework Manager is to inherit from the base class above and specify which entity and data contract type you will support. Note that the mapping utilitizes demands that you match your property names of the data contract with the columns in the database (e.g. entity properties), in addition to their types. Also, note that you can map deep objects by using a camel case convention, see the previously mentioned article for the details. I have added four methods:
  • GetAll()
  • InsertOrUpdate()
  • Delete()
  • InsertOrUpdateMany()
Note that you have to decorate ONE property of your data contracts with the System.ComponentModel.DataAnnotations.KeyAttribute! The attribute is found in the System.ComponentModel.DataAnnotations DLL. Some additional code:

 public class Singleton<T> where T : new()
    {
        private static readonly T instance;

        static Singleton()
        {
            instance = new T();
        }

        public static T Instance
        {
            get { return instance; }
        }

        private Singleton()
        {

        }

    } //class Singleton<T> 


using System.Configuration;
using System.Diagnostics;

namespace SomeAcme.Common.Logging
{

    /// <summary>
    /// Facade class to log information, warnings and exceptions to the event log
    /// </summary>
    /// <remarks>Based upon Microsoft Prism Logger Facade </remarks>
    public class EventLogFacade : ILoggerFacade
    {

        public const int MaxLogMessageLength = 32765;

        public string EventLogSourceName;

        public EventLogFacade()
        {
            EventLogSourceName = ConfigurationManager.AppSettings[Constants.EventLogSourceNameKey];
         
            if (!EventLog.SourceExists(EventLogSourceName))
            {
                EventLog.CreateEventSource(EventLogSourceName, Constants.Application);
            }
        }

        private void WriteEntry(string message, Category category, Priority priority)
        {
            int eventID = 0;
            if (!string.IsNullOrEmpty(message) && message.Length >= (MaxLogMessageLength))
                message = message.Substring(0, MaxLogMessageLength - 1); //Limit in how large Event Log Items can be 

            EventLog.WriteEntry(EventLogSourceName, message, GetEventLogEntryType(category), eventID, GetPriorityId(priority));
        }

        private static EventLogEntryType GetEventLogEntryType(Category category)
        {
            switch (category)
            {
                case Category.Debug:
                    return EventLogEntryType.Information;
                case Category.Exception:
                    return EventLogEntryType.Error;
                case Category.Info:
                    return EventLogEntryType.Information;
                case Category.Warn:
                    return EventLogEntryType.Warning;
                default:
                    return EventLogEntryType.Error;
            }
        }

        private static short GetPriorityId(Priority priority)
        {
            switch (priority)
            {
                case Priority.None:
                    return 0;
                case Priority.High:
                    return 1;
                case Priority.Medium:
                    return 2;
                case Priority.Low:
                    return 3;
                default:
                    return 0;
            }
        }

        public void Log(string message, Category category = Category.Exception, Priority priority = Priority.High)
        {
            WriteEntry(message, category, priority);
        }

    }

}



Sadly, lists inside data contracts are not being auto mapped for now. Otherwise, the code above should in theory make mapping back and forth between those data contracts and entities in EF way easier now! Good luck!

Wednesday, 25 November 2015

Locking and unlocking specific bytes of a file in C#

The following code shows a program that can lock and unlock specific bytes of file in C# using FileStream::Lock and FileStream::Unlock in System.IO. To test out that locking can protect designated bytes of a file, start up multiple instances of the program and try writing to the file after it has been locked. This will protect the file to be modified by other processes, which is handy if you want to ensure data integrity of files your system or application uses and expect to have a given contents and format. FileStream class allows us to work on files on a byte level and do detailed I/O operations on files in .NET.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestOutFileLocking
{

    class FStreamLock
    {

        static void Main(string[] args)
        {
            var uniEncoding = new UnicodeEncoding();
            string lastRecordText = "The last processed record number was: ";
            int textLength = uniEncoding.GetByteCount(lastRecordText);
            int recordNumber = 13;
            int byteCount = uniEncoding.GetByteCount(recordNumber.ToString());
            string tempString;

            using (var fileStream = new FileStream("Test#@@#.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                //Write the original file data. 
                if (fileStream.Length == 0)
                {
                    tempString = lastRecordText + recordNumber.ToString(); 
                    fileStream.Write(uniEncoding.GetBytes(tempString), 0, uniEncoding.GetByteCount(tempString));
                }

                //Allow the user to choose the operation. 
                char consoleInput = 'R'; 
                byte[] readText = new byte[fileStream.Length];
                while (consoleInput != 'X')
                {
                    Console.Write("\nEnter 'R' to read, 'W' to write, 'L' to " + "lock, 'U' to unlock, anything else to exit: ");

                    if ((tempString = Console.ReadLine()).Length == 0)
                    {
                        break;
                    }
                    consoleInput = char.ToUpper(tempString[0]);

                    switch (consoleInput)
                    {
                        //Read data from the file and 
                        //write it to the console 
                        case 'R':
                            try
                            {
                                fileStream.Seek(0, SeekOrigin.Begin);
                                fileStream.Read(readText, 0, (int) fileStream.Length);
                                tempString = new string(uniEncoding.GetChars(readText, 0, readText.Length));
                                Console.WriteLine(tempString);
                                recordNumber = int.Parse(tempString.Substring(tempString.IndexOf(':') + 2)); 

                            }
                            //Catch the IOException generated if the 
                            //specified part of the file is locked. 
                            catch (IOException e)
                            {
                                Console.WriteLine("{0}: The read " +
                                 "operation could not be performed " +
                                 "because the specified part of the " +
                                 "file is locked.",
                                 e.GetType().Name);
                                
                            }

                            break;

                            //Update the file. 
                        case 'W':

                            try
                            {
                                fileStream.Seek(textLength, SeekOrigin.Begin);
                                fileStream.Read(readText, textLength - 1, byteCount);
                                tempString = new string(uniEncoding.GetChars(readText, textLength - 1, byteCount));
                                recordNumber = int.Parse(tempString) + 1;
                                fileStream.Seek(textLength, SeekOrigin.Begin);
                                fileStream.Write(uniEncoding.GetBytes(recordNumber.ToString()), 0, byteCount);
                                fileStream.Flush(); 
                                Console.WriteLine("Record has een updated.");
                            }
                            catch (IOException e)
                            {
                                Console.WriteLine(
                                    "{0}: The write operation could not " +
                                    "be performed because the specified " +
                                    "part of the file is locked.",
                                    e.GetType().Name);
                            } //try-catch 
                            break;

                            //Lock the specified part of the file. 
                        case 'L':

                            try
                            {
                                fileStream.Lock(textLength - 1, byteCount);
                                Console.WriteLine("The specified part " + "of file has been locked.");
                            }
                            catch (IOException err)
                            {
                                Console.WriteLine("{0}: The specified part of file is" + " already locked.", err.GetType().Name);
                            } //try-catch 
                            break; 

                        case 'U':
                            try
                            {
                                fileStream.Unlock(textLength - 1, byteCount);
                                Console.WriteLine("The specified part of file has been unlocked.");

                            }
                            catch (IOException err)
                            {
                                Console.WriteLine("{0}: The specified part of file is " + "not locked by the current prcess.", err.GetType().Name);
                            }
                            break; 

                        default:
                            consoleInput = 'X';
                            break; 

                    } //switch 

                }

            } //using 



        }

    }

}


Thursday, 12 November 2015

Reading a text file in VB6 and putting the contents into an array

VB6 or Visual Basic 6.0 is not used in many new projects, as it is replaced by .NET. But sometimes you are assigned at work to read and further develop or migrate Legacy code. Let's look at some simple VB6 code. We first read the contents of a file and put each line into a string array. Then we add the items to a listbox control.

Private Sub Command3_Click()

 Dim someFileHandle As Integer
 Dim fileName As String
 Dim someStrings() As String
 
 someFileHandle = FreeFile

 fileName = App.Path + "\fox.txt"
 
 ReDim someStrings(1000) As String

 Open fileName For Input As #someFileHandle
 
 Dim lineNo As Integer
 
 Do Until EOF(someFileHandle)
  Input #someFileHandle, someStrings(lineNo)
  lineNo = lineNo + 1
 Loop
 
 ReDim Preserve someStrings(lineNo - 1) As String
  
 List1.Clear
  
 For x = 0 To lineNo - 1
  List1.AddItem someStrings(x)
 Next x

End Sub


First we get a file handle to the file we want to open. We declare an integer and use the FreeFile method to get a filehandle. We then use the Open function to open a file and assign the file handle. Note the use of the pound sign (#) here. We also declare a large string array, which is one dimensional. We use the ReDim Preserve Method to resize the array to save some memory space and preserve the content. We use the Input Method to put each line into an array element before this is done. Note the use of EOF here. We finally loop through the array and add each array item to a listbox control. So now you should have some basic overview how you can read a file in VB6 into an array structure and loop through its content. How neat is that!

Friday, 30 October 2015

Creating a socket-based echo server and client

Sockets in C# are flexible and efficient way of creating communication between a client and server. It supports many protocols and the code below shows one of the simplest scenarios for using Sockets - an echo server and client. Note that the code below will target TCP and Ipv4 protocol. Many users today have got a Ipv6 and/or Ipv4 address assigned.

Socket-based server

Create a new Console Application in Visual Studio and insert the following code into the Program.cs file.

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SynchronousSocketServer
{

    public class SynchronousSocketServer
    {

        //Incoming data from the client. 
        private static string _data;

        public static void StartListening()
        {
            //Data buffer for incoming data. 
            // ReSharper disable once RedundantAssignment

            //Establish the local endpoint for the socket.
            //Dns.GetHostName returns the name of the host running the application
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList.First(a =< a.AddressFamily == AddressFamily.InterNetwork);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11004);

            //Create a TCP/IP socket 
            var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //Bind the socket to the local endpoint and listen for incoming connections 
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                //Start listening for connections 
                while (true)
                {
                    Console.WriteLine("Waiting for connection ...");
                    //Program is suspended while waiting for an incoming connection. 
                    Socket handler = listener.Accept();
                    _data = null;

                    //An incoming connection needs to be processed. 
                    while (true)
                    {
                        var bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        _data += "\n" + Encoding.Unicode.GetString(bytes, 0, bytesRec);
                        if (_data.IndexOf("<EOF>", StringComparison.Ordinal) > -1)
                        {
                            break;
                        }
                        //Show the data on the console. 
                        byte[] msg = Encoding.Unicode.GetBytes(_data);
                        handler.Send(msg);
                    }

                    Console.WriteLine("Text received: {0}", _data);

                  
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
            } //try-catch 

            Console.WriteLine("\nPress ENTER to continue ...");
            Console.Read();
        }

        // ReSharper disable once UnusedParameter.Local
        static int Main(string[] args)
        {
            StartListening();
            return 0;
        }

    }

}

Socket-based client

Create a new Console application in Visual Studio. Add the following code into the Program.cs file:

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SynchronousSocketClient
{

    public class SynchronousSocketClient
    {

        public static void StartClient()
        {
            //Data buffer for incoming data. 
            byte[] bytes = new byte[1024];

            //Connect to a remote device. 
            try
            {
                //Establish the remote endpoint for the socket
                //This example uses port 11000 on the local computer 
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList.First(a =< a.AddressFamily == AddressFamily.InterNetwork);
                IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 11004);

                //Create a TCP/IP socket. 
                var sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //Connect the socket to the remote endpoint. Catch any errors. 
                try
                {
                    sender.Connect(remoteEndPoint);

                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint);

                    while (true)
                    {
                        Console.WriteLine("Enter text, type <EOF> to exit:");

                        //Encode the data string into a byte array 
                        string enteredText = Console.ReadLine() ?? "<EOF>"; 
                        byte[] msg = Encoding.Unicode.GetBytes(enteredText);

                        //Send the data through the socket. 
                        int bytesSent = sender.Send(msg);
                        Console.WriteLine("Sent {0} bytes over the network", bytesSent);

                        //Receive the response from the remote device. 
                        int bytesReceived = sender.Receive(bytes);
                        Console.WriteLine("Echoed test = {0}", Encoding.Unicode.GetString(bytes, 0, bytesReceived));

                        if (enteredText.IndexOf(">EOF<", StringComparison.CurrentCultureIgnoreCase) < -1)
                        {
                            break;
                        }

                    }

                    //Release the socket. 
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException err)
                {
                    Console.WriteLine("ArgumentNullException : {0}", err.Message);
                }
                catch (SocketException err)
                {
                    Console.WriteLine("SocketException : {0}", err.Message);
                }
                catch (Exception err)
                {
                    Console.WriteLine("Exception : {0}", err.Message);
                }

            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
            } //try-catch 

        }

        // ReSharper disable once UnusedParameter.Local
        static int Main(string[] args)
        {
            StartClient();
            return 0;
        }

    }

}

Wednesday, 28 October 2015

Creating an Azure WebJob and persisting data to an Azure Storage table

This article will describe how you can create an Azure WebJob and persist some data to an Azure Storage table. First of, head over to the portal for Azure using Internet Explorer and log in using your subscription: Azure Portal Select Web Apps in the left menu and click Add. Enter a name for your Web App and select your Subscription, Resource Group and App Service plan/Location and hit Create. Afterwards, select the Web Apps in the left menu again and select the Web App you just created. Use the Settings and choose WebJobs. We are going to create a webjob here using Visual Studio, note that the WebJobs link will list your webjobs.
Next, create in VS 2013 or newer a new ASP.NET Web Application using File and New Project in the Main Menu of VS. Choose an Empty web application. Do the following next:
  • Right click the web project
  • Choose Add
  • Add ASP.NET folder
  • App_Data
    • Select Solution Explorer and choose the Solution and right-click and add a new project which is Console Application. Also create subfolder jobs, triggered and web-job-helloworldv5. We will drop the compiled contents of the Console Application project we will add next. Let's add two app settings in the Console Application app.config file:


      
      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
        <appSettings>
          <add key="StorageAccount" value="INSERT_STORAGE_ACCOUNT" />
          <add key="StorageKey" value="INSERT_STORAGE_KEY" />
        </appSettings>
          <startup> 
              <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
          </startup>
      </configuration>
      
      
      Obviously, we need to put into the two appsettings the storage account and storage primary key. In the left menu of Azure Portal select New and choose Data+Storage and choose Storage Account. This is needed to get started with Blobs, Tables and Queues and Choose Create Back in the left menu again, choose Browse and then Storage accounts (classic). Now we need the necessary connection details to this Storage Accounts. Select in the right menu Settings the link Keys. Copy the values for Storage account name and Primary Access Key. Add these two values into the two app settings earlier noted. Now we just need to make a simple WebJob and persist some data into Azure Storage Table. Let's calculate the first 100 prime numbers and then add these numbers to a Azure Storage Table. Into the Main method of Program.cs of the Console application we add the following code:
      
       static void Main(string[] args)
              {
                  Console.WriteLine("Starting prime number calculation..");
                  var primes = new List<int>(); 
                  foreach (var n in Enumerable.Range(0, 100))
                  {
                      int numberToCheck = (n*2) + 1;
                      bool isPrimes = IsPrime(numberToCheck);
                      if (isPrimes)
                      {
                          primes.Add(numberToCheck);
                      }
                  }
      
                  StoreToAzureTableStorage(primes, "primenumbersfound");
              }
      
              public static bool IsPrime(long num)
              {
                  for (long j = 2; j <= Math.Sqrt(num); j++) // you actually only need to check up to sqrt(i)
                  {
                      if (num%j == 0)
                      {
                          return false;
                      }
                  } //for
      
                  return true;
              }
      
      
      We need some plumbing code to get our CloudTableClient to work against our Azure Table:
      
      /// 
              /// Returns an instance of a Azure Cloud Table client 
              /// 
              /// 
              public static CloudTableClient GetCloudTableClient()
              {
                  string accountName = ConfigurationManager.AppSettings["StorageAccount"];
                  string accountKey = ConfigurationManager.AppSettings["StorageKey"];
      
                  if (string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(accountKey))
                      return null; 
      
                  try
                  {
                      var credentials = new StorageCredentials(accountName, accountKey); 
                      var cloudStorageAccount = new CloudStorageAccount(credentials, useHttps: true);
                      CloudTableClient client = cloudStorageAccount.CreateCloudTableClient();
                      return client;
                  }
                  catch (Exception ex)
                  {
                      return null;
                  }
              }
      
      
      Next we commit the data to our Azure Storage Table:
      
         public static void StoreToAzureTableStorage(List primes, string tableName)
              {
                  
                  try
                  {
      
                      CloudTableClient client = GetCloudTableClient();
                      CloudTable table = client.GetTableReference(tableName);
                      table.CreateIfNotExists();
      
                      foreach (int prime in primes)
                      {
                          var primeEntity = new PrimeNumberEntity(prime);
                          var insertOperation = TableOperation.Insert(primeEntity);
                          table.Execute(insertOperation);
                      }
      
      
                      var query = new TableQuery();
                      var primesFound = table.ExecuteQuery(query).OrderBy(p => int.Parse(p.RowKey)).ToList();
      
                      foreach (PrimeNumberEntity pf in primesFound)
                      {
                          Console.WriteLine(pf);
                      }
      
                  }
      
                  catch (Exception ex)
                  {
      
                      Console.WriteLine(ex);
      
                  }
      
      
                  Console.WriteLine("Done... press a key to end.");
      
              }
      
      
      We can now invoke our WebJob from the Azure portal:




      We can choose Web Apps and then our WebApp and next in the right menu WebJobs. Note that we can pin our WebApp to our Dashboard for quicker navigation using the pin symbol in Azure Portal. Now choose the WebJobs and right click and choose Run.



      We can inspect the data we inserted using Azure Storage Explorer. Download a Visual Studio 2013 solution with code above below, you will need create a Web App and a Storage account in Azure Portal and insert the necessary app settings as noted to run the example: Download VS 2013 Solution file (.zip) [69 MB]

Friday, 9 October 2015

Switchbased delay with Dispatcher in WPF

Extended my DispatcherUtil class today, with SwitchBasedDelay! Example of calling the new method, note we use a fixed Guid in this case to "group" calls into a logical switch:

 DispatcherUtil.SwitchbasedDelayedInvokeAction(Guid.Parse(@"{4E101F98-31F3-4E19-B18B-2820AEA60A1B}"), () =>
     {
      PublishEvent<ProcedureFreeTypeTextChangedEvent, ProcedureFreeTypeTextChangedEventArg>(
       new ProcedureFreeTypeTextChangedEventArg
        {
          FreshId = Context.CurrentOperationalUnit.FreshId,
          ProcedureCode = Model.ProcedureTypeFreeText,
          OperationId = Model.OperationId
        });
      }, 2000);


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;

namespace SomeAcme.SomePackage
{

    /// <summary>
    /// Contains helper methods for dispatcher operations 
    /// </summary>
    public static class DispatcherUtil
    {

        private static readonly List<DelayedAction> ActionsRegistered = new List<DelayedAction>();

        private static readonly Dictionary<Guid?, bool> SwitchDelays = new Dictionary<Guid?, bool>();

        /// <summary>
        /// Executes an action passed into this method by a timeout measured in millisecond in a switch-based manner. 
        /// </summary>
        /// <param name="keyToken">A key token (Guid) to identity the switch (basic grouping)</param>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority">Priority of the dispatcher operation</param>
        /// <returns></returns>
        public static bool SwitchbasedDelayedInvokeAction(Guid keyToken, Action executeAction, int timeOut,
            DispatcherPriority priority = DispatcherPriority.Background)
        {
            if (SwitchDelays.ContainsKey(keyToken) && SwitchDelays[keyToken])
                return false; //do not execute, already in progress 

            SwitchDelays[keyToken] = true;

            DelayedInvokeAction(executeAction, timeOut, priority, keyToken);
            return true; //delayed action sent off
        }

        /// <summary>
        /// Executes an action passed into this method by a timeout measured in milliseconds
        /// </summary>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority"></param>
        ///    /// <param name="keyToken">A key token to identity the switch (basic grouing). Will be used as a tag on the DispatcherTimer</param>
        public static bool DelayedInvokeAction(Action executeAction, int timeOut, DispatcherPriority priority = DispatcherPriority.Background, Guid? keyToken = null)
        {
            var delayedAction = new DelayedAction(executeAction, timeOut, keyToken);
            ActionsRegistered.Add(delayedAction);
            DispatcherTimer dtimer = new DispatcherTimer(priority);

            dtimer.Interval += new TimeSpan(0, 0, 0, 0, timeOut);
            dtimer.Tag = delayedAction.ExecuteGuid;
            dtimer.Tick += DelayedInvokeTimerTick;
            dtimer.IsEnabled = true;
            dtimer.Start();

            return true;
        }

        private static void DelayedInvokeTimerTick(object sender, EventArgs e)
        {
            var dtimer = sender as DispatcherTimer;
            if (dtimer != null)
            {
                dtimer.IsEnabled = false;
                dtimer.Stop();
                dtimer.Tick -= DelayedInvokeTimerTick; //unsubscribe
                Guid targetActionGuid = (Guid)dtimer.Tag;

                DelayedAction delayedAction = ActionsRegistered.Single(a => a.ExecuteGuid == targetActionGuid);
                delayedAction.ActionToExecute(); //now execute the action 
                ActionsRegistered.Remove(delayedAction);

                if (dtimer.Tag != null)
                {
                    Guid? keyToken = dtimer.Tag as Guid?; 
                    if (SwitchDelays.ContainsKey(keyToken))
                    {
                        SwitchDelays.Remove(keyToken); //remove the switch 
                    } //if 
                } //if 

                // ReSharper disable once RedundantAssignment
                dtimer = null; //ensure free up dispatcher timer - do not starve threading resources 
            } //if 
        }

        /// <summary>
        /// Invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool InvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        /// <summary>
        /// Asynchronously invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool BeginInvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        public static void AsyncWorkAndUiThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate)
        {
            // ReSharper disable once UnusedAnonymousMethodSignature
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                T resultAfterThreadWork = threadWork();
                // ReSharper disable once UnusedAnonymousMethodSignature
                // ReSharper disable once UnusedAnonymousMethodSignature
                currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate {
                    guiUpdate(resultAfterThreadWork);
                }), resultAfterThreadWork);

            });
        }

    }
}



Wednesday, 7 October 2015

DispatcherUtil - Elegant WPF Dispatcher programmatic handling

Don't you hate it when you need to tweak the Dispatcher to do what you expect and respect the main GUI thread can only work with GUI controls rule? Wouldn't you like to have some code that just does the things you want to do with the Dispatcher without getting the dreaded InvalidOperationException? Well here is the DispatcherUtil I use to achieve this!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;

namespace SomeAcme.SomePackage
{

    /// <summary>
    /// Contains helper methods for dispatcher operations 
    /// </summary>
    public static class DispatcherUtil
    {

        private static readonly List<DelayedAction> actionsRegistered = new List<DelayedAction>();


        /// <summary>
        /// Executes an action passed into this method by a timeout measured in milliseconds
        /// </summary>
        /// <param name="executeAction">Action to execute</param>
        /// <param name="timeOut">The timeout to wait before executing (in milliseconds)</param>
        /// <param name="priority"></param>
        public static bool DelayedInvokeAction(Action executeAction, int timeOut, DispatcherPriority priority = DispatcherPriority.Background)
        {
            var delayedAction = new DelayedAction(executeAction, timeOut);
            actionsRegistered.Add(delayedAction);
            DispatcherTimer dtimer = new DispatcherTimer(priority); 
            dtimer.Interval += new TimeSpan(0, 0, 0, 0, timeOut);
            dtimer.Tag = delayedAction.ExecuteGuid;
            dtimer.Tick += DelayedInvokeTimerTick;
            dtimer.IsEnabled = true;
            dtimer.Start();

            return true;
        }

        private static void DelayedInvokeTimerTick(object sender, EventArgs e)
        {
            var dtimer = sender as DispatcherTimer;
            if (dtimer != null)
            {
                dtimer.IsEnabled = false;
                dtimer.Stop();
                dtimer.Tick -= DelayedInvokeTimerTick; //unsubscribe
                Guid targetActionGuid = (Guid)dtimer.Tag;

                DelayedAction delayedAction = actionsRegistered.Single(a => a.ExecuteGuid == targetActionGuid);
                delayedAction.ActionToExecute(); //now execute the action 
                actionsRegistered.Remove(delayedAction); 

                if (dtimer != null)
                    dtimer = null; //ensure free up dispatcher timer - do not starve threading resources 
            } //if 
        }

        /// <summary>
        /// Invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool InvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        /// <summary>
        /// Asynchronously invokes an action on the current dispatcher, used to execute operations on the GUI thread
        /// </summary>
        /// <param name="executeAction">The action to execute, pass in e.g. delegate { --code lines goes here } </param>
        /// <param name="dispatcherPriority">The priority to give the action on the thread (signal to the WPF messaging queue). Default is background.</param>
        /// <returns>Returns true when the action was dispatched</returns>
        /// <remarks>Default priority is DispatcherPriority.Background</remarks>
        public static bool BeginInvokeAction(Action executeAction, DispatcherPriority dispatcherPriority = DispatcherPriority.Background)
        {
            Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
            {
                executeAction();
            }), dispatcherPriority);
            return true;
        }

        public static void AsyncWorkAndUIThreadUpdate<T>(Dispatcher currentDispatcher, Func<T> threadWork, Action<T> guiUpdate)
        {
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                T resultAfterThreadWork = threadWork();
                currentDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action<T>(delegate(T result)
                {
                    guiUpdate(resultAfterThreadWork);
                }), resultAfterThreadWork);

            });
        }

    }
}


Enjoy the code! It has helped me many times when I want to do work in other threads or using Tasks with TPL!

Displaying math in webpages with MathJax

MathJax is a powerful Library for displaying math in webpages. It is possible to write mathematical symbols and equations with MathML syntatax or LateX syntax, and even other formats. In this article, LateX will be used. LaTeX has got all the necessary support for writing mathematical symbols and equations, note though that this does not mean everything in LateX is supported in browsers through MathJax. In this article, only simple examples will be used. First off, to use MathJax, just add a Reference to the MathJax JavaScript Library in the <HEAD>HEAD section of Your HTML page:

<html>
<head>
<script type="text/javascript"
  src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
  tex2jax: {
    inlineMath: [['$','$'], ['\\(','\\)']],
    processEscapes: true
  }
});

</script>

</head>

Now we are ready to insert some mathematical symbols and Equations on our web page!
Let's first add the Quadratic Equation:

<font size="+2">
Quadratic equation:

$$ \begin{array}{*{20}c} { x = \frac{ -b \pm \sqrt {b^2 - 4ac}}{2a} } & {{\rm{when}}} & {ax^2 + bx + c = 0} \\ \end{array} $$ </font>

And let us also list the Greek alphabet: <div style="color:charcoal;width:300px;background:white"> <font size="+2"> $$ \\ Greek \hspace{2mm} Alphabet. \\ letter - small symbol - large symbol \\ alpha \hspace{1mm} \alpha \hspace{2mm} A \hspace{2mm} \cdotp beta \hspace{1mm} \beta \hspace{2mm} B \hspace{2mm} \cdotp gamma \hspace{1mm} \gamma \hspace{2mm} \Gamma \hspace{2mm} \cdotp delta \hspace{1mm} \delta \hspace{2mm} \Delta \hspace{2mm} \cdotp epsilon \hspace{1mm} \epsilon \hspace{2mm} E \hspace{2mm} \cdotp zeta \hspace{1mm} \zeta \hspace{2mm} Z \hspace{2mm} \cdotp \\ eta \hspace{1mm} \eta \hspace{2mm} H \hspace{2mm} \cdotp theta \hspace{1mm} \theta \hspace{2mm} \Theta \hspace{2mm} \cdotp iota \hspace{1mm} \iota \hspace{2mm} I \hspace{2mm} \cdotp kappa \hspace{1mm} \kappa \hspace{2mm} K \hspace{2mm} \cdotp lambda \hspace{1mm} \lambda \hspace{2mm} \Lambda \hspace{2mm} \cdotp mu \hspace{1mm} \mu \hspace{2mm} M \hspace{2mm} \cdotp nu \hspace{1mm} \nu \hspace{2mm} N \hspace{2mm} \cdotp xi \hspace{1mm} \xi \hspace{2mm} \Xi \hspace{2mm} \cdotp omicron \hspace{1mm} \omicron \hspace{2mm} O \hspace{2mm} \cdotp \\ pi \hspace{1mm} \pi \hspace{2mm} \Pi \hspace{2mm} \cdotp rho \hspace{1mm} \rho \hspace{2mm} P \hspace{2mm} \cdotp sigma \hspace{1mm} \sigma \hspace{2mm} \Sigma \hspace{2mm} \cdotp tau \hspace{1mm} \tau \hspace{2mm} T \hspace{2mm} \cdotp upsilon \hspace{1mm} \upsilon \hspace{2mm} Y \hspace{2mm} \cdotp phi \hspace{1mm} \phi \hspace{2mm} \Phi \hspace{2mm} \cdotp chi \hspace{1mm} \chi \hspace{2mm} X \hspace{2mm} \cdotp psi \hspace{1mm} \psi \hspace{2mm} \Psi \hspace{2mm} \cdotp omega \hspace{1mm} \omega \hspace{2mm} \Omega \hspace{2mm} \cdotp $$ </font> </div>
As you have noted, we use the $$ .. $$ enclosing syntax to insert our LateX code that constitute the mathematical symbols and Equations. MathJax is really powerful! You can display triple integrals, matrices and vector Equations - both elementary, Intermediate and Advanced Math can be displayed on a web page. The web site of MathJax is available here: MathJax webiste - MathJax.org Ok, so how does the code above look like?


Displayed in IFRAME next - the source is: http://toreaurstad.ddns.net/website/index2.htm