Author Archives: Jebarson

About Jebarson

Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net, ASP.net, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at http://www.jebarson.info/ . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them http://bit.ly/houBNx . He is a contributor of this site and shared many tips and tricks.

Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property

Once stuck on a requirement where I needed to write a code which is flexible and generic enough to sort any type of collection and also the property based on which it has to be sorted will be dynamic. After trying many options I discovered myself how easy it is to hit this requirement using Lamda Expression.

Continue reading

ASP.NET Calendar Control as Outlook Calendar

This is a serious necessity in few applications where you want to show the appointments over a calendar. Though most of us are not aware, ASP.net calendar provides an easier way to deal with this. In this tip I am going to show how we can use a ASP.NET Calendar control as Outlook Calendar.
Continue reading

Releasing Single / Multiple Files To Pre Compiled ASP.net Web Site

We most the time run into the issue where we need to release a patch which requires a change in one or multiple code behind files and since your site is compiled, you are put into the state that you have to do a deployment instead of releasing those files. But, fortunately you can do that on a ASP.net website.

If your site is a ASP.net web application, then there is no shortcut since the application is compiled into a single class library and you have no option but to publish the site and this article will not help you. However, if you are using a web site, well here you go.

Continue reading

How To Scroll To Validation Summary ?

ASP.net by default calls the function window.scrollTo(0,0) after the validation failure from ASP.net validators but not always we have the validation summary control placed at the top. There are instances where we need to place validation summary at some other location but by doing this, instead the user being scrolled to see the validation error, he will always see the top of the page.
Continue reading

Null Coalescing Operator To Define Default Value For Nullable Types – Double Question Mark

We all know that defining a nullable type in C# is very simple as below

int? value;

And when you want to check whether the value is null, then there are definitely multiple way you could do.

// First option.
if(value == null)
{
    //Write the code here
}

// Second Option.
if(!value.HasValue)
{
   //Write the code here
}

However there is a easy way you could specify the default value i.e., the default value to be used in case the nullable type has a null value in it.
below code block will set the index to 10 if value is null.

	
int index = value ?? 10;

Below code block will check for both value1 and value2 for null and then assigns the value as null.

int index = value1 ?? value2 ?? 10;

Tip: Customizing / Adding Image To Radio Button List Control

