Monday, January 28, 2013

CSS Selector

Shout it kick it on DotNetKicks.com
In this post is about CSS selector and how it woks. Following is explanation of most of the selector that is used in CSS.

In the following first is css example and than html code on which it will work, so to try by yourself create html page and put the css as well as related Html and see the result. In most of the select I provided demo link where you can visit and see the result.

In below post you might find some new CSS selector that are the part of new CSS3. All of the below examples and demo tried by me on latest Chrome version.

.Class -: Select all the element with given class name.
CSS
.MyIntro
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div class="MyIntro">
<p>My name is Pranay Rana.</p>
<p>I am working as Soft Engg.</p>
</div>

#id -: Select all the element with given id name.
CSS
 #MyIntro
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div id="MyIntro">
<p>My name is Pranay Rana.</p>
<p>I am working as Soft Engg.</p>
</div>
Point to Note : You can have more than one element having same classname in HTML page but you can have only one element with the ID.

HTMLElement - Select all the html element which name is given.
CSS
 p
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
<p>My name is Pranay Rana.</p>
<p>I am working as Soft Engg.</p>
</div>

HtmlElement HtmlElemnt - Select all the html element which are in html element.
CSS
div p
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
<Span>
 <p> data </p>
</Span>
</div>
<p>I am working as Soft Engg.</p>
in this example all p element inside div get highlighted with read color, but p element outside div doesnt get affected.

Demo 


HtmlElement > HtmlElemnt - Select all the html element which are child of html element.
CSS
div > p
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
<Span>
 <p> data </p>
</Span>
</div>
<p>I am working as Soft Engg.</p>
in this example all p element which are child of div get highlighted with read color, but p element which are not child of div doesnt get affected.

Demo 


HtmlElement + HtmlElemnt - Select all the html element which are immediate after html element.
CSS
div + p
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
</div>
<p>I am working as Soft Engg.</p>
<p> data </p>
in this example p element which is immediate after div get highlighted with read color, in this example "I am working as Soft Engg." this text get highlighted.

Demo


HtmlElement ~ HtmlElemnt - Select all the html element which are precedes html element.
CSS
div ~ p
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p>My name is Pranay Rana.</p>
    <span>
        <p> data </p>
  </span> 
</div>
<p>I am working as Soft Engg.</p>
<p>My Demo Page.</p>
in this example p element which is precedes div get highlighted  with read color, in this example "I am working as Soft Engg." and "My Demo Page." text get highlighted.

Demo


[attribute] - Select all the html element which is having attribute.
CSS
[data-name]
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p data-name="pranay">My name is Pranay Rana.</p>
    <span>
        <p> data </p>
  </span> 
</div>
<p>I am working as Soft Engg.</p>
<p data-name="demo">My Demo Page.</p>
in this example any element which is having attribute "data-name"div get highlighted with red color, in this example "My name is Pranay Rana." and "My Demo Page." text get highlighted.

Demo


[attribute = data] - Select all the html element which is having attribute value equal to data.
CSS
[data-name = 'demo']
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p data-name="pranay">My name is Pranay Rana.</p>
    <span>
        <p> data </p>
  </span> 
</div>
<p>I am working as Soft Engg.</p>
<p data-name="demo">My Demo Page.</p>
in this example any element which is having attribute "data-name" and value = "demo" get highlighted  with red color, in this example "My Demo Page." text get highlighted.

Demo


[attribute ^= data] - Select all the html element where attribute value begins with data.
CSS
[data-name ^= 'pra']
{
  font:15px arial,sans-serif;
  color:red;
}
So with the above html when apply this "My name is Pranay Rana."  text is get highlighted because its "data-name" attribute value begining with "pra".

Demo


[attribute $= data] - Select all the html element where attribute value end with data.
CSS
[data-name ^= 'pra']
{
  font:15px arial,sans-serif;
  color:red;
}
So with the above html when apply this "My name is Pranay Rana."  text is get highlighted because its "data-name" attribute value ending with "nay".

Demo


[attribute *= data] - Select all the html element where attribute value contains data.
CSS
[data-name *= 'rana']
{
  font:15px arial,sans-serif;
  color:red;
}
So with the above html when apply this "My name is Pranay Rana."  text is get highlighted because its "data-name" attribute value contains "rana".

