August 15, 2016

LINQ : Expression Trees

An expression tree is an efficient data representation of a query operator lambda expression. This data representation is evaluated all simultaneously, so that an individual query can be built and launched on a data source in once

Consider the next query with two operators expecting delegates as arguments:

        private static decimal[] celsiusDegrees = new decimal[] 
            {0.0M, 6.0M, 14.0M, 25.0M, 28.0M, 34.0M, 36.0M};

        private static IEnumerable<decimal> enumerableTemps = celsiusDegrees
            .Where(i => i > 30.0M)
            .OrderBy(i => i).ToArray();

        private static IQueryable<decimal> queryableTemps = celsiusDegrees.Where(c => c > 30.0M)
            .OrderBy(c => c).AsQueryable();


When the first code is compiled .NET IL emits code with two anonymous methods, one for each of the query lambda expressions

This query is evaluated and launched linearly, first Where operator, then OrderBy operator. This linear evaluation has performance for this example, but consider a query on a large dataset. These scena is when Expression Trees become necessary. Expression trees will be generated if the operator is declared to accept an expression of a delegate

These are the two different implementations of the Where operator:

Standard query operator in LINQ to Objects API, in System.Linq.Enumerable class

        public static IEnumerable<T> Where<T>(
                this IEnumerable<T> source,
                Func<T, bool> predicate);


Implementation in the LINQ to SQL API, in the System.Linq.Queryable class

        public static IQueryable<T> Where<T>(
                this IQueryable<T> source,
                System.Linq.Expressions.Expression<Func<int, bool>> predicate);

The result of this code is the next

        Console.WriteLine(enumerableTemps);

        foreach (var temp in enumerableTemps)
            Console.WriteLine(temp);

        Console.WriteLine(Environment.NewLine);

        Console.WriteLine(queryableTemps);
        foreach (var temp in queryableTemps)
            Console.WriteLine(temp);




The ease way to create expression trees is by using advanced LINQ features, however, a tree made up only of constans would be converted automatically at compile time, the aim is build parametric expressions, such as the formula to convert celsius to kelvin degrees : K = C + 273.15

        Func<decimal, decimal> CelsiusToKelvin = (c) => c + 273.15M;

        Expression<Func<decimal, decimal>> CelsiusToKelvinExp = (c) => c + 273.15M;



The first delegate instance is no different from a regular function, you can get an expression tree representation instead of the delegate simply declaring CelsiusToKelvin as an Expression<TDelegate>

The result of this code is the next

            Console.WriteLine(CelsiusToKelvin.ToString());
            Console.WriteLine(CelsiusToKelvin(34.2M));

            Console.WriteLine(CelsiusToKelvinExp.ToString());
            Console.WriteLine(CelsiusToKelvinExp.Compile()(34.2M));






<METHOD SOFTWARE © 2016>

April 27, 2016

ASPx : Dependency Injection

Dependency Injection pattern is the best way to achieve loose coupling. In Web Forms applications, the mechanism for dependency injection varies slightly

In this example we set up dependency injection in a web form with Autofac Integration Web libraries. The first step will be installing Autofac Web Forms Integration Nuget



Once we have installed the libraries, we have to set up the injection modules, in web.config

  <system.web>
    <httpModules>
      <!-- This section is used for IIS6 -->
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"/>
      <add
        name="PropertyInjection"
        type="Autofac.Integration.Web.Forms.PropertyInjectionModule, Autofac.Integration.Web"/>
    </httpModules>

  </system.web>
  <system.webServer>

    <!-- This section is used for IIS7 -->
    <modules>
      <add
        name="ContainerDisposal"
        type="Autofac.Integration.Web.ContainerDisposalModule, Autofac.Integration.Web"
        preCondition="managedHandler"/>
      <add
        name="AttributedInjection"
        type="Autofac.Integration.Web.Forms.AttributedInjectionModule, Autofac.Integration.Web"
        preCondition="managedHandler"/>
    </modules>
  </system.webServer>


Now we implement IContainerProviderAccessor in Global.asax

    public class Global : HttpApplication, IContainerProviderAccessor
    {
        static IContainerProvider _containerProvider;

        public IContainerProvider ContainerProvider
        {
            get { return _containerProvider; }
        }
        
        // // // //
    }


We are using AttributedInjection Module, so injection will be launched for Web Forms with class header attribute

    [InjectProperties]
    public partial class SitePage : System.Web.UI.Page
    {
        public IDataManager _dataManager { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            var allData = _dataManager.GetAllData();
 
            // // // //
        }
        
        // // // //
    }


AttributedInjection Module will detect public properties to inject, in classes marked with InjectProperties attribute

Registering is launched from Application_Start in global.asax

    protected void Application_Start(object sender, EventArgs e)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<DataManager>().As<IDataManager>();

        _containerProvider = new ContainerProvider(builder.Build());
    }


We can check Autofac documentation in this link: Docs: Application Integration


<METHOD SOFTWARE © 2016>

April 5, 2016

Dynamic Types : Indexers

When we are using Indexers in order to access our variables, we can expand the property through a dynamic reference of the accessed variable, we achieve this through ExpandoObject of System.Dynamic namespace

In this example we set values in a Dictionary type variable, and expand the property name on a dynamic variable

            dynamic Values = new ExpandoObject();

            var _Values = Values as IDictionary<string, object>;

            _Values["Name"] = "Little Writer";
            _Values["Weight"] = 1550.0M;

            string name = Values.Name;
            decimal weight = Values.Weight;



