Wednesday, 19 December 2018

ConcurrentDictionary in C# - Introduction, Examples

One of the best thread safe programming we can do with ConcurrentDictionary ,
ConcurrentDictionary is one of five collection classes introduced in .NET 4.0. It exists in System.Collections.Concurrent namespace. ConcurrentDictionary is thread-safe collection class to store key/value pairs. ConcurrentDictionary can be used with multiple threads concurrently. 
Without ConcurrentDictionary class, if we have to use Dictionary class with multiple threads, then we have to use locks to provides thread-safety which is always error-prone. ConcurrentDictionary provides you an easy option. It internally manages the locking gives you an easy interface to add/update items.
ConcurrentDictionary uses different methods to add, retrieve, update and remove items.

Add items in ConcurrentDictionary

We can use TryAdd method to add a new key/value pair. Below is the example:
1
2
3
4
5
6
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    dict.TryAdd("1", "First");
    dict.TryAdd("2", "Second");
}
TryAdd methods returns true if key/value pair is added, and returns false if key already exists in dictionary.
1
2
3
4
5
6
7
8
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    bool firstItem = dict.TryAdd("1", "First");  //returns true
    bool secondItem = dict.TryAdd("2", "Second");  //returns  true
 
    bool thirdItem = dict.TryAdd("1", "Third"); //returns false;
}
In the above example, we try to add new item with the same key, TryAdd method returns false.

Retrieve Single Item using Key

To retrieve single item, ConcurrentDictionary provides TryGetValue method.
We have to provide Key in the TryGetValue method. It takes the out parameter to return the value of key. TryGetValue returns true if key exists, or returns false if key does not exists in dictionary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dict = new ConcurrentDictionary<string, string>();
    bool firstItem = dict.TryAdd("1", "First");
    bool secondItem = dict.TryAdd("2", "Second");
 
    string itemValue1;
    string itemValue2;
    bool isItemExists1 = dict.TryGetValue("1", out itemValue1);  //returns true
    Console.WriteLine(itemValue1); //Print "First"
 
    bool isItemExists2 = dict.TryGetValue("3", out itemValue2);  //returns false
    Console.WriteLine(itemValue2); //Print blank
}

Retrieve all items in ConcurrentDictionary

As ConcurrentDictionary implements the IEnumerable interface, we can use foreach loop to enumerate all items in dictionary.
As with other dictionary class in .NET, It also does not returns all items in the order we have added in dictionary. We may get second item in first index, and first item in second index. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    foreach(var item in dictionary)
    {
        Console.WriteLine(item.Key + "-" + item.Value);
    }
    //Returns
    // 4- Fourth
    // 3 - Third
    // 2 - Second
    // 1 - First
}
Note: Enumeration is thread-safe in ConcurrentDictionary.
We have created two tasks. First task is adding new values and second task is enumerating all the items. We will not get any exception in below example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
 
 
    Task t1 = Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < 100; ++i)
            {
                dictionary.TryAdd(i.ToString(), i.ToString());
                Thread.Sleep(100);
            }
        });
 
    Task t2 = Task.Factory.StartNew(() =>
        {
            Thread.Sleep(300);
            foreach (var item in dictionary)
            {
                Console.WriteLine(item.Key + "-" + item.Value);
                Thread.Sleep(150);
            }
        });
 
    try
    {
        Task.WaitAll(t1, t2);
    }
    catch (AggregateException ex) // No exception
    {
        Console.WriteLine(ex.Flatten().Message); 
    }
 
}

Update item

ConcurrentDictionary provides TryUpdate methods to update any key. TryUpdate takes three parameters. Three parameters are:
  1. Key - key to modify
  2. New Value - new value of the key
  3. Old Value - old value of the key
TryUpdate method update only when Key value matches with the old value, then it update the key with new value. It returns true if it successfully update the value else returns false. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    string newValue;
 
    bool returnTrue = dictionary.TryUpdate("1", "New Value", "First"); //Returns true
    dictionary.TryGetValue("1", out newValue);
    Console.WriteLine(newValue); //Print "New Value"
 
    bool returnsFalse = dictionary.TryUpdate("2", "New Value 2", "No Value"); //Returns false
    dictionary.TryGetValue("2", out newValue);  //Returns "Second" Old value
    Console.WriteLine(newValue);    //Print "Second"
}

Remove item

For remove any item, ConcurrentDictionary provides TryRemove method. TryRemove returns true if it successfully removes the item else returns false. It also returns the removed item in the out parameter. Below is the example:
1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    string removedItem;
    bool result = dictionary.TryRemove("2", out removedItem); //Returns true
    Console.WriteLine(removedItem); //Print "Second"
}

Remove all items in ConcurrentDictionary

For removing all items, we can use Clear method. It removes all the keys and its values from dictionary. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
 
    dictionary.Clear();
 
    foreach (var item in dictionary) //enumerate 0 times
    {
        Console.WriteLine(item.Key);
    }
}

Count all Items