Demo


[attribute ~= data] - Select all the html element where attribute value contains word data.
CSS
[data-name ~= 'page']
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div >
<p data-name="pranay_page">My name is Pranay Rana.</p>
    <span>
        <p> data </p>
  </span> 
</div>
<p>I am working as Soft Engg.</p>
<p data-name="demo page">My Demo Page.</p>
in this example any element where attribute "data-name"  value contains word = "page" get highlighted  with red color, in this example "My Demo Page." text get highlighted

Demo


:first-child - Select first element (first child) of parent.
CSS
li:forst-child
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
</ul>
in this example "item1" element get highlighted  with red color.

Demo


:last-child - Select last element (last child) of parent.
CSS
li:last-child
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
</ul>
in this example "item4" element get highlighted  with red color.

Demo


:nth-child(n) - Select all each element which n the child of parent.
CSS
li:nth-child(2)
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
</ul>
in this example "second li" element get highlighted  with red color, in this example "item2" text get highlighted

Demo


:nth-child(n) - Select all each element which last n the child of parent counting from bottom .
CSS
li:nth-child(2)
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<ul>
    <li>item1</li>
    <li>item2</li>
    <li>item3</li>
    <li>item4</li>
</ul>
in this example "second last li" element get highlighted  with red color, in this example "item3" text get highlighted

Demo


:only-child - Select child element which only child of parent .
CSS
p:only-child
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
</div> 
<div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>
in this example "paraghaph 1" element get highlighted  with red color,which is only child of div element.

Demo


:first-of-type - Select first element of given type which is first comes under parent element.
CSS
p:first-of-type
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
</div>
in this example "paragraph 1" element get highlighted  with red color.

Demo


:last-of-type - Select last element of given type which is last comes under parent element.
CSS
p:last-of-type
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
</div>
in this example "paragraph 1" element get highlighted  with red color, that means here "pragraph 1" is first element of type p under div.

Demo


:nth-of-type(n) - Select nth element of given type which comes at nth place under parent element.
CSS
p:nth-of-type(2)
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>  
in this example "paragraph 2" element get highlighted  with red color, that means here "pragraph 2" is 2th element of type p under div.

Demo


:nth-last-of-type(n) - Select nth last element of given type which comes at nth place under parent element from last.
CSS
p:nth-last-of-type(2)
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>  
in this example "paragraph 3" element get highlighted  with red color, that means here "pragraph 3" is last element of type p under div from last.

Demo


:only-of-type - Select only element of given type which comes under parent element.
CSS
p:only-of-type
{
  font:15px arial,sans-serif;
  color:red;
}
Use
<div>
    <p> pragraph 1</p>
</div> 
<div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>  
in this example "paragraph 1" element get highlighted  with red color, because p is only element of given type.

Demo


:empty - Select element which is empty i.e. donent have any child.
CSS
div:empty
{
  width:100px;
height:20px;
background:red;
}
Use
<div></div> 
<div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>  
in this highlight all text in the document with red color.

Demo


::selection - highlight the text with the color selected.
CSS
::selection
{
  background:green;
}
Use
<div> <p> pragraph 1</p> </div> 
   <div>
    <p> pragraph 2</p>
    <p> pragraph 3</p>
    <p> pragraph 4</p>
</div>    
in this highlight all text with green which get select in document.

Demo


:not(HTMLElement) - it not apply the style to the HTMLElement specified.
CSS
:not(span)
{
  font:15px arial,sans-serif;
  color:red;
}
span
{
  color:black;
}
Use
 <p> pragraph 1</p>
 <p> pragraph 2</p>
 <p> pragraph 3</p>
 <p> pragraph 4</p>
 <span> span data</span>    
in this highlight all text which is in p element i.e. not apply style to span element.

Demo


:enable - select to all enable element.
:disable - select to all disable element.
CSS
:input[type="text"]:enabled
{
background:green;
}
input[type="text"]:disabled
{
background:red;
}
Use
Name: <input type="text" value="Pranay Rana" /><br>
Country: <input type="text" disabled="disabled" value="India" />    
here name is get highlighted with red color and country box is get highlighted with green.

Demo


Conclusion
Most of the selector are new here those are part of CSS3, I hope that helpful to understand well. I covered most of the CSS selector here but if there is something missing please place comment below regarding it.