<METHOD SOFTWARE © 2016>

March 18, 2016

MVC 4 : Dependency Injection

Applying SOLID Principles ensures, and helps, writing quality code. One of the basis of SOLID is Dependency Inversion Principle

The Dependency Inversion Principle states:

  • High level modules should not depend upon low level modules. Both should depend upon abstractions
  • Abstractions should not depend upon details. Details should depend upon abstractions


Dependency Injection pattern is the best way to achieve loose coupling

In this post we implement Dependency Injection in a MVC4 app, using Autofac libraries, the first step will be installing Autofac ASP.NET MVC4 Integration Nuget, we can find it online



In the HomeController we have two dependencies with IDataAManager and IDataBManager

        private readonly IDataAManager _dataAManager;

        private readonly IDataBManager _dataBManager;

        public HomeController(IDataAManager dataAManager, IDataBManager dataBManager)
        {
            _dataAManager = dataAManager;
            _dataBManager = dataBManager;
        }


In order to resolve these dependencies we set up Autofac Builder, we add two classes: AutofacConfig, and AutofacModule

    public class AutofacConfig
    {
        public static void ConfigureContainer()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterFilterProvider();

            builder.RegisterSource(new ViewRegistrationSource());

            builder.RegisterModule(new AutofacModule());

            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }


    public class AutofacModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<DataAManager>().As<IDataAManager>();

            builder.RegisterType<DataBManager>().As<IDataBManager>();

            base.Load(builder);
        }
    }


We are making AutofacModule inherit from Module class from Autofac, which contains virtual method Load to set the container

  public abstract class Module : IModule


We launch the Dependency Injection from global.asax

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            AutofacConfig.ConfigureContainer();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }



<METHOD SOFTWARE © 2016>

March 4, 2016

HTML5 : Drag and Drop elements

HTML5 API includes Drag and Drop (DnD) native functionality

The event listener methods for all the drag and drop events accept Event object which has a readonly attribute called dataTransfer. The event.dataTransfer returns DataTransfer object associated with the event

This is the list of events fired during the different stages

Event Description
dragstart Fires when the user starts dragging of the object.
dragenter Fired when the mouse is first moved over the target element while a drag is occuring. A listener for this event should indicate whether a drop is allowed over this location. If there are no listeners, or the listeners perform no operations, then a drop is not allowed by default.
dragover This event is fired as the mouse is moved over an element when a drag is occuring. Much of the time, the operation that occurs during a listener will be the same as the dragenter event.
dragleave This event is fired when the mouse leaves an element while a drag is occuring. Listeners should remove any highlighting or insertion markers used for drop feedback.
drag Fires every time the mouse is moved while the object is being dragged.
drop The drop event is fired on the element where the drop was occured at the end of the drag operation. A listener would be responsible for retrieving the data being dragged and inserting it at the drop location.
dragend Fires when the user releases the mouse button while dragging an object.



In this post we develop an application to handle the drag and drop events between two elements, and launch a HttpPost method in the server which will ends inserting the dragged value in database

The first step is the definition of the UXinterface, in sequence the display is this



We are adding h5utils.js file, with an implementation of AddEvent function to simplify our code

var AddEvent = (function () {
    if (document.addEventListener) {
        return function (el, type, fn) {
            if (el && el.nodeName || el === window) {
                el.addEventListener(type, fn, false);
            } else if (el && el.length) {
                for (var i = 0; i < el.length; i++) {
                    AddEvent(el[i], type, fn);
                }
            }
        };
    } else {
        return function (el, type, fn) {
            if (el && el.nodeName || el === window) {
                el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
            } else if (el && el.length) {
                for (var i = 0; i < el.length; i++) {
                    AddEvent(el[i], type, fn);
                }
            }
        };
    }
})();


Now the code to implement drag and drop events

    var pDragElement = document.createElement('p');

    var chemicalElements = document.querySelectorAll('div > p'), el = null;
    for (var i = 0; i < chemicalElements.length; i++) {

        el = chemicalElements[i];

        el.setAttribute('draggable', 'true');

        AddEvent(el, 'dragstart', dragStartElement);
        
        AddEvent(el, 'dragend', dragEndElement);        
    }

    function dragStartElement(e) {

        e.dataTransfer.effectAllowed = 'copy';
        e.dataTransfer.setData('Text', this.id);
        e.dataTransfer.setData('Type', this.innerHTML);
        
        this.style.backgroundColor = "#ffa31a";
    }
    
    function dragEndElement(e) {
        
        this.style.backgroundColor = "#fff9f0";
    }
    
    var divBoxElements = document.querySelector('#divBoxElements');

    AddEvent(divBoxElements, 'dragover', function (e) {

        if (e.preventDefault) e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
        return false;
    });

    AddEvent(divBoxElements, 'drop', function (e) {

        if (e.stopPropagation) e.stopPropagation();

        var element = e.dataTransfer.getData('Type');

        pDragElement.innerHTML = "Adding " + element + " element";

        var pClone = pDragElement.cloneNode(true);

        var newDiv = document.createElement("div");

        newDiv.appendChild(pClone);

        divBoxElements.appendChild(newDiv);

        InsertChemicalElement(element);

        return false;
    });


