How to update the data in listview in Xamarin.Forms?

First you add a new class as a ViewModel like:

public class RoomViewModel : BaseViewModel
{
   [here following code]
}

If you don't have BaseViewModel try to download from nuget Refractored.MvvmHelpers. Then in your class define an observable collection like

  public ObservableCollection<RoomRecommandation> _roomSuggestionList = 
               new ObservableCollection<RoomRecommandation>();
  
  public ObservableCollection<RoomRecommandation> Recommendations
  {
     get { return _roomSuggestionList; }
  }

In your ContentPage add a listview like:

<ListView ItemsSource="{Binding Recommendations}">
 <ListView.ItemTemplate>
   <DataTemplate>
     <ViewCell>
       <Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
         <Grid.RowDefinitions>
           <RowDefinition Height="" />
         </Grid.RowDefinitions>
         <Grid.ColumnDefinitions>
           <ColumnDefinition Width="Auto" />
           <ColumnDefinition Width="" />
           <ColumnDefinition Width="Auto" />
         </Grid.ColumnDefinitions>
         <controls:CircleImage Grid.Column="0" BorderColor="#DDD3CB" 
                               BorderThickness="3" WidthRequest="66"
                               HorizontalOptions="CenterAndExpand" 
                               VerticalOptions="CenterAndExpand" 
                               Aspect="AspectFill" 
                               Source="{Binding Image}" />
         <Label Grid.Column="1" Text="{Binding Description}" 
                               VerticalOptions="Start" />
         <Label Grid.Column="2" Text="{Binding Price, StringFormat='£{0}'"
                               FontSize="Small" VerticalOptions="Start" />
        </Grid>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
 </ListView>

Then in your ContentPage code:

  RoomViewModel vm = null;
  public RoomPage ()
  {
      InitializeComponent ();
      LoadData();
  }

  public void LoadData()
  {
      if (vm == null)
      {
          vm = new RoomViewModel();
          BindingContext = vm;
      }
  }

Happy coding!

Xamarin Forms MasterDetail Page Navigation Recipe

In this recipe I will show you how to add a hamburger menu to your Xamarin Forms application using the MasterDetailPage class. The Xamarin.Forms MasterDetail Page consists of one page for the master and one or more pages for the detail.

When used for the main navigation, as in this recipe, we will have a single master page and 4 detail pages. The code for this recipe comes from the Xamarin Forms CRM sample. I have simplified and streamlined the code, and a full Xamarin Studio solution is included at the bottom of this post.

Xamarin.Forms MasterDetail

Think of the MasterDetailPage as the traffic cop of your application navigation. When a user clicks on the hamburger menu, Xamarin.Forms MasterDetail pushes the menu onto the screen. Then when the user taps on a menu item, MasterDetail creates the target page and pushes it onto the stack. Besides those two things, and some styling, MasterDetail doesn’t do much. Have a look at the code.

public class RootPage : MasterDetailPage
{
	public RootPage ()
	{
		var menuPage = new MenuPage ();
		menuPage.Menu.ItemSelected += (sender, e) => 
                             NavigateTo (e.SelectedItem as MenuItem);
		Master = menuPage;
		Detail = new NavigationPage (new ContractsPage ());
	}

	void NavigateTo (MenuItem menu)
	{
		Page displayPage = (Page)Activator.CreateInstance (menu.TargetType);
		Detail = new NavigationPage (displayPage);
		IsPresented = false;
	}
}

Pretty simple right? The only complicated bit is with the (Page)Activator.CreateInstance (menu.TargetType) part, but if you have been doing C# on .Net for a while, you probably have seen it before. All it is, is another way of creating objects.

MasterBehavior

In Xamarin.Forms 1.3, the Xamarin.Forms MasterDetail MasterDetail Page received a new property called MasterBehavior. This property controls how the menu will react when activated. The enumeration MasterBehavior has a few options and they are:

public enum MasterBehavior
{
    Default,
    Popover,
    Split,
    SplitOnLandscape,
    SplitOnPortrait
}

The normal behavior of the MasterDetailPage in landscape mode is “SplitOnLandscape”. I think splitting is normal when using the MasterDetailPage for detail drill in type navigation but not when using it as a hamburger menu or your apps main navigation. When using the MasterDetailPage for app navigation, I set the behavior to popover.