This tips discuss how you can customize the way your RadioButtonList control will look. Below is a simple code which will enable to add me icons for the radio buttons in the list.

 protected void ErrorPriority_DataBound(object sender, EventArgs e)
        {
            try
            {
                foreach (ListItem item in this.ErrorPriority.Items)
                {
                    Priority priority = this.GetErrorPriority(item.Value);
                    item.Text = string.Format("<img src = \"{ 0}\" / > {1} - {2}, this.GetErrorPriorityIconUrl(priority), priority.Order, priority.Name);
                }
            }
            catch (Exception ex)
            {
                this.DisplayError(ex.Message);
            }
        }


So, as above we are trying to loop through the radio buttons to which the data is bound. RadioButtonList is nothing but a set of radio buttons which has the same group. But, the advantage point is that you will be able to enumerate it as ListItem.

In the above scenario we are adding a icon for every radio button through a html img tag and also append it with a text. So below is how our output will look like.

Similarly you can have any scripts / html content added to make your control look better.

Shared by : Jebarson Jebamony
Original Source : http://bit.ly/e1oF4m

How to Sort Generic List Using Lambda Expression For Dynamic Type And Dynamic Property ?

This tips explained how to write a code which is flexible and generic enough to sort any type of collection and also the property based on which it has to be sorted will be dynamic.This is very much easy to hit this requirement using Lamda Expression.

Below code will do this for you.

public class Utility
{
        /// <Summary>
        /// Gets the sorted list.
        /// </Summary>
        /// <param name="source" />The source.
        /// <param name="sortColumn" />The sort column.
        /// <param name="sortDirection" />The sort direction.
        /// <The sorted list. />
        private List GetSortedList(List source, string sortColumn, SortDirection sortDirection)
        {
            // Prepare the dynamic sort expression
            var paramExp = Expression.Parameter(typeof(T), typeof(T).ToString());
            Expression propConvExp =
                             Expression.Convert(Expression.Property(paramExp, sortColumn), typeof(object));
            var sortExp = Expression.Lambda>(propConvExp, paramExp);
 
            if (sortDirection == SortDirection.Ascending)
            {
                return source.AsQueryable().OrderBy(sortExp).ToList();
            }
            else
            {
                return source.AsQueryable().OrderByDescending(sortExp).ToList();
            }
        }
}

We will call this method as below

List<Employee> sortedEmployees
= new Utility<Employee>().GetSortedList(employeeList, "City", SortDirection.Ascending);

First we create the parameter expression for the generic type and on the further two statements we are promting the expression to convert the dynamic property based on which we need to sort to a understandable format of lambda. Then we go ahead and use the sort of generic list.

Shared By : Jebarson
Original Post : http://jebarson.info/post/2011/03/03/Sort-Generic-List-Using-Lambda-Expression-For-Dynamic-Type-And-Dynamic-Property.aspx

Multiple Sort For Collection Using LINQ

There are quite a lot of instance where you need to do a primary sort and you need a secondary sort on the same collection and sometimes even multiple sort. With LINQ we can achieve it pretty straight forward.

Let us assume the situation here. We have a list of employees and we need the output to be sorted by city and within every city, we need it to be sorted by the employee’s first name. Below is the code which will get your job done.

employeeList.OrderBy(item => item.FirstName).OrderBy(item => item.City);

Remember the inner sort / secondary sort has to appear first and the outer sort at the last.

Source : http://jebarson.info/post/2011/03/01/Multiple-Sort-For-Collection-Using-LINQ.aspx

Must Know Tips For Windows Phone 7

We all know that Windows Phone 7 is the new smart kid out in the market and since it is altogether a new platform by itself, there are few things which you might not know about Windows Phone. This article will focus on getting on few tips that would help you on your day to day activities with Windows Phone. I will keep updating this article as soon as I find something new and interesting.

  1. Rearrange / remove your tiles
    Tap on the tile and hold for few seconds and the tile will come to the edit mode. Clicking on the right top pin will unpin the tile from the screen. You can also drag and drop to any place of the screen and tap again on the tile to release to normal mode.
  2. Add application / contact to home tiles
    Tap and hold on the application / contact and a context menu will appear where you select an option “Pin to start”
  3. Link / Unlink people
    Windows phone considers every contact of you in email accounts, SIM, Facebook and other accounts to “People”. By default Windows phone links similar names and if something is not linked, then you can link them by selecting the contact and tap the “chain” icon which will show similar contacts, if it is not shown you can search for the contact and link. This can be used for the unlink the same way.
  4. Hide only Facebook contacts
    If you don’t want to see the contacts in Facebook who doesn’t have any other contact like email or phone then select Settings –> applications –> people, select “Only add Facebook info to existing contacts”.
  5. Adding email accounts
    Settings –> email & accounts –> Add any account.
  6. Changing the signature of mail
    By default, Windows phone adds a signature “Sent from windows phone” to all the messages you send. However, you can change them by opening your mail click on the ellipsis (…) at the right bottom and tap the “settings”.
  7. View other folders of mail
    If you are able to see only inbox, then it’s the way Windows phone syncs your email account. It doesn’t show any other folders like “Sent Items” and other custom folders in the mail by default. You can add them by opening the mail, tap”folder” icon and select “Show all folders” and select the folders you want to sync.
  8. Where are my older mails
    If you can see only latest mails, then Windows phone by default syncs only the past 3 days mails.To customize, open the mail and tap on ellipsis then select settings –> Sync settings and change the number of days you want to keep the mail.
  9. Select multiple mails
    Open the mail, tap the second button on the bottom which will show the check boxes to the left of every message allowing you to select multiple mails for delete.
    There is a much faster way by tapping on the left most extreme of your mail.
  10. Using cursors
    If you aren’t able to find any cursor keys in the key pad, then be informed that there aren’t any. For cursor, tap and hold on the text area and the cursor will appear just above your finger tip. Drag it and drop anywhere you want.
  11. Caps lock
    Double tap or tap and hold on the shift button which will switch on caps lock. Tap again to release.
  12. Search anywhere
    There is a dedicated search button on the right bottom of the front side of the phone which will show the search for a corresponding place you are. e.g.) If you are in “people”, it will search for people and if you are in “market place” it will search for apps.
  13. Lock your screen.
    Your screen can be locked by pressing the power button once. Press again to release.
  14. Disable camera when locked
    You can access camera even when your screen is locked by a full and long press on the camera button.However, this can be disabled by Settings –> Swipe to applications –> pictures + camera and switch off “Allow the camera button to wake up the phone”.
  15. Talk to your phone
    You can talk to your phone for all the actions. This is very useful when you are driving. Do a long press on windows key
    Say a word to search; “Pizza” will search for pizza
    Say “Open market place” or “Run market place” or “Go to market place” to open the market place application. Similarly for any application.
    Say “Call Jebarson” and it will call “Jebarson” if he is in your contact.
  16. Tabbed browsing
    Open the internet explorer and select the “pages” icon or the last icon at the bottom and now you can traverse across tabs, add or remove tabs.
  17. Browsing desktop version
    The internet explorer in windows phone by default searches and displays the mobile version of the site you are browsing. If you always want the desktop version to be browsed, settings –> applications –> internet explorer –> Desktop version
  18. Talk to your phone when locked
    If you don’t want to unlock your phone when you want to talk to your phone for getting an operation done, then select Settings –> speech and select “Use speech when phone is locked”.
  19. Change the background of pictures
    Open the pictures, tap and hold the background and select “change background”.