The function InsertChemicalElement will call the HttpPost server method

    function InsertChemicalElement(element) {
        
        var url = '@Url.Action("InsertChemicalElements", "Home")';

        $.post(url, { chemicalElement: element },
            
        function (data) {

            switch (data) {
                case 1:                    
                    divBoxElements.innerHTML = element + " inserted OK";
                    setTimeout(function() { divBoxElements.innerHTML = ""; }, 2000);
                    break;
                    
                default:
                    alert("Error inserting the element");
            }
        });
    }


The code in the server side makes use of EF, with one table and one stored procedure in the diagram



With a SOLID implementation, the code for inserting data is divided in two functions

    [HttpPost]
    public JsonResult InsertChemicalElements(string chemicalElement)
    {
        string[] elementData = chemicalElement.Split(':');

        string symbol = elementData[0].Trim();
        string name = elementData[1].Trim();

        int insertResult = _chemicalDatabase.InsertElement(symbol, name);

        return Json(insertResult);
    }


//////////


    public class ChemicalDatabase : IChemicalDatabase
    {
        public int InsertElement(string symbol, string name)
        {
            using (ChemicalsEntities entities = new ChemicalsEntities())
            {
                return entities.P_INSERT_ELEMENT(symbol, name);
            }
        }
    }



<METHOD SOFTWARE © 2016>

February 6, 2016

WCF : One Way Dual Methods

WCF Services can declare methods which are invoked in one way mode, this implies the method will be called but the client side will not expect a reply, so will continue its operations without time leaks waiting for a response. This configuration is optimal for operations which don't require feedback results

OneWay methods can be bi-directionals, through a dual configuration, allowing client and server initiate invocation calls to each other. This mechanism is very useful for long-running processes in case the client expects a reply

In this post we develop a dual communication through a wsDualHttpBinding endpoint. These are the key points of the mechanism:

  • The service will expose an interface with the definition of the callback method, this method will be also marked as OneWay
  • This interface will be implemented in the client side
  • The OneWay method in the service will use this implementation to communicate with the client side once finish tasks
  • The client side must not dispose the InstanceContext with the server til the communication ends, the callback from the server will be treated as an event


The first step will be the definition of the interface in the service

    [ServiceContract(CallbackContract = typeof(IBookServiceCallBack))]
    public interface IBookService
    {
        [OperationContract]
        int AddBook(string title, string isbn, string synopsis, int idAuthor);

        [OperationContract]
        int AddAuthor(string firstName, string lastName, string biography);

        [OperationContract(IsOneWay = true)]
        void SendNewTitlesToSubscriptors(DateTime booksAddedAfterDate);
    }


And this is the definition of IBookServiceCallBack

    [ServiceContract] 
    public interface IBookServiceCallBack
    {
        [OperationContract(IsOneWay = true)]
        void NotifyClient(string message);
    }


We will focus on the method SendNewTitlesToSubscriptors, which will invoke the notification event on the client side

    public void SendNewTitlesToSubscriptors(DateTime booksAddedAfterDate)
    {
        _subscriptorManager.SendNewTitlesToSubscriptors(booksAddedAfterDate);

        INotificationServiceCallBack notificationSend =
            OperationContext.Current.GetCallbackChannel<IBookServiceCallBack>();

        notificationSend.NotifyClient(string.Format(
            "New titles added since {0} have been sent successfully", booksAddedAfterDate));
    }


With this configuration the client reference will add the interface IBookServiceCallBack

      <service name="BookService.BookService">
        <endpoint address="CallBackService" 
        binding="wsDualHttpBinding" contract="BookService.IBookService"/>
      </service>


Now the code in the client side:

    private InstanceContext instance
    {
        get { return new InstanceContext(new BookStoreNotificationHandler()); }
    }

    private BookServiceClient client
    {
        get { return new BookServiceClient(instance); }
    }

    private void btnSendNewTitles_Click(object sender, RoutedEventArgs e)
    {
        DateTime booksAddedAfterDate = dpBooksAddedFromDate.SelectedDate.Value;

        Thread threadSendNewTitles = new Thread(() =>
            {                    
                lblSendStep.SetContent("Sending new titles, please wait...");

                client.SendNewTitlesToSubscriptors(booksAddedAfterDate);
            });

        threadSendNewTitles.Start();
    }


and the implementation of IBookServiceCallBack as an event handler:

    public class BookStoreNotificationHandler : IBookServiceCallback
    {
        public void NotifyClient(string message)
        {
            MainWindow.lblSendStep.SetContent(message);
        }
    }


* Notice that in both cases we have used the extension method SetContent in order to control the content of the components in threading, as specified in this post: WPF MainWindow Instance

The result of this mechanism is the next:





<METHOD SOFTWARE © 2016>

November 2, 2015

Dynamic Types

Dynamic Types are built on runtime, adding properties on execution time

With all DTOs and typed classes the difficult might be finding scenario to apply dynamic types

Situation for implement a dynamic property is when we have a custom class, and in some moment of the process we need to add data dynamically

In this case we have a Base Class for our DTO in which we add a dynamic property

public class CustomCan : CanBase


//////

public class CanBase
{
    public dynamic Content { get; set; }
}


Properties added to a dynamic object can also contain custom objects, so the data transfer is not limited at this point

