Wednesday, August 15, 2012

Windows CE for Mobile - Retrieve values from configuration file

As you already know, Windows CE doesn't support Configuration Manager library of .NET Framework.
And, if you need store some configuration values regarding your application, you need find way to retrieve this values by yourself.

I find some simple and quick way to do so:

I am using my Serialization class (see previous post) to deserialize  my configuration model from XML (config file):


public static PrintingConfigurationModel GetTJPrinterCEConfiguration()
{
     //Looking for path of config file
     var mSettingsPath =  Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()
                                                                                                                                       .GetName()
                                                                                                                                       .CodeBase);
     mSettingsPath += @"\Settings.xml";

     if (!File.Exists(mSettingsPath))
     {
           throw new FileNotFoundException(mSettingsPath + " could not be found.");
     }
        
    var printingConfigurationModel = SerializerUtils.Deserialize<PrintingConfigurationModel>(mSettingsPath)   
                                                                                                                    as PrintingConfigurationModel;

    return printingConfigurationModel;

}

My Configuration Model:


[Serializable()]
    public class PrintingConfigurationModel
    {
        [System.Xml.Serialization.XmlElement("PrinterIp")]
        public string PrinterIp { get; set; }

        [System.Xml.Serialization.XmlElement("PrinterPort")]
        public int PrinterPort { get; set; }

        [System.Xml.Serialization.XmlElement("PrintingImagePath")]
        public string PrintingImagePath { get; set; }

        [System.Xml.Serialization.XmlElement("JpgPrintingImagePath")]
        public string JpgPrintingImagePath { get; set; }
    }


And for the End :-), configuration file (xml):


<?xml version="1.0" encoding="utf-8" ?>
<PrintingConfigurationModel xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <PrinterIp>10.190.16.25</PrinterIp>
  <PrinterPort>9100</PrinterPort>
  <PrintingImagePath>\Program Files\Retalix\HandHeldOffice\PrintData\SavedReport.bmp</PrintingImagePath>
  <JpgPrintingImagePath>
           \Program Files\Retalix\HandHeldOffice\PrintData\JpgSavedReport.jpg
  </JpgPrintingImagePath>
</PrintingConfigurationModel>


Hope this simple thing helps !

Wednesday, June 27, 2012

Sending big size (>2MB) file over WCF (bulking)

If you trying to send big file over WCF you need config  file on server and client, depends on direction.

But there is another way to do this - divide your file (pfd, txt, word and etc.) to packages  (bulks)

Following example in C# with WCF:

Client Sending file to server:


 var bulkSize = 2000000; //in kb
 var stillSize = originalPdf.Length; //original file size
 var globalCounter = 0;
 while (stillSize > 0)
 {                
    var newActualBulkSize = stillSize > bulkSize ? bulkSize : stillSize;
    var bulkArray = new byte[newActualBulkSize];
    for (var i = 0; i < (newActualBulkSize); i++)
    {
       bulkArray[i] = originalPdf[globalCounter++]; //creating small bulks of file
    }
                
     //sending to server small parts
     clientReference.TransferDocToServer(new DataTransferObject() 
                                              { DocBase64Array = bulkArray }, 
                                    stillSize > bulkSize ? false : true, originalPdf.Length);
 
     
stillSize -= bulkSize;
     
 }                        


Server Side Code:

private static readonly Dictionary<intbyte[]> Bulks = new Dictionary<intbyte[]>();
private static int _key; 

public void TransferDocToServer(DataTransferObject dataTransferObject, bool finishTransfer, int originalSize)
{            
    Bulks.Add(_key++, dataTransferObject.DocBase64Array);
    if (finishTransfer)
    {
       var originalPdf = CreatePdfAgain(originalSize);
       CreatePdfOnFileSystem(originalPdf);
       ClearObjects();               
    }                       
}
 
private static void ClearObjects()
{
    Bulks.Clear();
    _key = 0;
}
 
private static void CreatePdfOnFileSystem(byte[] originalPdf)
{
   using (Stream stream = new FileStream("c:/newFile.pdf"FileMode.Create))
   {
       stream.Write(originalPdf, 0, originalPdf.Length);
   }     
}

private byte[] CreatePdfAgain(int originalSize)
{
   var resultIndex = -1;
   var resultArrayForPdf = new byte[originalSize];
   foreach (var bytesBulk in Bulks)
   {
       foreach (byte t in bytesBulk.Value)
       {
           resultArrayForPdf[++resultIndex] = t;
       }
   }
 
   return resultArrayForPdf;
}

Generics Serializer with file saving on file system


