Monday, July 29, 2013

MVP with Events and Delegates Simple Example

Events and Delegates Simple Example

With Delegates

using System;
 
namespace ConsoleApplication1
{
    public delegate void MyDelegate(int state);
 
    class Program
    {
        static void Main(string[] args)
        {
            var view = new View();
            new Presenter(view);
            view.ViewDelete();
        }
    }
 
    public class View
    {
        public delegate void VDelete();
 
        public event VDelete Delete;
 
        public void ViewDelete()
        {
            VDelete vd = new VDelete(Delete);
 
            if (Delete != null)
            {
                vd();
            }
        }
    }
 
    public class Presenter
    {
        public Presenter(View view)
        {
            view.Delete += view_Delete;
        }
 
        void view_Delete()
        {
 
        }
    }
}
 



Without Delegates
using System;
 
namespace ConsoleApplication1
{
    public delegate void MyDelegate(int state);
 
    class Program
    {
        static void Main(string[] args)
        {
            var view = new View();
            var presenter = new Presenter(view);
            view.ViewDelete();
        }
    }
 
 
 
 
 
    public class View
    {
        public event EventHandler Delete;
 
        public void ViewDelete()
        {
            Delete(thisEventArgs.Empty);
        }
    }
 
 
 
    public class Presenter
    {
        public Presenter(View view)
        {            
            view.Delete += view_Delete;
        }
 
        void view_Delete(object sender, EventArgs e)
        {
 
        }
    }
}

Wednesday, July 10, 2013

Simple SOA infrastructure (Call RESTful WCF Service, Recognize relevant Service and Execute)

Simple SOA infrastructure (Call RESTful WCF Service, Recognize relevant Service and Execute)


Let's start with Service Gateway part:


And Utils for:


And Request Object Model:

And WCF Service Part:

Service Contract



Service implementation:


...and Service Request Object (must be exactly like Client Request Object for JSON Serialization)


Wednesday, December 12, 2012

ASP.NET Web Site most common Architecture

Hi,

Let's try create design for most common internet web site (ASP.NET application WEB FORMS)

First of all, try to whiteboard your architecture in most simple way in order to have base to working on with.





Crosscutting Concerns
Crosscutting concerns are the features of your design that may apply across all layers,
components, and tiers. These are also the areas in which high-impact design mistakes
are most often made. Examples of crosscutting concerns are:

Authentication and Authorization.
How you choose appropriate authentication
and authorization strategies, flow identity across layers and tiers, and store user
identities.
Caching.

How you choose an appropriate caching technology, determine what
data to cache, where to cache the data, and a suitable expiration policy.

Communication. How you choose appropriate protocols for communication
across layers and tiers, design loose coupling across layers, perform asynchronous
communication, and pass sensitive data.

Configuration Management. How you determine what information must be
configurable, where and how to store configuration information, how to protect
sensitive configuration information, and how to handle configuration information
in a farm or cluster.

Exception Management. How you handle and log exceptions, and provide
notification when required.

Logging and Instrumentation. How you determine which information to log, how
to make the logging configurable, and determine what level of instrumentation is
required.

Validation. How you determine where and how to perform validation; the techniques
you choose for validating on length, range, format, and type; how you
constrain and reject input invalid values; how you sanitize potentially malicious
or dangerous input; and how you can define and reuse validation logic across
your application’s layers and tiers.


Designing for Issue Mitigation
By analyzing quality attributes and crosscutting concerns in relation to your design
requirements, you can focus on specific areas of concern. For example, the quality
attribute Security is obviously a vital factor in your design, and applies at many
levels and areas of the architecture. The relevant crosscutting concerns for security
provide guidance on specific areas where you should focus your attention. You can
use the individual crosscutting categories to divide your application architecture for
further analysis, and to help you identify application vulnerabilities. This approach
leads to a design that optimizes security aspects.

Auditing and Logging. Who did what and when? Is the application operating
normally? Auditing refers to how your application records security-related
events. Logging refers to how your application publishes information about its
operation.

Authentication. Who are you? Authentication is the process where one entity
definitively establishes the identity of another entity, typically with credentials
such as a username and password.

Authorization. What can you do? Authorization refers to how your application
controls access to resources and operations.

Configuration Management. What context does your application run under?
Which databases does it connect to? How is your application administered?
How are these settings protected? Configuration management refers to how
your application handles these operations and issues.

Cryptography. How are you handling secrets (confidentiality)? How are you
tamper-proofing your data or libraries (integrity)? How are seeding random
values that must be cryptographically strong? Cryptography refers to how
your application enforces confidentiality and integrity.

Exception Management. When a method call in your application fails, what
does your application do? How much information does it reveal? Does it return
friendly error messages to end users? Does it pass valuable exception information
back to the calling code? Does it fail gracefully? Does it help administrators
to perform root cause analysis of the fault? Exception management refers to how
you handle exceptions within your application.

Input and Data Validation. How do you know that the input your application
receives is valid and safe? Does it constrain input through entry points and
encode output through exit points. Can it trust data sources such as databases
and file shares? Input validation refers to how your application filters, scrubs,
or rejects input before additional processing.

Sensitive data. How does your application handle sensitive data? Does it protect
confidential user and application data? Sensitive data refers to how your application
handles any data that must be protected either in memory, over the network,
or in persistent stores.
Session Management. How does your application handle and protect user sessions?
A session refers to a set of related interactions between a user and your application.
You can use these questions and answers to make key security design decisions
for your application, and document these are part of your architecture. For example,

Logical Layered Design

Presentation, Business, and Data Layers



In the end I did something like this for my ASP.NET application:



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());
            }                     
        }
    }
}