In this post we set the content of our can through the next code

    var MyCustomCan = new CustomCan();

    Noodles contentNoodles = _contentProvider.GetNoodles();

    MyCustomCan.Content.Quantity = 440.0;
    MyCustomCan.Content.SettedTo = contentNoodles; 






<METHOD SOFTWARE © 2015>

May 26, 2015

WPF: MainWindow Instance

When we are developing WPF Win forms, we have to consider the implementation of access to the main window, through multi-threaded processes, and through instances of classes outside the main window class

WPF Applications run on a single thread, and new processes adhere themselves to this main thread, but when we separate long running threads explicitly, we need to keep the access to the main window controls. This is achieved through the Dispatcher's control, the inheritance hierarchy of window controls to the dispatcher is the next:


ContentControl : Control : FrameworkElement : UIElement : 
Visual : DependencyObject : DispatcherObject


the implementation of DispatcherObject is this:

namespace System.Windows.Threading
{
    public abstract class DispatcherObject
    {
        protected DispatcherObject();

        [EditorBrowsable(EditorBrowsableState.Advanced)]
        public Dispatcher Dispatcher { get; }

        [EditorBrowsable(EditorBrowsableState.Never)]
        public bool CheckAccess();

        [EditorBrowsable(EditorBrowsableState.Never)]
        public void VerifyAccess();
    }
}


In this post we are going to implement controls' extension methods to stablish access to the the main window elements, and will let to the Dispatcher property of the control invoke the actions over the element

The application in this example is this



We have two elements to be modified from outside the main thread and the MainWindow class: one Label and one ProgressBar to display the results. In order to get access to these elements from different classes in the application, we have to provide static controls pointing the originals, so the access will not be restricted to the MainWindow class

This is the code declaring the static controls

    public partial class MainWindow : Window
    {
        public static Label lblResultSyncStaticControl;
        public static ProgressBar pbResultSyncStaticControl;

        public MainWindow()
        {
            InitializeComponent();

            InitializeStaticControls();
        }

        protected void InitializeStaticControls()
        {
            lblResultSyncStaticControl = lblResultSync;
            pbResultSyncStaticControl = pbResultSync;
        }
        
        // ....
    }


And these are the extension methods provided to invoke the actions

    public static class ControlMethods
    {
        public static void SetContent(this ContentControl cc, object content)
        {
            InvokeIfRequired(cc, () => { cc.Content = content; }, 
                DispatcherPriority.Background);
        }

        public static void SetMax(this ProgressBar pb, int max)
        {
            InvokeIfRequired(pb, () => { pb.Maximum = max; }, DispatcherPriority.Background);
        }

        public static void SetValue(this ProgressBar pb, int value)
        {
            InvokeIfRequired(pb, () => { pb.Value = value; }, 
                DispatcherPriority.Background);
        }

        private static void InvokeIfRequired(this DispatcherObject control, 
            Action methodcall, DispatcherPriority priorityForCall)
        {
            //see if we need to Invoke call to Dispatcher thread  
            if (control.Dispatcher.Thread != Thread.CurrentThread)
                control.Dispatcher.Invoke(priorityForCall, methodcall);
            else
                methodcall();
        }
    }


The process will perform a data validation, after which will begin the synchronization, and will keep open access to modify the display of the controls on the main window

    public static ValidationResults ValidateData()
    {
        var testDataRecords = DataContext.GetAllRecordsInTable("TestData");
        var validationResults = new ValidationResults();
            
        MainWindow.pbResultSyncStaticControl.SetMax(testDataRecords.Count());
        MainWindow.pbResultSyncStaticControl.SetValue(0);

        int index = 0;

        foreach (var record in testDataRecords)
        {
            MainWindow.lblResultSyncStaticControl
                .SetContent(string.Format("Validating record: {0}", record.Id));
            MainWindow.pbResultSyncStaticControl.SetValue(++index);

            validationResults.Results.Add(ValidateRecord(record));
        }

        return validationResults;
    }


And if the data validation returns no errors, the synchronization begins

    public void Synchronize()
    {
        var validationResults = DatabaseValidator.ValidateData();

        if (!validationResults.Results.Contains("error"))
        {
            BeginSynchronization();    
        }
    }


The code in BeginSynchronization function to display the advance is the next

            MainWindow.lblResultSyncStaticControl
                .SetContent(string.Format("Synchronizing record: {0}", record.Id));
            MainWindow.pbResultSyncStaticControl.SetValue(++index);


Through this mechanism we can start a new thread to run synchronization and non-block the window interaction

    private void btnSync_Click(object sender, RoutedEventArgs e)
    {
        Thread syncThread = new Thread(() =>
            {
                DatabaseSynchronizer.Synchronize();
            });

        syncThread.Start();
    }







<METHOD SOFTWARE © 2015>

January 2, 2015

MVC 4 : Ajax Forms

ASP.NET MVC 4 includes Ajax functionalities based on jQuery javascript library. Most of the Ajax features in the framework build on or extend features in jQuery

In this post we will implement an asynchronous request form with validation

This is the Chemical model in our Application

    public class ChemicalElement
    {
        public int IdElement { get; set; }

        [DisplayName("Name")]
        [Required]
        public string Name { get; set; }

        [DisplayName("Latin name")]
        [Required]
        public string LatinName { get; set; }

        [DisplayName("Symbol")]
        [Required]
        [RegularExpression(@"\b[a-zA-Z]{1,3}\b")]
        public string Symbol { get; set; }
    }