Generics Serializer with file saving on file system and in String

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Retalix.Client.HandHeldTraderJoesOffice.Model
{
    public class SerializerUtils
{
             public static object Deserialize<T>(string serializeableFilePath)
    {           
             var serializer = new XmlSerializer(typeof(T));
             var reader = new StreamReader(serializeableFilePath);
            T result = (T)serializer.Deserialize(reader);
            reader.Close();           
             return result;
     }
       
     public static object Serialize(T data, string serializeableFilePath)
     {           
          var serializer = new XmlSerializer(typeof(T));                 
          var writer = new StreamWriter(serializeableFilePath);
          serializer.Serialize(writer, data);           
          writer.Close();           
          return result;
      }
    }
}

-----------------------------------------------------------------------------------------------------------------



using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using BroadwayBox.SeatingChart.Common;

namespace BroadwayBoxSeattingChartWS.Serialization
{
    public class SerializerUtils
    {
        public static string Serialize<T>(T data)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                TextWriter writer = new StringWriter();
                serializer.Serialize(writer, data);
                return writer.ToString();            
            }
            catch (Exception exception)
            {
                return string.Empty;
            }            
        }

        public static T Deserialize<T>(string data)
        {
            var serializer = new XmlSerializer(typeof(T));
            TextReader reader = new StringReader(data);
            return (T)serializer.Deserialize(reader);
        }

        public static string SerializeWithXmlTextWriter(Chart chart)
        {            
            var ms = new MemoryStream();
            using (var writer = new XmlTextWriter(ms, Encoding.UTF8))
            {
                chart.WriteToXml(writer);

                return Encoding.UTF8.GetString(ms.ToArray());
            }                     
        }
    }
}

Wednesday, February 15, 2012

Template Method Design Pattenr

Template method design pattern more useful after observer, visitor, command, factory, decorator , single tone and of course facade and adapter :-))), but anyway I think it very nice and not so simple to understand.
Those two reasons, why I would like show this pattern in VERY simple way, I hope it will helps understand this pattern in couple of minutes:

OK, first of all short explanation:

Suppose, we want to prepare for us and tea for friend. We will boil water and after put coffee and tea into the cups. So, we will perform 4 actions:

1. - boil water and put into the cup_1
2. - boil water and put into the cup_2
3. - put coffee into the cup_1
4. - put tea into the cup_2

We have 4 methods and 2 same actions at all (1&2)

So, we can create template method for 1 & 2.
OK, Lets see some code in order to understand it simple:


using System;
 
namespace TemplateMethodPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            var tea = new Tea();
            tea.Create();
 
            var cofee = new Cofee();
            cofee.Create();
 
            Console.ReadLine();
        }
    }
 
    public abstract class TemplateCreateDrink
    {
        public void Create()
        {
            BoilWater();
            AddSomethink();
        }
 
        public void BoilWater()
        {
            Console.WriteLine("Boil Water");    
        }
 
        public abstract void AddSomethink();
    }
 
    public class TeaTemplateCreateDrink
    {        
        public override void AddSomethink()
        {
            Console.WriteLine("Add Tea to Water");
        }
    }
 
    public class Cofee : TemplateCreateDrink
    {
        public override void AddSomethink()
        {
            Console.WriteLine("Add Cofee to Water");
        }
    }    
}


And...we create template pattern in order to prepare tea and coffee :)



Tuesday, January 10, 2012

Software Basic Architecture

In this post I would like to explain some basic software architecture. If you going to build your new application from scratch and you decide to build application that will be right OO designed, following architecture can helps you in.



Doesn't matter, you going to build Winform, WPF or Web application the basic architecture still to be same.

Before you going to read this post, I suggest you to be familiar with Dependency Injection (see my previous posts) and MVC and / or MVVM pattern.

1. Represents Client View - it's may be HTML, WPF or Winform application. This part of application not so 'interesting' for us and not an issue in this post. After some interaction accured with user and request has been sent to the server (in case of Web application) we suppose to come to Controller / CommandHandler or some else object that responsible to get response from client and decide what going on with. Let's take example of currency calculator. In this case we got some data model from client, like: 

Pseudo Code:

class CurrencyModel:
{
     string currencyCodeFrom = 'USD', 
     string currencyCodeTo = 'EUR'
     decimal quantityToConvert = 100.0
     decimal quantityAfterConversion = 0.0
}

OK, we have our first model, that arrived to  our first layer (number 3 on pic.1)

First of all we would like to save current state of our main model, before we going to change it or may be not, any way. 
We need to create DataModelManager that will holds all Models that inherit from  IMainCurrencyModel that inherit from IDataModel interface all application session or until we will delete it from. 

MainCurrencyModel has method Update(CurrencyModel currencyModel):

class MainCurrencyModel
{
     public CurrencyModel _currencyModel {get; set;}

     Update(CurrencyModel currencyModel)
     {
           _currencyModel = currencyModel;
     }
}

So, now we have data to going on to service. Now we need to get service provider in order to refer to service and get back quantityAfterConversation. Suppose,  service wait from us currencyCodeFrom, currencyCodeTo and  quantityToConvert and after perform all works for us return us in response quantityAfterConversion.

