Currency Code

Do you need a list of currency code?

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Globalization;
using System.Threading;

namespace PSC {
   public enum CurrencyCodes {
      [Display(Name = "GBP - British Pound")]
      GBP,
      [Display(Name = "AED - Emirati Dirham")]
      AED,
      [Display(Name = "AFN - Afghan Afghani")]
      AFN,
      [Display(Name = "ALL - Albanian Lek")]
      ALL,
      [Display(Name = "AMD - Armenian Dram")]
      AMD,
      [Display(Name = "ANG - Dutch Guilder")]
      ANG,
      [Display(Name = "AOA - Angolan Kwanza")]
      AOA,
      [Display(Name = "ARS - Argentine Peso")]
      ARS,
      [Display(Name = "AUD - Australian Dollar")]
      AUD,
      [Display(Name = "AWG - Aruban or Dutch Guilder")]
      AWG,
      [Display(Name = "AZN - Azerbaijani New Manat")]
      AZN,
      [Display(Name = "BAM - Bosnian Convertible Marka")]
      BAM,
      [Display(Name = "BBD - Barbadian or Bajan Dollar")]
      BBD,
      [Display(Name = "BDT - Bangladeshi Taka")]
      BDT,
      [Display(Name = "BGN - Bulgarian Lev")]
      BGN,
      [Display(Name = "BHD - Bahraini Dinar")]
      BHD,
      [Display(Name = "BIF - Burundian Franc")]
      BIF,
      [Display(Name = "BMD - Bermudian Dollar")]
      BMD,
      [Display(Name = "BND - Bruneian Dollar")]
      BND,
      [Display(Name = "BOB - Bolivian Boliviano")]
      BOB,
      [Display(Name = "BRL - Brazilian Real")]
      BRL,
      [Display(Name = "BSD - Bahamian Dollar")]
      BSD,
      [Display(Name = "BTN - Bhutanese Ngultrum")]
      BTN,
      [Display(Name = "BWP - Botswana Pula")]
      BWP,
      [Display(Name = "BYR - Belarusian Ruble")]
      BYR,
      [Display(Name = "BZD - Belizean Dollar")]
      BZD,
      [Display(Name = "CAD - Canadian Dollar")]
      CAD,
      [Display(Name = "CDF - Congolese Franc")]
      CDF,
      [Display(Name = "CHF - Swiss Franc")]
      CHF,
      [Display(Name = "CLP - Chilean Peso")]
      CLP,
      [Display(Name = "CNY - Chinese Yuan Renminbi")]
      CNY,
      [Display(Name = "COP - Colombian Peso")]
      COP,
      [Display(Name = "CRC - Costa Rican Colon")]
      CRC,
      [Display(Name = "CUP - Cuban Peso")]
      CUP,
      [Display(Name = "CVE - Cape Verdean Escudo")]
      CVE,
      [Display(Name = "Cyprus, Pounds (expires 2008-Jan-31)")]
      CYP,
      [Display(Name = "CZK - Czech Koruna")]
      CZK,
      [Display(Name = "DJF - Djiboutian Franc")]
      DJF,
      [Display(Name = "DKK - Danish Krone")]
      DKK,
      [Display(Name = "DOP - Dominican Peso")]
      DOP,
      [Display(Name = "DZD - Algerian Dinar")]
      DZD,
      [Display(Name = "EEK - Estonian Krooni")]
      EEK,
      [Display(Name = "EGP - Egyptian Pound")]
      EGP,
      [Display(Name = "ERN - Eritrean Nakfa")]
      ERN,
      [Display(Name = "ETB - Ethiopian Birr")]
      ETB,
      [Display(Name = "EUR - Euro")]
      EUR,
      [Display(Name = "FJD - Fijian Dollar")]
      FJD,
      [Display(Name = "FKP - Falkland Island Pound")]
      FKP,
      [Display(Name = "GEL - Georgian Lari")]
      GEL,
      [Display(Name = "GGP - Guernsey Pound")]
      GGP,
      [Display(Name = "GHS - Ghanaian Cedi")]
      GHS,
      [Display(Name = "GIP - Gibraltar Pound")]
      GIP,
      [Display(Name = "GMD - Gambian Dalasi")]
      GMD,
      [Display(Name = "GNF - Guinean Franc")]
      GNF,
      [Display(Name = "GTQ - Guatemalan Quetzal")]
      GTQ,
      [Display(Name = "GYD - Guyanese Dollar")]
      GYD,
      [Display(Name = "HKD - Hong Kong Dollar")]
      HKD,
      [Display(Name = "HNL - Honduran Lempira")]
      HNL,
      [Display(Name = "HRK - Croatian Kuna")]
      HRK,
      [Display(Name = "HTG - Haitian Gourde")]
      HTG,
      [Display(Name = "HUF - Hungarian Forint")]
      HUF,
      [Display(Name = "IDR - Indonesian Rupiah")]
      IDR,
      [Display(Name = "ILS - Israeli Shekel")]
      ILS,
      [Display(Name = "IMP - Isle of Man Pound")]
      IMP,
      [Display(Name = "INR - Indian Rupee")]
      INR,
      [Display(Name = "IQD - Iraqi Dinar")]
      IQD,
      [Display(Name = "IRR - Iranian Rial")]
      IRR,
      [Display(Name = "ISK - Icelandic Krona")]
      ISK,
      [Display(Name = "JEP - Jersey Pound")]
      JEP,
      [Display(Name = "JMD - Jamaican Dollar")]
      JMD,
      [Display(Name = "JOD - Jordanian Dinar")]
      JOD,
      [Display(Name = "JPY - Japanese Yen")]
      JPY,
      [Display(Name = "KES - Kenyan Shilling")]
      KES,
      [Display(Name = "KGS - Kyrgyzstani Som")]
      KGS,
      [Display(Name = "KHR - Cambodian Riel")]
      KHR,
      [Display(Name = "KMF - Comoran Franc")]
      KMF,
      [Display(Name = "KPW - North Korean Won")]
      KPW,
      [Display(Name = "KRW - South Korean Won")]
      KRW,
      [Display(Name = "KWD - Kuwaiti Dinar")]
      KWD,
      [Display(Name = "KYD - Caymanian Dollar")]
      KYD,
      [Display(Name = "KZT - Kazakhstani Tenge")]
      KZT,
      [Display(Name = "LAK - Lao or Laotian Kip")]
      LAK,
      [Display(Name = "LBP - Lebanese Pound")]
      LBP,
      [Display(Name = "LKR - Sri Lankan Rupee")]
      LKR,
      [Display(Name = "LRD - Liberian Dollar")]
      LRD,
      [Display(Name = "LSL - Basotho Loti")]
      LSL,
      [Display(Name = "LTL - Lithuanian Litas")]
      LTL,
      [Display(Name = "LVL - Latvian Lat")]
      LVL,
      [Display(Name = "LYD - Libyan Dinar")]
      LYD,
      [Display(Name = "MAD - Moroccan Dirham")]
      MAD,
      [Display(Name = "MDL - Moldovan Leu")]
      MDL,
      [Display(Name = "MGA - Malagasy Ariary")]
      MGA,
      [Display(Name = "MKD - Macedonian Denar")]
      MKD,
      [Display(Name = "MMK - Burmese Kyat")]
      MMK,
      [Display(Name = "MNT - Mongolian Tughrik")]
      MNT,
      [Display(Name = "MOP - Macau Pataca")]
      MOP,
      [Display(Name = "MRO - Mauritanian Ouguiya")]
      MRO,
      [Display(Name = "MLT - Maltan Liri")]
      MTL,
      [Display(Name = "MUR - Mauritian Rupee")]
      MUR,
      [Display(Name = "MVR - Maldivian Rufiyaa")]
      MVR,
      [Display(Name = "MWK - Malawian Kwacha")]
      MWK,
      [Display(Name = "MXN - Mexican Peso")]
      MXN,
      [Display(Name = "MYR - Malaysian Ringgit")]
      MYR,
      [Display(Name = "MZN - Mozambican Metical")]
      MZN,
      [Display(Name = "NAD - Namibian Dollar")]
      NAD,
      [Display(Name = "NGN - Nigerian Naira")]
      NGN,
      [Display(Name = "NIO - Nicaraguan Cordoba")]
      NIO,
      [Display(Name = "NOK - Norwegian Krone")]
      NOK,
      [Display(Name = "NPR - Nepalese Rupee")]
      NPR,
      [Display(Name = "NZD - New Zealand Dollar")]
      NZD,
      [Display(Name = "OMR - Omani Rial")]
      OMR,
      [Display(Name = "PAB - Panamanian Balboa")]
      PAB,
      [Display(Name = "PEN - Peruvian Nuevo Sol")]
      PEN,
      [Display(Name = "PGK - Papua New Guinean Kina")]
      PGK,
      [Display(Name = "PHP - Philippine Peso")]
      PHP,
      [Display(Name = "PKR - Pakistani Rupee")]
      PKR,
      [Display(Name = "PLN - Polish Zloty")]
      PLN,
      [Display(Name = "PYG - Paraguayan Guarani")]
      PYG,
      [Display(Name = "QAR - Qatari Riyal")]
      QAR,
      [Display(Name = "RON - Romanian New Leu")]
      RON,
      [Display(Name = "RSD - Serbian Dinar")]
      RSD,
      [Display(Name = "RUB - Russian Ruble")]
      RUB,
      [Display(Name = "RWF - Rwandan Franc")]
      RWF,
      [Display(Name = "SAR - Saudi Arabian Riyal")]
      SAR,
      [Display(Name = "SBD - Solomon Islander Dollar")]
      SBD,
      [Display(Name = "SCR - Seychellois Rupee")]
      SCR,
      [Display(Name = "SDG - Sudanese Pound")]
      SDG,
      [Display(Name = "SEK - Swedish Krona")]
      SEK,
      [Display(Name = "SGD - Singapore Dollar")]
      SGD,
      [Display(Name = "SHP - Saint Helenian Pound")]
      SHP,
      [Display(Name = "SLL - Sierra Leonean Leone")]
      SLL,
      [Display(Name = "SOS - Somali Shilling")]
      SOS,
      [Display(Name = "SPL - Seborgan Luigino")]
      SPL,
      [Display(Name = "SRD - Surinamese Dollar")]
      SRD,
      [Display(Name = "STD - Sao Tomean Dobra")]
      STD,
      [Display(Name = "SVC - Salvadoran Colon")]
      SVC,
      [Display(Name = "SYP - Syrian Pound")]
      SYP,
      [Display(Name = "SZL - Swazi Lilangeni")]
      SZL,
      [Display(Name = "THB - Thai Baht")]
      THB,
      [Display(Name = "TJS - Tajikistani Somoni")]
      TJS,
      [Display(Name = "TMT - Turkmenistani Manat")]
      TMT,
      [Display(Name = "TND - Tunisian Dinar")]
      TND,
      [Display(Name = "TOP - Tongan Pa'anga")]
      TOP,
      [Display(Name = "TRY - Turkish Lira")]
      TRY,
      [Display(Name = "TTD - Trinidadian Dollar")]
      TTD,
      [Display(Name = "TVD - Tuvaluan Dollar")]
      TVD,
      [Display(Name = "TWD - Taiwan New Dollar")]
      TWD,
      [Display(Name = "TZS - Tanzanian Shilling")]
      TZS,
      [Display(Name = "UAH - Ukrainian Hryvna")]
      UAH,
      [Display(Name = "UGX - Ugandan Shilling")]
      UGX,
      [Display(Name = "USD - US Dollar")]
      USD,
      [Display(Name = "UYU - Uruguayan Peso")]
      UYU,
      [Display(Name = "UZS - Uzbekistani Som")]
      UZS,
      [Display(Name = "VEF - Venezuelan Bolivar")]
      VEB,
      [Display(Name = "VEF - Venezuelan Bolivar Fuerte")]
      VEF,
      [Display(Name = "VND - Vietnamese Dong")]
      VND,
      [Display(Name = "VUV - Ni-Vanuatu Vatu")]
      VUV,
      [Display(Name = "WST - Samoan Tala")]
      WST,
      [Display(Name = "XAF - Central African CFA Franc BEAC")]
      XAF,
      [Display(Name = "XAG - Silver Ounce")]
      XAG,
      [Display(Name = "XAU - Gold Ounce")]
      XAU,
      [Display(Name = "XCD - East Caribbean Dollar")]
      XCD,
      [Display(Name = "XDR - IMF Special Drawing Rights")]
      XDR,
      [Display(Name = "XOF - CFA Franc")]
      XOF,
      [Display(Name = "XPD - Palladium Ounce")]
      XPD,
      [Display(Name = "XPF - CFP Franc")]
      XPF,
      [Display(Name = "XPT - Platinum Ounce")]
      XPT,
      [Display(Name = "YER - Yemeni Rial")]
      YER,
      [Display(Name = "ZAR - South African Rand")]
      ZAR,
      [Display(Name = "ZMW - Zambian Kwacha")]
      ZMK,
      [Display(Name = "ZWD - Zimbabwean Dollar")]
      ZWD
   }