We have imported the next SQL schema (table and stored procedure)



The code to release the search of chemical elements is the next

    public PartialViewResult SearchChemicalElements(string search)
    {
        var elementsModel = SearchElementsModel(search);

        return PartialView("Elements", elementsModel);
    }

    private IEnumerable<ChemicalElement> SearchElementsModel(string search)
    {
        var allElements = Elements.SearchElements(search);

        return allElements;
    }


And in the Elements class the implementation of the SearchElement method is this

    public static IEnumerable<ChemicalElement> SearchElements(string search)
    {
        using (CHEMICALSEntities context = new CHEMICALSEntities())
        {
            ObjectResult<SearchElementsBySymbol_Result> matchElements =
                context.SearchElementsBySymbol("%" + search + "%");

            foreach (var element in matchElements)
                yield return new ChemicalElement()
                {
                    IdElement = element.IdElement,
                    Name = element.Name,
                    LatinName = element.LatinName,
                    Symbol = element.Symbol
                };
        }
    }


The code in the View to make the process work asynchronously, is the next

@using (Ajax.BeginForm("SearchChemicalElements", "Chemical", new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "GET",
        LoadingElementId = "preloader",
        UpdateTargetId = "searchResults",
    }))


This code renders an html form with the next marks



The information about how to perform the AJAX request is contained in the DOM, and it is released by the jquery.unobtrusive-ajax.js code

The PartialView for Elements is strongly typed and renders a table in a loop for each element



The validation rules are specified in the model, so the code in the view

         @Html.TextBoxFor(m => m.Symbol, new { Name = "search"})


will renders the information into these data dash attributes

data-val="true" 
data-val-regex="The field Symbol must match the regular expression '\b[a-zA-Z]{1,3}\b'." 
data-val-regex-pattern="\b[a-zA-Z]{1,3}\b" 
data-val-required="The field Symbol is required." 
id="Symbol" name="search"


The Ajax request, and validation are implemented inside the jQuery scripts

@section scripts {
    <script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.min.js"></script>
    <script type="text/javascript" src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
}



<METHOD SOFTWARE © 2015>

December 26, 2014

Extension Methods

Extension methods are static methods, in static classes, marked up to be added to existing types without creating a new derived type, or modifying the original type. You can use extension methods to extend a class or interface. This feature was introduced in C# 3.0

In this example we will implement extension methods for two different data types: DateTime, and IEnumerable

This is the implementation of the methods in this example

    public static class ExtensionMethods
    {
        public static string ToLetterFormat(this DateTime dateTime)
        {
            return dateTime.ToString("MMMM d',' yyyy");
        }

        public static IEnumerable<string> GetOnlyStrings<T>(this IEnumerable<T> list)
        {
            foreach (var item in list)
            {
                if (item is string)
                    yield return item as string;
            }
        }
    }


The markup that makes these extension methods is the keyword this used before the first parameter in the parameter list of the method. This keyword is specific to C#, and it instructs the compiler to add the ExtensionMethodAttribute to the method

The first method produces a result like this:

    string letterFormatDate = (DateTime.Today).ToLetterFormat();

    Console.WriteLine(letterFormatDate);
    Console.ReadKey();




The second method produces this result:


    customList.ForEach(l => Console.WriteLine(l.GetType().ToString()));
    Console.ReadKey();

    List<string> allStringsFromCustomList = customList.GetOnlyStrings().ToList();

    Console.WriteLine(Environment.NewLine);

    allStringsFromCustomList.ForEach(s => Console.WriteLine(s));

    Console.ReadKey();





<METHOD SOFTWARE © 2014>

September 14, 2014

Entity Framework : ChangeTracker

With ChangeTracker we can track the state of the entities in the database context, so when our processes work into a context we can work on specific group of entities

In this example we have this diagram and a class which handles the retrieve and insert methods. This is the implementation:



        public IEnumerable<GALAXIES> GetKnownGalaxies()
        {
            return (from GALAXIES galaxies in _context.GALAXIES select galaxies);
        }

        public void InsertGalaxy(GALAXIES galaxy)
        {
            _context.GALAXIES.Attach(galaxy);
            _context.Entry(galaxy).State = EntityState.Added;
            _context.GALAXIES.Add(galaxy);
        }


Now we add a third method to retrieve only the added galaxies:

        public IEnumerable<GALAXIES> GetNewGalaxies()
        {
            return
                (from GALAXIES galaxies in _context.ChangeTracker.Entries()
                     .Where(e => e is GALAXIES && e.State == EntityState.Added)
                     .Select(e => e.Entity as GALAXIES)
                 select galaxies);
        }


The result of the program with this sequence is the next:

        var knownGalaxies = galaxyClass.GetKnownGalaxies().ToList();

        knownGalaxies.ForEach(
            x =>
            Console.WriteLine("{0}: {1} distance, {2} magnitude", 
                                x.Name, x.Distance.ToString(),
                                x.Magnitude.ToString()));

        Console.WriteLine(Environment.NewLine);
        Console.ReadKey();

        InsertNewGalaxy();

        var newGalaxies = galaxyClass.GetNewGalaxies().ToList();

        newGalaxies.ForEach(
            x =>
            Console.WriteLine("{0}: {1} distance, {2} magnitude", 
                                x.Name, x.Distance.ToString(),
                                x.Magnitude.ToString()));