Leave comment if you have any query or if you like it.  Pelease report if any link is not working or broken.

Friday, January 25, 2013

DistinctBy in Linq (Find Distinct object by Property)

Shout it kick it on DotNetKicks.com
In this post I am going to discuss about how to get distinct object using property of it from collection. Here I am going to show three different way to achieve it easily.
In this post I am going to discuss about extension method that can do task more than the current Distinct method available in .Net framework.

Distinct method of Linq works as following right now.
public class Product
{
    public string Name { get; set; }
    public int Code { get; set; }
}
Consider that we have product Class which is having Code and Name as property in it.
Now Requirement is I have to find out the all product with distinct Code values.
Product[] products = { new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "orange", Code = 4 }, 
                       new Product { Name = "apple", Code = 10 }, 
                       new Product { Name = "lemon", Code = 9 } };
var lstDistProduct = products.Distinct();
foreach (Product p in list1)
{
     Console.WriteLine(p.Code + " : " + p.Name);
}
Output

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

Way 1 : Make use of MoreLinq Library
First way to achieve the requirement is make use of MoreLinq Library, which support function called DistinctBy in which you can specify the property on which you want to find Distinct objects.
Below code is shows the use of the function.
var list1 = products.DistinctBy(x=> x.Code);

foreach (Product p in list1)
{
     Console.WriteLine(p.Code + " : " + p.Name);
}
Output

As  you can see in output there is only two object get return which actually I want. i.e. distinct value by Code or product.
If you want to pass more than on property than you can just do like this  var list1 = products.DistinctBy(a => new { a.Name, a.Code });
You can read about the MoreLinq and Download this DLL from here : http://code.google.com/p/morelinq/ one more thing about this library also contains number of other function that you can check.

Way 2: Implement Comparable
Second 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 ProductComparare which you can see in below code.
   
    class ProductComparare : IEqualityComparer
    {
        private Func<Product, object> _funcDistinct;
        public ProductComparare(Func<Product, object> funcDistinct)
        {
            this._funcDistinct = funcDistinct;
        }

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

        public int GetHashCode(Product obj)
        {
            return this._funcDistinct(obj).GetHashCode();
        }
    }
So In ProductComparare 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.
var list2 = products.Distinct(new ProductComparare( a => a.Code ));

            foreach (Product p in list2)
            {
                Console.WriteLine(p.Code + " : " + p.Name);
            }
Output

So this approach also satisfy my requirement easily. I not looked in code of MoreLinq library but I think its also doing like this only. If you want to pass more than on property than you can just do like this  var list1 = products.Distinct(a => new { a.Name, a.Code });.

Way 3: Easy GroupBy wa
The third and most eaisest way to avoide this I did in above like using MoreLine and Comparare implementation is just make use of GroupBy like as below
 List<Product> list = products
                   .GroupBy(a => a.Code )
                   .Select(g => g.First())
                   .ToList();

            foreach (Product p in list)
            {
                Console.WriteLine(p.Code + " : " + p.Name);
            }
In above code I am doing grouping object on basis of property and than in Select function just selecting fist one of the each group will doing work for me.
Output

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.Name, a.Code }).

So this one is very easy trick to achieve the functionality that I want without using any thing extra in my code.

Conclusion
So Above is the way you can achieve Distinct of collection easily by property of object.

Leave comment if you have any query or if you like it.

Wednesday, January 23, 2013

GeoLocation API in HTML5

Shout it kick it on DotNetKicks.com
HTML5 have cool feature that is provide gelocation of the user on the fly without using any extra services that we do right now. This feature is supported by Gelocation API which is part of HTML5.

Following is sample Code in JavaScript how it works.
<button onclick="getGeoLocation()">Get GeoLocation</button>
<script>
  function getGeoLocation()
  {
    if (navigator.geolocation)
    {
      navigator.geolocation.getCurrentPosition(showPosition,HandleError);
    }
    else
    {
      alert("Geolocation is not supported by this browser.");
    }
  }
  function showPosition(position)
  {
      alert("Latitude: " + position.coords.latitude + 
               "    Longitude: " + position.coords.longitude); 
  }