   class Program {
      static void Main(string[] args) {
         Console.WriteLine(CurrencyCodes.EUR);
         Console.WriteLine((int)CurrencyCodes.EUR);
         Console.ReadLine();
      }
   }
}

Happy coding!

DistinctBy in Linq (Find Distinct object by Property)

Linq-Distinct-Screenshot1

public class Size {
   public string Name { get; set; }
   public int Height { get; set; }
   public int Width { get; set; }
}

Consider that we have Size Class for advertisement which is having Heigth, Width and Name as property in it. Now Requirement is I have to find out the all product with distinct Name values.

Size[] adv = { 
    new Size { Name = "Leaderboard", Height = 90, Width = 728 }, 
    new Size { Name = "Large Rectangle", Height = 280, Width = 336 }, 
    new Size { Name = "Large Mobile Banner", Height = 100, Width = 320 }, 
    new Size { Name = "Large Skyscraper", Height = 600, Width = 300 },
    new Size { Name = "Medium Rectangle", Height = 250, Width = 300 },
    new Size { Name = "Large Skyscraper", Height = 300, Width = 600 },
};

var lst = adv.Distinct();

foreach (Size p in lst) {
   Console.WriteLine(p.Height + " : " + p.Name);
}

It returns all the size event though two size have same Name value. So this doesn't meet requirement of getting object with distinct Name value.

