Removing Background color of RadTabControl – Silverlight

To remove the background color we need to set the background visibility property to collapsed

BackgroundVisibility=”Collapsed”

If we need to change the color we need to edit the template

Getting first and Last day of specific month using c#

  1. First Day of month can be fetched from DateTime like below

public static DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
{
return new DateTime(dateTime.Year, dateTime.Month, 1);
}

public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

2.Last Day of month can be calculated like below

public DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
{
DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
}

ThreadPool in c#

.net internally manages the Threads in ThreadPool. ThreadPool limits the maximum no of threads to be created if any further creation happens it will maintain in queue and will be processed when one current thread completes it process the queued thread will come in to action
Sample Code: 

static void Main(string[] args)
{

//Maximum no of threads 6 IO threads ; 5
ThreadPool.SetMaxThreads(6,5);

for (int i = 0; i < 10000; i++)
{
Thread t = new Thread(PrintLine);
t.Name = “Thread_” + i;
ThreadPool.QueueUserWorkItem(new WaitCallback(PrintLine),i);
}

Console.WriteLine(“All threads finished their processes”);
Console.ReadLine();
}

static void PrintLine(object obj)
{
for (int i = 0; i <= 1000; i++)
{
int threadCount= ((IEnumerable)System.Diagnostics.Process.GetCurrentProcess().Threads)
.OfType<System.Diagnostics.ProcessThread>()
.Where(t => t.ThreadState == System.Diagnostics.ThreadState.Running)
.Count();
Console.WriteLine(“Total no of Threads :{0}”, threadCount);
if (threadCount > 5)
{
Console.BackgroundColor = ConsoleColor.DarkRed;
}
}

}

Threading is very much important for applications which needs to execute with in short timespan as well as which focus on user experience

AutoReset and Manual Reset Events

Using Reset Events we can control when particular instructions in a thread will execute relative to instructions in another thread There are two types of Reset Events

  1. Auto reset
  2. Manual reset
In spite of the term events, reset events have nothing to do with C# delegates and events. Instead, reset events are a way to force code to wait for the execution of another thread until the other thread signals. It is mainly used in multithreaded applications because there are scenarios in multithreaded apps  to wait for a particular state before verifying the results.
Key Methods:
  1. Set() – Signals the thread which is waiting for the signal
  2. WaitHandle() – will cause a thread to block until a different thread calls Set() or until the wait period times out
Difference ;
1. Calling Set() in AutoReset signals only one thread waiting for a signal and the selection of the thread is done by OS , How ever the same will signal all the threads in case of ManualReset
Taken from MSDN
There is no guarantee that every call to the Set method will release a thread. If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released. It is as if the second call did not happen. Also, if Set is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect.
Sample code:

class Program
{
private static AutoResetEvent autoReset = new AutoResetEvent(false);
private static ManualResetEvent manualReset = new ManualResetEvent(false);

static void Main(string[] args)
{
for (int i = 1; i < 100; i++)
{
Thread t = new Thread(ThreadImplementation);
t.Name = “Thread_” + i;
t.Start();
}
Thread.Sleep(100);

for (int i = 0; i < 2; i++)
{
Console.WriteLine(“Press Enter to release another thread.”);
Console.ReadLine();
manualReset.Set();
//autoReset.Set();
Thread.Sleep(100);
}
}

static void ThreadImplementation()
{
Console.WriteLine(“{0} waits on AutoResetEvent #1.”, Thread.CurrentThread.Name);
manualReset.WaitOne();
// autoReset.WaitOne();
Console.WriteLine(“{0} is released from AutoResetEvent #1.”, Thread.CurrentThread.Name);

}
}

Difference between HashTable and Dictionary C#

Hash table

  1. It returns null if we try to find a key which does not exist.
  2. It is slower than dictionary because it requires boxing and unboxing
  3. All the members in a Hashtable are thread safe,

Dictionary

  1. It returns error if we try to find a key which does not exist.
  2. It is faster than a Hashtable because there is no boxing and unboxing.
  3. Only public static members are thread safe.
  4. Dictionary is a generic type which means we can use it with any data type.

Sample Code

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

namespace HashvsDictionary
{
class Program
{
static Hashtable hashtable { get; set; }

static Dictionary<string, string> dictionary { get; set; }

static void Main(string[] args)
{
Program.hashtable = new Hashtable();
//You can add object type key values to HashTable so while retrieving need to unbox the original datatype
hashtable.Add(“1012”, “Thiru”);
hashtable.Add(“1013”, “Raj”);

Program.dictionary = new Dictionary<string, string>();
dictionary.Add(“1012”, “Thiru”);
dictionary.Add(“1013”, “Raj”);

Console.WriteLine(string.Format(” Key present :{0} Key Not present:{1}”, hashtable[“1013”], hashtable[“1016”]));

//It will throw error since key is not present
Console.WriteLine(string.Format(” Key present :{0} Key Not present:{1}”, dictionary[“1013”], dictionary[“1016”])); ;
Console.ReadLine();

}
}
}

Wrap RadTabItem in RadTabControl

Usually the overflowmode property of RadTabControl will be “Scroll” Changing it to “Wrap” will done the trick..

<telerik:RadTabControl TabStripPlacement=”Top” Grid.Row=”2″ OverflowMode=”Wrap”>

Convert a List to an Observable collection c#

You can simply convert your List to observable collection using the below syntax

new ObservableCollection<Object>(yourList)

Add Not null Column to Sqlserver with Default Value

ALTER Table Table1
ADD
UpdatedBy NVarchar(100) NOT NULL DEFAULT ”,
ReservedBy NVarchar(100)NOT NULL DEFAULT ”;

Silverlight – Iterate and get all xml node values & Name using xdocument

  string str = “<Data><Name>Thiru</Name><Phone>61084846</Phone><Card>Credit</Card><Memeber>VIP</Memeber></Data>”;

  public void GenerateData(string str)
        {
            doc = XDocument.Parse(str);
            foreach (XElement child in doc.Root.Descendants())
            {
           MessageBox.Show(string.Format(“Key:{0} Value:{1}”, child.Name,child.Value));
            }
        }

Call Asp.net serverside method on brower close using javascript

  1. Declare a WebMethod in asp.net page
  2. Have global variable in javascript check the value for raising the event if it is invoked by button click or browser close

[System.Web.Services.WebMethod()]

public static string AbandonSession() {

HttpContext.Current.Session.Abandon();

return “cool”;

}

<script src=”scripts/jquery-1.2.6.min.js” type=”text/javascript”></script>

<script type=”text/javascript” language=”javascript”>

var trigger = false;

$(document).ready(function() {

$(‘#ctl00_ContentPlaceHolder_btnSubmit’).click(function() {

trigger = true

});

});

window.onbeforeunload = function(evt) {

if (trigger== false) {

$.ajax({

type: “POST”,

url: “Converse.aspx/AbandonSession”,

data: “{}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(msg) {

alert(msg.d);

},

error: function(msg) {

var res = alert(“Error! Try again…”);

}

});

} else {

warn_on_unload = false;

}

//            return false;

}

</script>