</script>
Code is work in this pattern.
  1. First when user click on button it calls getGeoLocation
  2. In that function its first check navigator.geolocation supported or not.
  3. It calls Inbuilt JavaScript method getCurrentPosition which returns Postion object
  4. This Position object used by showPostion to display Latitude and Logitude 

Below is handleError function that used to handle any error which might occur while accessing GeoLocation of the user.
  function HandleError(error)
  {
    switch(error.code) 
    {
     case error.PERMISSION_DENIED:
      alert("User denied the request for Geolocation.");
      break;
     case error.POSITION_UNAVAILABLE:
      alert("Location information is unavailable.");
      break;
     case error.TIMEOUT:
      alert("The request to get user location timed out.");
      break;
     case error.UNKNOWN_ERROR:
      alert("An unknown error occurred.");
      break;
    }
  }
Code of the function is self-explained by the values given.

Update GeoLocation as you Move with watchPosition
There is one of function which is part of Gelocation API that is very useful to get continues update of location as user moves from one place to another palce.
watchPosition - function that is used to achieve the above function.
To see how this works actually just replace getCurrentPosition function with watchPosition.
To stop updates from watchPosition you can use clearWatch() of API.

Position Object
Both method returns Postion object as output. Following is list of property that is part of Position Object.

coords.latitudeThe latitude as a decimal number
coords.longitudeThe longitude as a decimal number
coords.accuracyThe accuracy of position
coords.altitudeThe altitude in meters above the mean sea level
coords.altitudeAccuracyThe altitude accuracy of position
coords.headingThe heading as degrees clockwise from North
coords.speedThe speed in meters per second
timestampThe date/time of the response
Leave comment if you have any query or if you like it.

Tuesday, January 22, 2013

Index of Collection Using Linq

Shout it kick it on DotNetKicks.com
This is small post regarding How to get the index of each element in collection. There are sometime requirement to bind list of element with the dropdwon or list control with index as value and Data as Text value in this case you need to get index for each element.

Following is piece of code that make use of Linq and get the indexes for each element in collection.

//example of getting index of List Element
List<string> ListItems = 
       new List<string> { "Test1", "Test2", "Test3", "Test4" };
var ListWithIndex= someItems.Select((item, index) => new
{
      ItemName = item,
      Position = index
});

//example of getting index of Array Element
string[] ArryItem= { "Item1", "Item2", "Item3", "Item4" };
var ArraywithInex= someItems.Select((item, index) => new
{
      ItemName = item,
      Position = index
});
As you see in code there is one lambda function passed in the Select function of linq, and another point to note down is each elemtn has index associated with it. So by applying function like above in linq its easy to get the index of element.

Friday, January 4, 2013

Display and Format Negative Currency value

Shout it kick it on DotNetKicks.com
This small tip about how to show the negative currency value in your application. For Example if you have currency value like -1234 and you want to display it like -$1,234 according to you culture.

Problem
In C# to one of the way to format currency value easily is use ToString("c") with value will do work for you. For example check below code
//format -1234 as currency..
Console.WriteLine((-1234).ToString("c"));

Output
This will display value in output like this ($1,234.00). But the actual problem with the formatting is its not displaying - sign with currency value.

Solution
So to come out of this You need to create a custom NumberFormatInfo from your current locale. Then you can specify it's CurrencyNegativePattern, for example:
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
CultureInfo newCulture = new CultureInfo(currentCulture.Name);
newCulture.NumberFormat.CurrencyNegativePattern = 1;
Thread.CurrentThread.CurrentCulture = newCulture;
Console.WriteLine((-1234).ToString("c"));

Output
Now output of the above code is -$1,234.00. That's what actually needed display negative sign for negative currency value.
So in above code actual trick done by NumberFormatInfo.CurrencyNegativePattern Property, which is set to 1 which associated with pattern -$n. There number of different pattern supported which you can check on MSDN and assign value to property according to your need. This will not affect positive value of currency i.e. if you pas 1234 as value its dispaly as $1,234 only. And for this this example my current culture is "en-US" .

Conclusion
I Hope you all like this simple and easy example of formatting negative currency. you can explore more on MSDN on reference provided at end of post.
NumberFormatInfo Classhttp://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx
NumberFormatInfo.CurrencyNegativePattern Property - http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern.aspx

Leave comment if you have any query or if you like it.