ConcurrentDictionary provides Count method to returns the total number of items. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    int totalItems = dictionary.Count(); // Returns 4
 
    int filterItems = dictionary.Count(w => w.Value.ToLower().Contains("t")); //Returns 3
}
ConcurrentDictionary also provides an overloaded method of Count() which takes the Predicate to filter the items.

Check Key exists

To check particular key exits in dictionary, we can use ContainsKey method. It returns true if key exists otherwise returns false.
1
2
3
4
5
6
7
8
9
10
11
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
    dictionary.TryAdd("2", "Second");
    dictionary.TryAdd("3", "Third");
    dictionary.TryAdd("4", "Fourth");
 
    bool firstItemFound = dictionary.ContainsKey("1"); //Returns true
    bool fifthItemFound = dictionary.ContainsKey("5"); //Returns false
}

Copy ConcurrentDictionary items to another Collection classes

For copy stored key/values pairs to another collection class, It provides different "To..." methods.
  1. ToArray
  2. ToDictionary
  3. ToList
  4. ToLookup
We can use above methods to copy over dictionary values into another collection classes. Below is the example.
1
2
3
4
5
6
7
8
9
10
11
12
13
static void Main(string[] args)
{
    ConcurrentDictionary<string, string> dictionary = new ConcurrentDictionary<string, string>();
    dictionary.TryAdd("1", "First");
 
    KeyValuePair<string, string>[] keyValues = dictionary.ToArray();
 
    Dictionary<string, string> dict = dictionary.ToDictionary(w => w.Key, m => m.Value);
 
    List<KeyValuePair<string, string>> lst = dict.ToList();
 
    ILookup<string, string> lookup = dict.ToLookup(w => w.Key, m => m.Value);
}

Final Words

ConcurrentDictionary is thread-safe collection class to store key/value pairs. It internally uses locking to provide you a thread-safe class. It provides different methods as compared to Dictionary class. We can use TryAdd, TryUpdate, TryRemove, and TryGetValue to do CRUD operations on ConcurrentDictionary.
Do post your queries for the same.

RxJs BehaviorSubject vs Observable?

Here is few finding and analysis about the topics for above topics,

BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
  • It needs an initial value as it must always return a value on subscription even if it hasn't received a next()
  • Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an onnext
  • at any point, you can retrieve the last value of the subject in a non-observable code using the getValue() method.
Unique features of a subject compared to an observable are:
  • It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.
In addition, you can get an observable from behavior subject using the asObservable() method on BehaviorSubject.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.

Observe how using Observable.create created different output for each observer, but BehaviorSubject gave the same output for all observers. This is important.

Other differences summarized.
━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         Observable                  ┃     BehaviorSubject/Subject         ┃      
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ 
│ Is just a function, no state        │ Has state. Stores data in memory    │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Code run for each observer          │ Same code run                       │
│                                     │ only once for all observers         │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Creates only Observable             │Can create and also listen Observable│
│ ( data producer alone )             │ ( data producer and consumer )      │
├─────────────────────────────────────┼─────────────────────────────────────┤
│ Usage: Simple Observable with only  │ Usage:                              │
│ one Obeserver.                      │ * Store data and modify frequently  │
│                                     │ * Multiple observers listen to data │
│                                     │ * Proxy between Observable  and     │
│                                     │   Observer                          │
└─────────────────────────────────────┴───────────────
Feel free to ask your queries and comments.

Sunday, 9 December 2018

Selenium with C# mobile

Your guide to running Selenium Webdriver tests with C# on BrowserStack.


Introduction

BrowserStack gives you instant access to our Selenium Grid of 2000+ real devices and desktop browsers. Running your Selenium tests with C# on BrowserStack is simple. This guide will help you:
  1. Run a sample Selenium Webdriver test on BrowserStack
  2. Setup your environment to be able to test URLs in your internal network
  3. Understand and configure the core capabilities in your Selenium test suite
  4. Explore advanced features

Prerequisites

Before you can start running your Selenium tests with C#::
  1. Download the Selenium C# bindings from the Selenium website
  2. Extract the bindings and add them to relevant folder

Getting Started

Note: Running your Selenium tests on BrowserStack requires a username and an access key.
To get started, let’s run a simple Selenium Webdriver test. The C# script below will open a URL, input a string, submit the form, and return the page title.
First, select the OS and Device/Browser combination you'd like to test on the using drop-down menus below. This will automatically update the C# code sample below:
1. Select an OS
2. Select a device
Look for the  icon to select a real device.
Note: Testing on real devices requires the Automate Mobile plan
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace SeleniumTest {
  class Program {
    static void Main(string[] args) {
      IWebDriver driver;
      DesiredCapabilities capability = new DesiredCapabilities();
      capability.SetCapability("browserName", "iPhone");
      capability.SetCapability("device", "iPhone 8 Plus");
      capability.SetCapability("realMobile", "true");
      capability.SetCapability("os_version", "11.0");
      capability.SetCapability("browserstack.user", "USERNAME");
      capability.SetCapability("browserstack.key", "ACCESS_KEY");

      driver = new RemoteWebDriver(
        new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability
      );
      driver.Navigate().GoToUrl("http://www.google.com");
      Console.WriteLine(driver.Title);

      IWebElement query = driver.FindElement(By.Name("q"));
      query.SendKeys("Browserstack");
      query.Submit();
      Console.WriteLine(driver.Title);

      driver.Quit();
    }
  }
}