<METHOD SOFTWARE © 2014>

July 6, 2014

MVC 4 : Display images from database

In this post we will read and write data to the database including an IMAGE SQL Server type field, which will be displayed in our web site

IMAGE type in SQL Server represents variable-length binary data from 0 up to 2 ^31-1 (2,147,483,647 ) bytes

The diagram of the application is the next, from the database to the application model:

We have the next table, and two stored procedures in the database:

    CREATE DATABASE UNIVERSE
    GO

    CREATE TABLE GALAXIES
    (
        IdGalaxy            INT IDENTITY (1,1) NOT NULL,
        Name                VARCHAR(200) NOT NULL,
        Magnitude           DECIMAL(6,2) NOT NULL,
        Distance            DECIMAL(6,2) NOT NULL,
        Picture             IMAGE NULL,
        
        CONSTRAINT PK_GALAXIES PRIMARY KEY (IdGalaxy),
        CONSTRAINT UQ_GALAXY UNIQUE (Name)
    )
    GO

    CREATE PROCEDURE GetGalaxyByName 
        (@name VARCHAR(200))
    AS BEGIN
        
        SELECT * FROM GALAXIES WHERE Name = @name
        RETURN 
        
    END
    GO


    CREATE PROCEDURE SaveGalaxy
    (@name VARCHAR(200), @magnitude DECIMAL(6,2), 
     @distance DECIMAL(6,2), @picture IMAGE)
    AS BEGIN

        INSERT INTO GALAXIES VALUES 
            (@name, @magnitude, @distance, @picture)
            
        RETURN @@ROWCOUNT

    END
    GO


The model for our application is the Galaxy model:

    public class Galaxy
    {
        public int IdGalaxy { get; set; }

        [Required(ErrorMessage = "Name of the galaxy is required")]
        public string Name { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
        public decimal? Magnitude { get; set; }

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
        public decimal? Distance { get; set; }

        public byte[] Picture { get; set; }
    }


Now we add the database schema to our project, we will import the Galaxies table, and the stored procs to be invoked from the database context



Once we have defined the model, we will implement two views, one for Insert, and a second one for Select galaxies. This is the Insert View, the file upload component is defined in code as follows



        <div>
            <input id="photo" name="photo" type="file" value="UploadPicture"/>
        </div>


There are two important points to keep in mind when we are submitting files to the server, one is naming the html input file, and the HttpPostedFileBase parameter of the action, with the same identifier, so the mechanism of binding will recognize the file submitted. In order to make this happen we have to define the enctype of the html form as multipart/form-data, the syntax in server side is as follows

@using (Html.BeginForm("Insert", "Galaxy", FormMethod.Post, new { enctype = "multipart/form-data" }))


In the GalaxyController, the method called when we submit the form is this

        [HttpPost]
        public ActionResult Insert(Galaxy galaxyModel, HttpPostedFileBase photo)
        {
            try
            {
                byte[] imageData = new Byte[photo.InputStream.Length];
                photo.InputStream.Read(imageData, 0, (int)photo.InputStream.Length);

                galaxyModel.Picture = imageData;

                int result = GalaxyClass.SaveGalaxy(galaxyModel);

                ViewBag.InsertResult = result;

                return View(galaxyModel);
            }
            catch (Exception ex)
            {
                LogException(ex);
                return View("Error", new HandleErrorInfo(ex, "Galaxy", "Insert"));
            }
        }


The static method invoked to save the galaxy is implemented as follows, making a call to the SaveGalaxy stored procedure with the params expected

        public static int SaveGalaxy(Galaxy galaxy)
        {
            using (UniverseEntities context = new UniverseEntities())
            {
                int result = context.SaveGalaxy(galaxy.Name, galaxy.Magnitude, 
                    galaxy.Distance, galaxy.Picture);
                return result;
            }
        }


The result of the Insert Action is the insertion in database of the galaxy data



Now we will display these data in the Select View



The code to retrieve the data from db is the next

        [HttpPost]
        public ActionResult Select(Galaxy galaxyModel)
        {
            galaxyModel = GalaxyClass.GetGalaxyModel(galaxyModel.Name);
            return View(galaxyModel);
        }


And the method invoking the GetGalaxyByName stored proc

        public static Galaxy GetGalaxyModel(string galaxyName)
        {
            using (UniverseEntities context = new UniverseEntities())
            {
                GetGalaxyByName_Result galaxyResult = 
                        context.GetGalaxyByName(galaxyName).First();

                return new Galaxy()
                {
                    IdGalaxy = galaxyResult.IdGalaxy,
                    Name = galaxyResult.Name,
                    Magnitude = galaxyResult.Magnitude,
                    Distance = galaxyResult.Distance,
                    Picture = galaxyResult.Picture
                };
            }            
        }


The code inside the view to display the image is the next

        <div>
            @{
                if (Model.Picture != null)
                {
                    string imageBase64 = Convert.ToBase64String(Model.Picture);
                    string imageSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64);
                    <img src="@imageSrc" style="height:auto;width:auto;" />
                }
            }
        </div> 


The result of submitting the view with the Bode's Galaxy selected is this




<METHOD SOFTWARE © 2014>

May 16, 2014

SOLID Software in the Enterprise

This post is just to redirect to the next article from Noel Stieglitz's Blog about SOLID Principle:

SOLID Software in the Enterprise

Regards Developers,


<METHOD SOFTWARE © 2014>

April 20, 2014

LINQ : Compiled queries

The process of converting LINQ queries to SQL statements, involves syntax check, and the construction of the SQL query, this task is performed every time we launch the LINQ query

In compiled queries, the syntax check and construction plan are cached in a static class, so LINQ uses this cached plan from the static class object instead of re-building it in sequent executions

In this example we have the next diagram of LINQ to SQL Classes



We will compile these two queries. A compiled query is stored in a Func delegate, where the first argument must be an instance of DataContext (or derived), and the last argument must be the type returned from the query, you can define up to three arguments in the middle as parameters of the compiled query. You will need to specify these arguments for each compiled query invocation

        private static Func<BusinessClassesDataContext, DateTime, IQueryable<B_SALES>>
            SalesByDate = CompiledQuery.Compile(
                (BusinessClassesDataContext ctx, DateTime saleDate) =>
                    (from sl in ctx.GetTable<B_SALES>()
                     where sl.SALEDATE >= saleDate
                     select sl));

        private static Func<BusinessClassesDataContext, int, Decimal>
            SalesAverageByCustomer = CompiledQuery.Compile(
                (BusinessClassesDataContext ctx, int idCustomer) =>
                    (from sl in ctx.B_SALES
                     where sl.B_CUSTOMERS.IdCustomer == idCustomer
                     group sl by sl.Price
                     into sales
                     select sales.Average(sl => sl.Price)).First());


Now the code calling these queries is the next

        using (BusinessClassesDataContext context = new BusinessClassesDataContext())
        {
            foreach (B_SALES sale in SalesByDate(context, saleDate))
            {
                Console.WriteLine("{0} : {1}", sale.IdSale, sale.IdProduct);
            }

            Console.WriteLine("{0:N2}$", SalesAverageByCustomer(context, 1));
        }            



<METHOD SOFTWARE © 2014>

April 14, 2014

MVC 4 Application Resources: multi language

Application Resources can be created in ASP.NET applications with two different scopes, depending on the level you want to share these resources across the application

In this example we will create a set of global resources containing dictionaries for the application display in three different languages: English (en), Spanish (es), and Catalán (ca)



The application we will build is a data-entry form based on Guest model, and will be displayed in the selected language

    public class Guest
    {
        [Required(ErrorMessageResourceType = typeof(Resources.Dictionary), 
         ErrorMessageResourceName="RequiredFirstName")]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceType = typeof(Resources.Dictionary), 
         ErrorMessageResourceName = "RequiredLastName")]
        public string LastName { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime? BirthDate { get; set; }
    }




We will add the next div element to the _layout.cshtml view in order to generate the language selector

    <div class="content-wrapper">
        @{
            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            string selectedLanguageStyle = "background-color:#FFDAA3;font-weight:bold;";
            <div class="float-right">                        
            @switch (currentCulture.TwoLetterISOLanguageName)
            {
                case "en":
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "en-US" })'>English</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "es-ES" })'>Spanish</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "ca-ES" })'>Catalán</a>
                    break;
                case "es":
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "en-US" })'>English</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "es-ES" })'>Spanish</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "ca-ES" })'>Catalán</a>
                    break;
                case "ca":
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "en-US" })'>English</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "es-ES" })'>Spanish</a>
                    <a href='@Url.Action("ChangeLanguage", 
                                            "Home", new { culture = "ca-ES" })'>Catalán</a>
                    break;
            }
            </div>
        }
    </div>


This is the action method called from the language selectors (anchor elements), inside the HomeController

    public ActionResult ChangeLanguage(string culture)
    {
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
        Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;

        Session["lang"] = culture;

        return Redirect(Request.UrlReferrer.ToString());
    }


The approach is this: we will create a BaseController to handle the ExecuteCore method, and stablish the thread's current culture. ExecuteCore method invokes the action in the current controller context. The controllers in our application will inherit BaseController

    public class BaseController : Controller
    {
        //
        // GET: /Base/

        protected override void ExecuteCore()
        {
            var culture = Session["lang"] ?? "en-US";        

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture.ToString());
            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;

            base.ExecuteCore();
        }

        protected override bool DisableAsyncSupport
        {
            get { return true; }
        }
    }


DysableAsyncSupport property gets whether to disable the asynchronous support for the controller. This flag is for backwards compatibility. ASP.NET MVC 4. allows a controller to support asynchronous patterns. This means ExecuteCore doesn't get called on derived classes. Derived classes can override this flag and set to true if they still need ExecuteCore to be called

The strongly-typed view based on Guest model is this:

@model MvcApp1.Models.Guest

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@Resources.Dictionary.ViewTitle</h2>

<div>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <table>
            <tbody>
                <tr>
                    <td>
                        <div class="editor-field">
                            <span>@Resources.Dictionary.FirstName</span>
                        </div>                        
                    </td>
                    <td>
                        @Html.EditorFor(model => model.FirstName)
                        @Html.ValidationMessageFor(model => model.FirstName)                        
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="editor-field">
                            <span>@Resources.Dictionary.LastName</span>
                        </div>                        
                    </td>
                    <td>
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)                        
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="editor-field">
                            <span>@Resources.Dictionary.BirthDate</span>
                        </div>                        
                    </td>
                    <td>
                        @Html.EditorFor(model => model.BirthDate)
                    </td>
                </tr>
            </tbody>
        </table>
        <input type="submit" value="Save"/>
    }    
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