Way 1: Implement Comparable

First way to achieve the same functionality is make use of overload Distinct function which support to have comparator as argument.

Here is MSDN documentation on this : Enumerable.Distinct<TSource> Method (IEnumerable<TSource>, IEqualityComparer<TSource>).

So for that I implemented IEqualityComparer and created new SizeComparare which you can see in below code.

class SizeComparare : IEqualityComparer<Size> {
   private Func<Size, object> _funcDistinct;
   public SizeComparare(Func<Size, object> funcDistinct) {
      this._funcDistinct = funcDistinct;
   }

   public bool Equals(Size x, Size y) {
      return _funcDistinct(x).Equals(_funcDistinct(y));
   }

   public int GetHashCode(Size obj) {
      return this._funcDistinct(obj).GetHashCode();
   }
}

So in SizeComparare constructor I am passing function as argument, so when I create any object of it I have to pass my project function as argument. In Equal method I am comparing object which are returned by my projection function. Now following is the way how I used this Comparare implementation to satisfy my requirement.

Way 2: Implement Comparable

The second and most eaisest way to avoide this I did in above like using Comparare implementation is just make use of GroupBy like as below

List<Size> list = adv
                     .GroupBy(a => a.Name)
                     //.GroupBy(a => new { a.Name, a.Width })
                     .Select(g => g.First())
                     .ToList();