The Menu Page

The menu page is just what the name implies, it’s the Xamarin Forms page that will be shown when the user clicks the menu button. This is the master part of the Xamarin.Forms MasterDetail Page. Our MenuPage is a simple content page with a StackLayout containing a label and a ListView of our menu items.

Please note the public property Menu. This property allows our MasterDetail page access to the ItemSelected event. When the event is fired, the item selected will be sent to the NavigateTo method on the master detail object.

public class MenuPage : ContentPage
{
	public ListView Menu { get; set; }

	public MenuPage ()
	{
		Icon = "settings.png";
		Title = "menu"; // The Title property must be set.
		BackgroundColor = Color.FromHex ("333333");

		Menu = new MenuListView ();

		var menuLabel = new ContentView {
			Padding = new Thickness (10, 36, 0, 5),
			Content = new Label {
				TextColor = Color.FromHex ("AAAAAA"),
				Text = "MENU", 
			}
		};

		var layout = new StackLayout { 
			Spacing = 0, 
			VerticalOptions = LayoutOptions.FillAndExpand
		};
		layout.Children.Add (menuLabel);
		layout.Children.Add (Menu);

		Content = layout;
	}
}

Menu Item

Menu Item is a simple type that holds our menu data and the most important data is the Target type. When a user clicks on a menu item, the NavigateTo method will create a new page from the TargetType, and push that page onto the stack.

public class MenuItem
{
	public string Title { get; set; }
	public string IconSource { get; set; }
	public Type TargetType { get; set; }
}

Menu List View

The menu list view couldn’t be simpler; we use the built in ImageCell for the rows and set the bindings to the properties on the MenuItem type. We set the first item as the selected item and also used it when constructing the MasterDetail Page initial detail class.

public class MenuListView : ListView
{
	public MenuListView ()
	{
		List data = new MenuListData ();

		ItemsSource = data;
		VerticalOptions = LayoutOptions.FillAndExpand;
		BackgroundColor = Color.Transparent;

		var cell = new DataTemplate (typeof(ImageCell));
		cell.SetBinding (TextCell.TextProperty, "Title");
		cell.SetBinding (ImageCell.ImageSourceProperty, "IconSource");

		ItemTemplate = cell;
	}
}

Menu List Data

The MenuListData class is a data structure holding our applications navigation. In your app you could get this data from the database or configuration file. The menu structure of my application doesn’t change much, so I just use code.

public class MenuListData : List
{
	public MenuListData ()
	{
		this.Add (new MenuItem () { 
			Title = "Contracts", 
			IconSource = "contracts.png", 
			TargetType = typeof(ContractsPage)
		});

		this.Add (new MenuItem () { 
			Title = "Leads", 
			IconSource = "Lead.png", 
			TargetType = typeof(LeadsPage)
		});

		this.Add (new MenuItem () { 
			Title = "Accounts", 
			IconSource = "Accounts.png", 
			TargetType = typeof(AccountsPage)
		});

		this.Add (new MenuItem () {
			Title = "Opportunities",
			IconSource = "Opportunity.png",
			TargetType = typeof(OpportunitiesPage)
		});
	}
}

The Content Pages

These pages are what is created when a user clicks on our menu items.

public class ContractsPage : ContentPage
{
	public ContractsPage (){}
}

public class LeadsPage : ContentPage
{
	public LeadsPage (){}
}

public class AccountsPage : ContentPage
{
	public AccountsPage (){}
}

public class OpportunitiesPage : ContentPage
{
	public OpportunitiesPage (){}
}

Download the source code PSC-MasterDetail.zip (79.74 kb)

Happy coding!

Xamarin Studio: complete uninstall on Mac

Remove these directories:

/Applications/Xamarin Studio.app
/Developer/MonoTouch
/Developer/MonoAndroid
/Library/Frameworks/Mono.framework
/Library/Frameworks/Xamarin.Mac.framework
/Library/Frameworks/Xamarin.Android.framework

Locations in your user directory:

~/Library/Caches/Xamarin
~/Library/Caches/XamarinStudio-4.0
~/Library/Developer/Xamarin
~/Library/Developer/XamarinStudio
~/Library/Logs/Xamarin
~/Library/Logs/XamarinStudio-4.0
~/Library/Preferences/Xamarin
~/Library/Preferences/XamarinStudio-4.0
~/Library/Xamarin
~/Library/Xamarin.Mac
~/Library/MonoTouch
~/Library/MonoAndroid
~/Library/XamarinStudio-4.0

That's all there is afaik.

ASP.NET LinkButton: children disappears after postback

I have a LinkButton with image and label inside it or tags i and span as in the following picture.example_linkbutton

The code in the page is:

<asp:LinkButton ID="LinkButton1" runat="server">
    <i class="glyphicon glyphicon-plus"></i>
    <span class="js-add-button" runat="server" id="Span1">Add New</span>
</asp:LinkButton>

After a postback everything inside the LinkButton disappeared. I've spent two days to understand why and the solution is very easy.

<asp:LinkButton ID="LinkButton1" runat="server">
    <i class="glyphicon glyphicon-plus" runat="server"></i>
    <span class="js-add-button" runat="server" id="Span1">Add New</span>
</asp:LinkButton>

The tag i doesn't have runat="server" and for that you lost all content inside the LinkButton.

Happy coding!

Remove multiple line in the same file with C#

Read the file, remove the multiple line (but it saves one of them) in memory and put the contents back to the file (overwriting) and create a backup file with the original file.

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DelMultiLine {
   class Program {
      static void Main(string[] args) {
         if (args.Count() == 0 || args.Count() > 2) {
            Console.WriteLine("\nDelMultiLine (by Enrico Rossini - puresourcecode.com)");
            Console.WriteLine("-----------------------------------------------------------------------");
            Console.WriteLine("Remove duplicate line in a file\n");
            Console.WriteLine("Usage:");
            Console.WriteLine("   delmultiline <Filename> <resultFilename>\n");
            Console.WriteLine("filename:       define a full path for the file you want to elaborate");
            Console.WriteLine("resultFilename: define the full path for the original file for a backup");
            Environment.Exit(0);
         }

         string file1 = args[0];
         string file2 = "";

         if (args.Count() == 1) {
            if (string.IsNullOrEmpty(file2)) {
               file2 = file1 + ".old";
            }
            else {
               file2 = args[1];
            }
         }

         Console.WriteLine(string.Format("Reading {0} in progress...", args[0]));
         string[] lines = File.ReadAllLines(file1);
         List<string> newline = new List<string>();

         for (int i = 0; i < lines.Length; i++) {
            newline.Add(lines[i]);
         }

         Console.WriteLine("Deleting multiple line in progress...");
         for (int i = 0; i < lines.Length; i++) {
            List<string> temp = new List<string>();
            int duplicate_count = 0;

            for (int j = newline.Count - 1; j >= 0; j--) {
               //checking for duplicate records
               if (lines[i] != newline[j])
                  temp.Add(newline[j]);
               else {
                  duplicate_count++;
                  if (duplicate_count == 1)
                     temp.Add(lines[i]);
               }
            }
            newline = temp;
         }

         // reverse the array
         newline.Reverse();

         //assigning into a string array
         string[] newFile = newline.ToArray();
         newline.Sort();

         // move the original file in a new location
         Console.WriteLine(string.Format("Copying original file in {0}", args[0]));
         File.Move(file1, file2);

         //now writing the data to a text file
         Console.WriteLine(string.Format("Write new file {0}", args[0]));
         File.WriteAllLines(file1, newFile);

         Console.WriteLine("Convertion is finished.");
         Console.WriteLine("\nPress any key to continue...");
         Console.ReadLine();
      }
   }
}

Happy coding!

Dijkstra's Algorithm in C# with Generics

I recently needed to to implement a shortest-path algorithm (to identify preferred domain controllers using site link costs) and I found Dijkstra's Algorithm

Path class

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

namespace DijkstraAlgorithm {
   public class Path<T> {
      public T Source { get; set; }

      public T Destination { get; set; }

      /// <summary>
      /// Cost of using this path from Source to Destination
      /// </summary>
      /// 
      /// Lower costs are preferable to higher costs
      /// </remarks>
      public int Cost { get; set; }
   }
}

ExtensionMethods class

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