Sunday, 4 November 2018

What are MVP and MVC and what is the difference?

Let me provide  difference between MVP and MVC ,

Model-View-Presenter

If we are talking about In MVP, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.
MVP tends to be a very natural pattern for achieving separated presentation in Web Forms. The reason is that the View is always created first by the ASP.NET runtime. You can find out more about both variants.

Two primary variations

Passive View: The View is as dumb as possible and contains almost zero logic. The Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead the View exposes setter properties which the Presenter uses to set the data. All state is managed in the Presenter and not the View.
  • Pro: maximum testability surface; clean separation of the View and Model
  • Con: more work (for example all the setter properties) as you are doing all the data binding yourself.
Supervising Controller: The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.
  • Pro: by leveraging databinding the amount of code is reduced.
  • Con: there's less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.

Model-View-Controller

In the MVC, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:
    Action in the View
        -> Call to Controller
        -> Controller Logic
        -> Controller returns the View.
One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.

Presentation Model

One other pattern to look at is the Presentation Model pattern. In this pattern there is no Presenter. Instead the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model, and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behaviour for the view. This pattern is a very strong candidate for use in WPF applications and is also called Model-View-ViewModel.
You can now do this in most "modern" browsers!

you can do this to your success action :

window.history.pushState("object or string", "Title", "/new-url");
Additional Note:

  1. The first parameter is the data we'll need if the state of the web page changes, for instance whenever someone presses the back or forwards button in their browser. Note that in Firefox this data is limited to 640k characters.
  2. title is the second parameter which can be a string, but at the time of writing, every browser simply ignores it.
  3. This final parameter is the URL we want to appear in the address bar.

You can achieve via AJAX also,


$(".urut").change(function() {
  $.ajax({
    url: "<?php echo base_url(); ?>categories/brand/<?= $link_brand; ?>?l=<?= $l; ?>&h=<?= $h; ?>&city=<?= $city; ?>&city_name=<?= $city_name; ?>&ket=view",
    type: "POST",
    data: "urut=" + $(".urut").val(),
    success: function(data) {
      $("#result").html(data);
    }
  })
})
Do comment, and let me know if you face any issue.

Monday, 29 October 2018

Visual Studio Code for front-end developers | Visual Studio Code Can Do That?

Visual  studio code for newbie or a seasoned developer, code editor is an imperative part of your work. The problem, especially if you are a beginner, is that there are tons of choices for IDEs. And many of them share similar features, functionalities, and even UI. As a result, choosing the right IDE might actually take more time and effort that you thought.
If your question right now is: “which code editor should I start with?” then I would reply: “It depends, my friend.” Choosing a particular IDE significantly depends on a few factors: what type of developer you are, what kinds of environments you mostly work with, or whether you have an exclusive built-in feature that you absolutely need to get jobs done.
The main purpose of this blog is not to compare different IDEs, but to discuss my experience with VSCode. So in this post, I will:
  • show a brief introduction to VSCode
  • introduce the particular theme I’ve installed
  • discuss helpful extensions I use
  • show you how I leverage VSCode’s features to enhance my workflow.
Let’s get into it!
  • HTML Snippets: add rich language support for the HTML Markup such as auto-close tags.
  • JavaScript (ES6) code snippets: pretty self-explanatory
  • Live Server: launch a local server with live reload features for your HTML or PHP site
  • Markdown Preview Enhanced: run live server for your markdown file.
  • Material Icon Theme: provides icons based on Google’s Material Design. To activate, click Setting => File Icon Theme => Select Material Icon Theme
  • Prettier: beautifully format your JavaScript/ TypeScript/ CSS code.

Things I wish I’d known since the beginning

Apart from these themes and extensions, I would like to share with you how I use VSCode’s great features to boost productivity. These are all things that I didn’t know as a beginner, and that would’ve been very helpful for leveraging and facilitating my workflow.

Integrated Terminals

It is kind of inevitable that the more time you are in software development, the more important the Terminal becomes. As a JavaScript developer, I use the Terminal to install packages, run the development server, or even push changes in my current repository to GitHub.
VS code is light weight open source code editor. use it and enjoy it..

Sunday, 28 October 2018

Node npm ENOSELF error - installing a package in its package in branch RxJS package

I was facing issue while installing node packages,

Please review error  screenshot as well,





SOLUTION  : just rename package.json file with package1.json and start executing your package command.
To fix that, open your package.json file and change/rename the name of the project.

Error was faced during package installation  as below :
$ npm install rxjs webpack webpack-dev-server typescript ts-loader


try out with this:
$ npm install webpack webpack-dev-server typescript ts-loader

if you face same issue, just rename package.json file as per my comment and execute your package it will create automatically new package file.