foreach (Size p in list) {
   Console.WriteLine(p.Height + "x" + p.Width + " : " + p.Name);
}

So this approach also satisfy my requirement easily and output is similar to above two approach. If you want to pass more than on property than you can just do like this .GroupBy(a => new { a.Width, a.Code }).

Linq-Distinct-Screenshot2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Threading;

namespace DistinctBy {
   public class Size {
      public string Name { get; set; }
      public int Height { get; set; }
      public int Width { get; set; }
   }

   class SizeComparare : IEqualityComparer<Size> {
      private Func<Size, object> _funcDistinct;
      public SizeComparare(Func<Size, object> funcDistinct) {
         this._funcDistinct = funcDistinct;
      }

      public bool Equals(Size x, Size y) {
         return _funcDistinct(x).Equals(_funcDistinct(y));
      }

      public int GetHashCode(Size obj) {
         return this._funcDistinct(obj).GetHashCode();
      }
   }

   class Program {
      static void Main(string[] args) {

         Console.WriteLine("Linq Distinct");
         Size[] adv = { 
                        new Size { Name = "Leaderboard", Height = 90, Width = 728 }, 
                        new Size { Name = "Large Rectangle", Height = 280, Width = 336 }, 
                        new Size { Name = "Large Mobile Banner", Height = 100, Width = 320}, 
                        new Size { Name = "Large Skyscraper", Height = 600, Width = 300 },
                        new Size { Name = "Medium Rectangle", Height = 250, Width = 300},
                        new Size { Name = "Large Skyscraper", Height = 300, Width = 600 },
                      };

         var lst = adv.Distinct();

         foreach (Size p in lst) {
            Console.WriteLine(p.Height + "x" + p.Width + " : " + p.Name);
         }

         Console.WriteLine("\nCompare Distinct");

         var list2 = adv.Distinct(new SizeComparare(a => new { a.Name, a.Height }));
         //var list2 = adv.Distinct(new SizeComparare(a => a.Name));

         foreach (Size p in list2) {
            Console.WriteLine(p.Height + "x" + p.Width + " : " + p.Name);
         }

         Console.WriteLine("\nGroup By way");
         List<Size> list = adv
                              .GroupBy(a => a.Name)
                              //.GroupBy(a => new { a.Name, a.Width })
                              .Select(g => g.First())
                              .ToList();

         foreach (Size p in list) {
            Console.WriteLine(p.Height + "x" + p.Width + " : " + p.Name);
         }

         Console.ReadLine();
      }
   }
}