namespace DijkstraAlgorithm {
   public static class ExtensionMethods {
      /// <summary>
      /// Adds or Updates the dictionary to include the destination and its associated cost 
      /// and complete path (and param arrays make paths easier to work with)
      /// </summary>
      public static void Set<T>(this Dictionary<T, KeyValuePair<int, LinkedList<Path<T>>>> Dictionary, 
                                T destination, int Cost, params Path<T>[] paths) {
         var CompletePath = paths == null ? new LinkedList<Path<T>>() : new LinkedList<Path<T>>(paths);
         Dictionary[destination] = new KeyValuePair<int, LinkedList<Path<T>>>(Cost, CompletePath);
      }
   }
}

Engine class

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

namespace DijkstraAlgorithm {
   /// <summary>
   /// Calculates the best route between various paths, using Dijkstra's algorithm
   /// </summary>
   public static class Engine {
      public static LinkedList<Path<T>> CalculateShortestPathBetween<T>(T source, T destination, IEnumerable<Path<T>> Paths) {
         return CalculateFrom(source, Paths)[destination];
      }

      public static Dictionary<T, LinkedList<Path<T>>> CalculateShortestFrom<T>(T source, IEnumerable<Path<T>> Paths) {
         return CalculateFrom(source, Paths);
      }

      private static Dictionary<T, LinkedList<Path<T>>> CalculateFrom<T>(T source, IEnumerable<Path<T>> Paths) {
         // validate the paths
         if (Paths.Any(p => p.Source.Equals(p.Destination)))
            throw new ArgumentException("No path can have the same source and destination");

         // keep track of the shortest paths identified thus far
         Dictionary<T, KeyValuePair<int, LinkedList<Path<T>>>> ShortestPaths = new Dictionary<T, KeyValuePair<int, LinkedList<Path<T>>>>();

         // keep track of the locations which have been completely processed
         List<T> LocationsProcessed = new List<T>();

         // include all possible steps, with Int.MaxValue cost
         Paths.SelectMany(p => new T[] { p.Source, p.Destination })           // union source and destinations
                 .Distinct()                                                  // remove duplicates
                 .ToList()                                                    // ToList exposes ForEach
                 .ForEach(s => ShortestPaths.Set(s, Int32.MaxValue, null));   // add to ShortestPaths with MaxValue cost

         // update cost for self-to-self as 0; no path
         ShortestPaths.Set(source, 0, null);

         // keep this cached
         var LocationCount = ShortestPaths.Keys.Count;

         while (LocationsProcessed.Count < LocationCount) {
            T _locationToProcess = default(T);

            //Search for the nearest location that isn't handled
            foreach (T _location in ShortestPaths.OrderBy(p => p.Value.Key).Select(p => p.Key).ToList()) {
               if (!LocationsProcessed.Contains(_location)) {
                  if (ShortestPaths[_location].Key == Int32.MaxValue)
                     return ShortestPaths.ToDictionary(k => k.Key, v => v.Value.Value); //ShortestPaths[destination].Value;

                  _locationToProcess = _location;
                  break;
               }
            } // foreach

            var _selectedPaths = Paths.Where(p => p.Source.Equals(_locationToProcess));

            foreach (Path<T> path in _selectedPaths) {
               if (ShortestPaths[path.Destination].Key > path.Cost + ShortestPaths[path.Source].Key) {
                  ShortestPaths.Set(
                      path.Destination,
                      path.Cost + ShortestPaths[path.Source].Key,
                      ShortestPaths[path.Source].Value.Union(new Path<T>[] { path }).ToArray());
               }
            }

            //Add the location to the list of processed locations
            LocationsProcessed.Add(_locationToProcess);
         } // while

         return ShortestPaths.ToDictionary(k => k.Key, v => v.Value.Value);
         //return ShortestPaths[destination].Value;
      }
   }
}

Test