The result is the next:




<METHOD SOFTWARE © 2014>

March 17, 2014

HTML5 : API Indexed Database

API Indexed Database is the officially supported by W3C way for the creation of databases with HTML5

This system takes the concept of key/value pairs to store data. the Database can contain Stores, the equivalent to the SQL tables, and each Object Store contains key/value pairs; this API is not a relational database, but object oriented. you can query this database inline as offline

The first step in this example will be creating a new database, for this we use the open() method, the syntax is as follows:
    indexedDB.open("database_name", version)
If the database does not exist, it is created, else, it is open. The call to the open() function returns an IDBOpenDBRequest object with a result (success) or error value that you handle as an event

In this example we build the next web form, and implement a Web Method in the server side which returns an array of json objects for loading the database



The js code to open the database and create the object store is the next

    var HTML5DB = {};
    HTML5DB.indexedDB = {};
    HTML5DB.indexedDB.db = null;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || 
                       window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || 
                            window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || 
                         window.msIDBKeyRange;

    HTML5DB.indexedDB.onerror = function (e) { console.log(e); };

    HTML5DB.indexedDB.open = function () {

        var version = 1;
        var request = window.indexedDB.open("db_example", version);

        request.onupgradeneeded = function (e) {

            var db = e.target.result;
            e.target.transaction.onerror = HTML5DB.indexedDB.onerror;
            var store = db.createObjectStore("object_store", 
                { keyPath: "id", autoIncrement: true });
        };

        request.onsuccess = function (e) {
            HTML5DB.indexedDB.db = e.target.result;
            HTML5DB.indexedDB.getAllRecords();
        };

        request.onerror = HTML5DB.indexedDB.onerror;
    };


The code to add and delete records is the next:

Since the id has been declared autoIncrement, we are inserting a record initializing two fields in the value property (value, and timeStamp)

    HTML5DB.indexedDB.addRecord = function (value) {

        var db = HTML5DB.indexedDB.db;
        var trans = db.transaction(["object_store"], "readwrite");
        var store = trans.objectStore("object_store");

        var data = {
            "value": value,
            "timeStamp": new Date($.now()).toLocaleTimeString()
        };

        var request = store.put(data);

        request.onsuccess = function (e) {
            HTML5DB.indexedDB.getAllRecords();
        };

        request.onerror = function (e) {
            console.log("Error Adding: ", e);
        };
    };

    HTML5DB.indexedDB.deleteRecord = function(id) {
      var db = HTML5DB.indexedDB.db;
      var trans = db.transaction(["object_store"], "readwrite");
      var store = trans.objectStore("object_store");

      var request = store.delete(id);

      request.onsuccess = function(e) {
        HTML5DB.indexedDB.getAllRecords();
      };

      request.onerror = function(e) {
        console.log("Error deleting: ", e);
      };
    };


The next is the code to retrieve and render records from the database:

    HTML5DB.indexedDB.getAllRecords = function() {

      $('#dbRecords tr').remove();

      var db = HTML5DB.indexedDB.db;
      var trans = db.transaction(["object_store"], "readwrite");
      var store = trans.objectStore("object_store");

      var keyRange = IDBKeyRange.lowerBound(0);
      var cursorRequest = store.openCursor(keyRange);

      cursorRequest.onsuccess = function(e) {
        var result = e.target.result;
        if(!!result == false)
          return;

        renderRecord(result.value);
        result.continue();
      };

      cursorRequest.onerror = HTML5DB.indexedDB.onerror;
    };

    function renderRecord(record) {

        $("#dbRecords").find('tbody')
            .append($('<tr>')
                .append($('<td>')
                    .append($('<span>')
                        .html(record.value)
                    )
                )
                .append($('<td>')
                    .append($('<span>')
                        .html(record.timeStamp)
                    )
                )
                .append($('<td>')
                    .append($('<a>')
                        .attr('href', 
                              'javascript:HTML5DB.indexedDB.deleteRecord(' + record.id + ')')
                        .html('Delete')
                )
            ));
    }


Here is the result of this code in the client side:



Finally we have implemented this call to the server to retrieve a collection of json objects and preload the database:

    function getData() {

        $.ajax({
            url: "application.aspx/getData",
            type: "POST",
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (json) {

                var records = json.d.Data.records;

                for (var i = 0; i < records.length; i++) {

                    HTML5DB.indexedDB.addRecord(records[i].Data.value);
                }
            },
            error: function (e) {
                alert('ERROR: ' + e.status + ' : ' + e.statusText);
            }
        });
    }


    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static JsonResult getData()
    {
        List<JsonResult> recordSet = new List<JsonResult>();

        for (int i = 0; i < 10; i++)
        {
            Record rec = new Record();
            rec.value = "record " + i.ToString();
            recordSet.Add(new JsonResult() { Data = rec });
        }

        JsonResult result = new JsonResult();
        result.Data = new Result() { records = recordSet };
        return result;
    }

    private class Result
    {
        public List<JsonResult> records;
    }

    private class Record
    {
        public string value;
    }




This is the IndexedDB API Documentation from Mozilla Developers

To read more about exchanging Json objects with the server, please check this post


<METHOD SOFTWARE © 2014>