Happy coding!

Data and data access technologies

In my previous post I spoke about key layers of distributed applications. Now we will go through the most crucial layer of any distributed application, the data layer. In this part, you will be introduced to various database technologies, along with .NET-related technologies.

Data can be stored in a wide range of data sources such as relational databases, files on the local filesystems, on the distributed filesystems, in a caching system, in storage located on the cloud, and in memory.

  • Relational databases (SQL server): This is the traditional data source that is designed to store and retrieve data. Queries are written in languages such as T-SQL-utilized Create, Retrieve, Update, and Delete (CRUD) operations model.
  • The filesystem: The filesystem is used to store and retrieve unstructured data on the local disk system in the files. One of the simplest options to store and retrieve data, it has many functional limits and is not distributed by its nature.
  • The Distributed File System (DFS): The DFS is the next level of file system that solves the size and other limitations introduced by local disks. In a nutshell, DFS is a pool of networked computers that store data files.
  • NoSQL databases: NoSQL databases are a new way of storing data in a non-relational fashion. Often, NoSQL databases are used to store large or very large volumes of data, and the biggest difference between these databases and relational database is that NoSQL data stores are schema-free. However, data can be organized by one or more different models, such as key-value stores and document stores, among others.
  • Cloud storage: Any infrastructure located on the cloud solves many issues, such as security, reliability, resilience, and maintenance. Cloud offerings such as Microsoft Azure Storage provide many ways of storing the data in different formats, which can be structured or unstructured. As with many other cloud storage offerings, Microsoft Azure Storage exposes the HTTP REST API, used by any application and client running on any platform that supports HTTP.
  • In-memory stores: In-memory stores are the fastest data stores that are limited in size, not persistent, and cumbersome to use in a distributed multi-server environment. In-memory stores are used to store temporary and volatile data.