using System.Linq;
using DijkstraAlgorithm;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1 {
   [TestClass]
   public class UnitTest1 {
      [TestMethod]
      public void Calculate_A_to_D_given_AB_BC_CD__should_be__ABCD() {
         var Results = Engine.CalculateShortestPathBetween(
             "A",
             "D",
             new Path<string>[] {
                new Path<string>() { Source = "A", Destination = "B", Cost = 3 },
                new Path<string>() { Source = "B", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "C", Destination = "D", Cost = 3 }
             });

         Results.Sum(r => r.Cost).Should().Be(9);
         Results.Count.Should().Be(3);

         Results.First().Cost.Should().Be(3);
         Results.First().Source.Should().Be("A");
         Results.First().Destination.Should().Be("B");

         Results.Skip(1).First().Cost.Should().Be(3);
         Results.Skip(1).First().Source.Should().Be("B");
         Results.Skip(1).First().Destination.Should().Be("C");

         Results.Skip(2).First().Cost.Should().Be(3);
         Results.Skip(2).First().Source.Should().Be("C");
         Results.Skip(2).First().Destination.Should().Be("D");
      }

      [TestMethod]
      public void Calculate_A_to_D_given_AB_BC_CD_DE__should_be__ABCD() {
         var Results = Engine.CalculateShortestPathBetween(
             "A",
             "D",
             new Path<string>[] {
                new Path<string>() { Source = "A", Destination = "B", Cost = 3 },
                new Path<string>() { Source = "B", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "C", Destination = "D", Cost = 3 },
                new Path<string>() { Source = "D", Destination = "E", Cost = 3 }
             });

         Results.Sum(r => r.Cost).Should().Be(9);
         Results.Count.Should().Be(3);

         Results.First().Cost.Should().Be(3);
         Results.First().Source.Should().Be("A");
         Results.First().Destination.Should().Be("B");

         Results.Skip(1).First().Cost.Should().Be(3);
         Results.Skip(1).First().Source.Should().Be("B");
         Results.Skip(1).First().Destination.Should().Be("C");

         Results.Skip(2).First().Cost.Should().Be(3);
         Results.Skip(2).First().Source.Should().Be("C");
         Results.Skip(2).First().Destination.Should().Be("D");
      }

      [TestMethod]
      public void Calculate_A_to_D_given_AB_AC_AD_AE_BC_CD_DE__should_be__ACD() {
         var Results = Engine.CalculateShortestPathBetween(
             "A",
             "D",
             new Path<string>[] {
                new Path<string>() { Source = "A", Destination = "B", Cost = 3 },
                new Path<string>() { Source = "A", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "A", Destination = "D", Cost = 7 }, // set this just above ABC (3+3=6)
                new Path<string>() { Source = "A", Destination = "E", Cost = 3 },
                new Path<string>() { Source = "B", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "C", Destination = "D", Cost = 3 },
                new Path<string>() { Source = "D", Destination = "E", Cost = 3 }
             });

         Results.Sum(r => r.Cost).Should().Be(6);
         Results.Count.Should().Be(2);

         Results.First().Cost.Should().Be(3);
         Results.First().Source.Should().Be("A");
         Results.First().Destination.Should().Be("C");

         Results.Skip(1).First().Cost.Should().Be(3);
         Results.Skip(1).First().Source.Should().Be("C");
         Results.Skip(1).First().Destination.Should().Be("D");
      }

      [TestMethod]
      public void Calculate_A_to_D_given_AB_AC_AD_AE_BC_CD_DE__should_be__AD() {
         var Results = Engine.CalculateShortestPathBetween(
             "A",
             "D",
             new Path<string>[] {
                new Path<string>() { Source = "A", Destination = "B", Cost = 3 },
                new Path<string>() { Source = "A", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "A", Destination = "D", Cost = 5 }, // set this just below ABC (3+3=6)
                new Path<string>() { Source = "A", Destination = "E", Cost = 3 },
                new Path<string>() { Source = "B", Destination = "C", Cost = 3 },
                new Path<string>() { Source = "C", Destination = "D", Cost = 3 },
                new Path<string>() { Source = "D", Destination = "E", Cost = 3 }
             });

         Results.Sum(r => r.Cost).Should().Be(5);
         Results.Count.Should().Be(1);

         Results.Single().Cost.Should().Be(5);
         Results.Single().Source.Should().Be("A");
         Results.Single().Destination.Should().Be("D");
      }
   }
}

You can find the code on GitHub.

Happy coding!

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.

Advertsing

125X125_06





TagCloud

MonthList

CommentList