OK, let's assume that we have two service providers (or maybe more) of currency conversions rates. In this case we don't want create service provider with 'new' and we will user service manager build for us list of all service providers we have define in our application scope and let to Business Logic to decide which one to use.
While creating service provider object we must inherit from IServiceProvider. While application starts ServiceManager running and imports [imports many] all objects inherits from IServiceProvider (using MEF dependancy injection framework).

Now we need get from a list of providers one we need to use in our case, let's say we will use 'ChippestConversionServiceProvider':

pseudo code:

//let's save our current DataModel
var mainDataModel = DataModelManager<MainDataModel>();
mainDataModel.Update(CurrencyModel);

//get our serviceProvider we need according our Business Logic 
var serviceProviders = ServiceManager.GetServiceProvider<ChippestConversionServiceProvider>();
serviceProvider.GetQuantityAfterConversion(mainDataModel );

In case you need to use another serviceProvider you can take from all list of serverProviders:

var serviceProviders = ServiceManager.GetServiceProvider();

provider you need to use according to specific logic:

Example:

if(currencyCodeFrom  == 'USD')
   var serviceProvider = serviceProvider.Where(x=>x.GetType == 'ChippestConversionServiceProvider')
else
  var serviceProvider = serviceProvider.Where(x=>x.GetType == 'RapidConversionServiceProvider')

Of course all providers must realize GetQuantityAfterConversion() method.

OK, we finished explanation of 3,4,9 parts of pic. 1

To be continued :-)

Thursday, November 10, 2011

Factory Method Pattern

Very useful pattern, that I am using almost each day - Factory Method Pattern.
I would like to explain it with very simple code that I created for this post:

Before just to image how its looks:



C# Code:

3 Instances that will need to create according to some conditions and we did know before:


 public class Instance1IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance2IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance3IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }

All this instances inherits from IInstance interface that have only one PRINT(); method:

 public interface IInstance
    {
        void Print();   
    }

Next - its a Factory class that do all works (concrete of IFactory interface), create one of three above Instance classes according to some condition, in our case its simply swithch caseindex.


 public interface IFactory
    {
        IInstance CreateInstance();
    }



 public class FactoryIFactory
    {
        private int Index { getset; }
 
        public Factory(int instanceIndex)
        {
            Index = instanceIndex;
        }
        public IInstance CreateInstance()
        {
            switch (Index > 2 ? 3 : Index)
            {
                case 1:
                    return new Instance1();                    
                case 2:
                    return new Instance2();
                default:
                    return new Instance3();
            }
        }        


and, main that will run our modest programm:

 static void Main(string[] args)
 {
      IInstance instance = new Factory(2).CreateInstance();
      instance.Print();
 }


Enjoy!























Thursday, November 3, 2011

Observer Pattern with Managed Extensibility Framework (MEF)

Following example expose using of Observer Pattern with MEF dependency injection.
I will need send to all observers XmlElement I got from WebService.

Interfaces of Observer Pattern:


public interface IResponceObserver
{
        void Update();
}

public interface IResponceSubject
{
        List<IResponceObserver> Observers { getset; }
        void Attach(IResponceObserver observer);
        void Detach(IResponceObserver observer);
        void Notify();
}



And Concrete of Subject interface:


public class ResponceSubjectIResponceSubject
{
        public List<IResponceObserver> Observers { getset; }
        
        public void Attach(IResponceObserver observer)
        {
            Observers.Add(observer);
        }
 
        public void Detach(IResponceObserver observer)
        {
            Observers.Remove(observer);
        }
 
        public void Notify()
        {
            foreach (IResponceObserver o in Observers)
            {
                o.Update();
            }
        }
}

Suppose we have two observer classes that need to realize Update() method:



[Export(typeof(IResponceObserver))]
public class LoginCommandHandler_1 CommandHandlerBase, IResponceObserver {
     public void Update()
     {
        WriteLine ("LoginCommandHandler_1")
     }
}

[Export(typeof(IResponceObserver))]
public class LoginCommandHandler_2 CommandHandlerBase, IResponceObserver {
     public void Update()
     {
        WriteLine ("LoginCommandHandler_2")
     }
}

And Main Class that will add observer to List of subject and Notify all observers:

public class CustomerServiceAgent : ICustomerServiceAgent
{         
        [ImportMany]
        public IResponceObserver[] ResponseObservers getset; }

        public void SomethingDo()
        {
            //REGISTER ALL OBSERVERS WHO WANT TO GET ANY FROM response.Customer
            IResponceSubject responceSubject = new ResponceSubject();
            foreach (var observer in ResponseObservers)
            {
                responceSubject.Attach(observer);   
            }            
 
            //YOUR CODE HERE:
            //UPDATE All Observers with response.Customer.Any
            responceSubject.Notify();
 
            return customer;
        }
}

Output:

\> LoginCommandHandler_1
\> LoginCommandHandler_2

I hope its help to understand MEF and return against on Observer Pattern

Thanks,
Enjoy!