ADO.NET and ADO.NET Entity Framework

.NET Framework has several database access options, and the foundation of most of them is ADO.NET. ADO.NET can be called a foundation for every other data access technology on Microsoft stacks. In a nutshell, ActiveX Data Objects .NET (ADO.NET) is a collection of classes that implement program interfaces to simplify the process of connecting to data stores without depending on the structure and implementation of a concrete data store and its location. The challenge that it offers is that most developers must write complex data access code (between the application and the database) that requires them to have a good understanding of the database itself, of raw tables, views, stored procedures, the database schema, table definitions and parameters, results, and so on.

This is mostly solved by the Object-relational mapping (ORM) approach. Programmers create a conceptual model of the data and write their data access code against that model, while an additional layer provides a bridge between the entity-relationship model and the actual data store. Entity Framework generates database entities according to database tables and provides the mechanism for basic CRUD operations, managing 1-to-1, 1-to-many, and many-to-many relationships, and the ability to have inheritance relationships between entities among others.

Basically, you have the ability to "talk" about your model not with the database but with the class model you wrote or generated from a database using Entity Framework. This is achieved by the creation of a combination of XML schema files, code generation, and the ADO.NET Entity Framework APIs. The schema files are used to define a conceptual layer, to be used as a map between the data store and the application. The ADO.NET Entity Framework allows you to write the application that uses classes that are generated from the conceptual schema. Entity Framework then takes care of the rest.

Another important component of Entity Framework that is often used by developers is Language Integrated Query (LINQ). It adds data querying capabilities to .NET languages and extends the language with SQL-like query expressions.

There are three approaches to working with Entity Framework in the project:

  • Database-first: This approach is used when you already have a database that is going to be used as a data source.
  • Model-first: This approach is used when you have no database. First, you draw the model in the Visual Designer and then instruct it to create the database for you with all the tables.
  • Code-first: This approach is used often as it provides a way to write your model in code as classes and instruct Entity Framework to generate the database with objects described in the code.

Key layers of distributed applications

Every application that is going to be used by end users should be designed appropriately as users are expecting to process information from various data sources that might be geographically distributed. They are also expecting this information to be up-to-date and capable of being inflected very fast. Designing such applications is not an easy task and involves integration among different groups of components. Let's review the layers that form a typical distributed application.

The responsibilities in a distributed system can be divided into four layers:

  • The data layer
  • The business logic layer
  • The server layer
  • The user interface layer

The data layer

The data layer is responsible for storing and accessing data and for querying, updating, or deleting this data. This layer includes the logic of data access and store performance that can be a complicated task, especially dealing with a large volume of data distributed among different data sources.

The business logic layer

The business logic layer is responsible for the crucial part of the application: logic that is executed between the client and data layers. Basically, the business logic layer contains the logic of the application. It is the "brain" that coordinates the integration between the data layer that is used for reading and storing the data and the user interface layer that interacts with the client.

The server layer

The server layer is sometimes called a services layer, and that is an accurate term as well. The server layer is responsible for exposing some of the capabilities of the application that can be consumed by other services and used as a data source, for example. This layer works as the interface between our application and the world of other services, which is different from that of the end users.

The server layer is an extremely important part of every distributed application; its proper design can impact the overall performance of the system as it is responsible for the defining of the collaboration principles between parts of applications and the distribution of load and data. It contains security mechanisms that validate requests as well.

The user interface layer

The user interface layer is the layer that is used by clients interacting with the application. This layer must contain only that part of the system that is responsible for rendering the interface consisting of the data, user interface components, and other things important in the process of interacting between the user and the application.

This layer also has the logic that can be used in the process of adapting the application user interface layer for different form factors, people, cultures, interfaces (such as touchscreens), screen sizes, and resolutions. At the same time, it must be simple and effective and must provide a smooth user experience.

Properly designed user interface design is important; if the user interface is not friendly and experience is not smooth or if the user does not understand how the system works and how it should be used, the application will not be used.

C# and 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.