Author:Jebarson | Follow him

Search Multiple Strings Using Regular Expression

This is small piece of code snippet which I wanted to share as we face this necessity in our day to day programming. Suppose you have a need when you need to search multiple string, say you need to search strings like "int", "float", "string" in a piece of text. Below is how you will achieve it without using any loop and in a simple and straight forward way.
[surcecode language=”csharp”]
string pattern = “int|float|string”;
MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);
[/sourcecode]

Since the return value is a "MatchCollection", you can find the index of the matched string and many other properties / methods supported by “Match” type.

Author:Jebarson | Follow him

Workaround For Non Serializable Types

There are many a situations you would have come across when you want to XML serialize an object but since the type is a non – serializable you can’t do it, and you could have done a lot of code for getting the functionality done. There is a much simpler and easy way to get this achieved.

Let me get you a scenario as below

 

public class HighlightInfo
{
        public string Name { get; set; }
 
        public Color ForeColor { get; set; }
}

As you all know System.Drawing.Color is a structure and it is not xml serializable. So whenever you try to serialize “HighlightInfo”, you will get a null tag for "ForeColor". Below is how you achieve this functionality

public class HighlightInfo
{
        public string Name { get; set; }
 
        [XmlIgnore]
        public Color ForeColor { get; set; }
 
        [XmlElement("ForeColor")]
        public string HtmlForeColor
        {
            get
            {
                return ColorTranslator.ToHtml(this.ForeColor);
            }
            set
            {
                this.ForeColor = ColorTranslator.FromHtml(value);
            }
        }
}

Now this is a much easier way to achieve serialization without much trouble. However, this workaround might not work for few situations but it will obviously work for situations where you can transpose a data to another. E.g.) in our scenario we transposed color object to html color and vice versa.
Author:Jebarson | Follow him

Getting Added And Deleted Items In A List Using LINQ

Most the time when we work with a list object, finding a newly added items or deleted items becomes a very trivial part of the logic. Sometimes, we endup writing sophisticated logic or loops to get this done. Below code will demonstrate how this can be easily done using LINQ.

Lets assume that we have a list as below.

List actualList = new List();
actualList.Add(new MyClass() { Id = 1, FirstName = "First Name1", LastName = "Last Name1" });
actualList.Add(new MyClass() { Id = 2, FirstName = "First Name2", LastName = "Last Name2" });
actualList.Add(new MyClass() { Id = 3, FirstName = "First Name3", LastName = "Last Name3" });

Below is the list which will mimic as we have removed 2 items from the list and added 1 item.

List<MyClass> updatedList = new List<MyClass>();
updatedList.AddRange(actualList);
updatedList.RemoveAt(0);
updatedList.RemoveAt(1);
updatedList.Add(new MyClass() { Id = 4, FirstName = "First Name4", LastName = "Last Name4" });

Below LINQ query will give you deleted items from the orginal list.

IEnumerable<MyClass> deletedItems = (IEnumerable<MyClass>)from actualItem in actualList
                                           where !
                                           (from newItem in updatedList select newItem.Id)
                                           Contains(actualItem.Id)
                                           select actualItem;

Below LINQ query will give you added items to the orginal list.


IEnumerable<MyClass> addedItems = (IEnumerable<MyClass>)from actualItem in updatedList
                                           where !
                                           (from newItem in actualList select newItem.Id)
                                           Contains(actualItem.Id)
                                           select actualItem;

Hope this snippet helps you somewhere.

Author : image Jebarson Jebamony.   image  @jebarson007

Continue reading