First of all we create an MVC project in C#. Under Controller folder in the HomeController we add this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HTML5DragAndDrop.Controllers {
   public class HomeController : Controller {
      ITestDatabase _testDatabase = new TestDatabase();

      public ActionResult Index() {
         return View();
      }

      public ActionResult About() {
         ViewBag.Message = "Your application description page.";

         return View();
      }

      public ActionResult Contact() {
         ViewBag.Message = "Your contact page.";

         return View();
      }

      [HttpPost]
      public JsonResult InsertTestElements(string testElement) {
         int? insertResult = null;

         if (!string.IsNullOrEmpty(testElement)) {
            string[] elementData = testElement.Split(':');

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

            insertResult = _testDatabase.InsertElement(symbol, name);
         }

         return Json(insertResult);
      }
   }
}

Now we create a folder in the root of the project called Code. Under this folder we create two new files:

ITestDatabase.cs

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

public interface ITestDatabase {
   int InsertElement(string symbol, string name);
}   
 

TestDatabase.cs

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

public class TestDatabase : ITestDatabase {
   /// <summary>
   /// Save an element in the database and return the new ID
   /// </summary>
   /// <param name="symbol"></param>
   /// <param name="name"></param>
   /// <returns></returns>
   public int InsertElement(string symbol, string name) {
      // save the element in database
      // now it returns just a number: it will be the Id of the record
      return 1;
   }
}

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

DragAndDrop_App

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

h5utils.js

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

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);
   InsertTestElement(element);

   return false;
});

In the Index.cshtml we change as following code:

Index.cshtml

@{
   ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Drag and drop example</h1>
    <p class="lead">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.</p>
    <p><a href="http://puresourcecode.com" 
    class="btn btn-primary btn-lg">Learn more »</a></p>
</div>

<div class="row">
    <p id="1A">1: A</p>
    <p id="2B">2: B</p>
    <p id="3C">3: C</p>
    <p id="4D">4: D</p>
    <p id="5E">5: E</p>
    <div id="divBoxElements 
       style="border: 1px solid #dcdcdc; width: 300px; height: 300px;"
    ></div>
</div>

@section scripts {
    <script src="~/Scripts/html5utils.js"></script>
    <script>
        <!--
        function InsertTestElement(element) {
            var url = '@Url.Action("InsertTestElements", "Home")';

            $.post(url, { testElement: element }, function (data) {
                switch (data) {
                    case 1:
                        divBoxElements.innerHTML = 
                             element + " inserted OK";
                        setTimeout(function () { 
                             divBoxElements.innerHTML = ""; }, 2000);
                        break;

                    default:
                        alert("Error inserting the element");
                }
            });
        }
        //-->
    </script>
}

Download or fork tthis code on Github.

Happy coding!

Insert spaces between words on a camel-cased token

Here's an extension method that I have used extensively for this kind of thing

public static string SplitCamelCase( this string str )
{
    return Regex.Replace( 
        Regex.Replace( 
            str, 
            @"(\P{Ll})(\P{Ll}\p{Ll})", 
            "$1 $2" 
        ), 
        @"(\p{Ll})(\P{Ll})", 
        "$1 $2" 
    );
}

It also handles strings like "FistName", converting it to "First Name".

Happy coding!

WebRole and WorkerRole Templates in VS 2015

Download the Azure SDK for Visual Studio 2015 from here: https://azure.microsoft.com/en-us/downloads/

It should force you to close Visual Studio, but if it doesn't, do so anyways. Once it's installed, you can reboot it.

When you go to add a new project, you can look under Cloud and then choose Azure Cloud Service.

Visual-Studio-2015-New-Project-Azure-Cloud-Service

This will give you the same old familiar screen, where you can choose a Web Role or Worker Role:

Visual-Studio-2015-New-Project-Azure-Cloud-Service

Microsoft Azure Storage Explorer for OS X, Linux, and Windows (and it's free)

microsoft-azure-storage-explorer-screenshot

Microsoft Azure Storage Explorer (Preview) is a standalone app from Microsoft that allows you to easily work with Azure Storage data. The Preview release currently supports Azure Blobs only. Tables, queues, and files are coming soon.

Features

  • Mac OS X, Linux, and Windows versions
  • Sign in to view your Storage Accounts – use your Org Account, Microsoft Account, 2FA, etc
  • Add Storage Accounts by account name and key, as well as custom endpoints
  • Add Storage Accounts for Azure China
  • Add blob containers with Shared Access Signatures (SAS) key
  • Local development storage (use storage emulator, Windows-only)
  • ARM and Classic resource support
  • Create and delete blobs, queues, or tables
  • Search for specific blobs, queues, or tables
  • Explore the contents of blob containers
  • View and navigate through directories
  • Upload, download, and delete blobs and folders
  • Open and view the contents text and picture blobs
  • View and edit blob properties and metadata
  • Generate SAS keys
  • Manage and create Stored Access Policies (SAP)
  • Search for blobs by prefix
  • Drag ‘n drop files to upload or download

Known Issues

  • Cannot view/take actions on Queues or Tables (coming soon!)
  • Linux install needs gcc version updated or upgraded – steps to upgrade are below:
    • sudo add-apt-repository ppa:ubuntu-toolchain-r/test
    • sudo apt-get update
    • sudo apt-get upgrade
    • sudo apt-get dist-upgrade
  • After reentering credentials, you may need to manually refresh Storage Explorer to show your Storage Accounts

Project Deco

Looking for the old open-source version? It's still available on GitHub!

C# MVC: HttpContextBase from HttpContext.Current

It's easy by using the HttpContextWrapper

HttpContextBase basecontext = (new HttpContextWrapper(HttpContext.Current));
Happy coding!

How to upload a file in an ASP.Net MVC page

For this example, I’m using a controller named “HomeController”, with the view “Index”. When you click the “Submit” button on the view, it will be submitted to the “Save” method of HomeController.

Index.cshtml

@using(Html.BeginForm("Save", "Home", FormMethod.Post, 
               new {enctype = "multipart/form-data"}))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit"/>
            </td>
        </tr>
    </table>
}

Notice the two additional parameters for BeginForm

FormMethod.Post, new {enctype = "multipart/form-data"}

You need those to have the file included in the HTTP Post action to the Save method on the controller. Other than that, you just need a file input control, with a unique name attribute set.

HomeController

using System;
using System.Web;
using System.Web.Mvc;

namespace FileUpload.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Save(FormCollection formCollection)
        {
            if(Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if((file != null) && (file.ContentLength > 0) && 
                   !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    file.InputStream.Read(fileBytes, 0, 
                                       Convert.ToInt32(file.ContentLength));

                    string pth = Path.GetFileName(fileName);
                    // change the folder
                    file.SaveAs(Server.MapPath("~/Uploads") + "/" + pth);
                }
            }

            return View("Index");
        }
    }
}

The Request object is a base object for handling HTTP requests. Since we set the FormMethod and enctype in the view, we have access to the file that was submitted on the page.

If the Request object isn’t null, we can check for the file by getting the HttpPostedFileBase from the Request object’s list of files, using its name (which is why a unique name was required for the file input control on the view).

Then we do some checking, to make sure the file actually has data, and get its information.

If you’re going to save the files somewhere (which is probably why you’re letting people upload files), then you’re going to need a way to display it for them later. To display a file within a browser, you need to know its ContentType. This will let the browser display it in the correct way.

With the byte array of the file’s contents, you can either save it to the database, in a varbinary column [for SQL Server], or write it out to disk, or some other document storage location.

Where you should save the files depends on what you’re going to do with them, how large they are, and what type of file they are.

If you see an error like

The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The SaveAs method is configured to require a rooted path, and the path '~/App_data/Uploads/1.pdf' is not rooted.

the problem is in the SaveAs function. You must pass a valid full path such as “C:\Uploads\Test\1.png”. For this reason I created in the root of the project a folder called Uploads and use Server.MapPath to find the full path.

Happy coding!

Advertsing

125X125_06

TagCloud

MonthList

CommentList