<a href = "www.google.com" style='<%# Eval("IsOnline").ToString() == "True" ? "display:block" : "display:none" %>' >link</a>
Dec 8, 2011
How to set html link visible false depending on Eval function in grid view
<a href = "www.google.com" style='<%# Eval("IsOnline").ToString() == "True" ? "display:block" : "display:none" %>' >link</a>
Dec 7, 2011
How to convert DateTime to Date in Linq to Entity + C#
grid.DataSource = (from user in context.Users where ISActive = True select new
{
user.UserId,
user.UserName,
FirstName = (user.FirstName + " " + user.LastName),
CreatedDate = System.Data.Objects.EntityFunctions.TruncateTime(user.CreatedDate)
}).ToList();)
May 20, 2011
How to use double coute in string + C#
For eg:
To show the below text
"This is a "Test"
Code:
TextBox1.text = @"""This is a " + @"""Test""";
The logic is that if you use @ in front of the sting variable then using e double coute(""")
throughout the string will give you one double coute(").
Oct 4, 2010
How to find First non repeated character in a string + c#
This was asked in one of my interview.
now lets see how to solve this
Method call : GetFirstNonRepeatedChar("abcdab");
private char GetFirstNonRepeatedChar(string value)
{
// declare a character array.
char[] cArr = null;
try
{
// load the string to char array.
cArr = value.ToCharArray();
for (int i = 0; i < cArr.Length; i++)
{
// count to track all comparison has over
int count = 0;
for (int j = 0; j < cArr.Length; j++)
{
// avoids to comparison for same character
if (i != j)
{
// if repeated then come out of the inner loop
if (cArr[i] == cArr[j])
{
break;
}
else
{
// increament the count for each non repeatable comparison
count = count + 1;
// if the count reaches the char array length - 1
// and you are inside the for loop then the current value
// is the first non repeated character.
if (count == cArr.Length -1)
{
return cArr[i];
}
}
}
}
}
return '0'; // if no non repeated char is fount
}
catch (Exception)
{
throw;
}
}
Answer : c
Jul 6, 2010
How to split a sentence into word using C# + Regular Expressions
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string[] w = SplitWords("This is a Sample, Test");
foreach (string s in w)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
/// <summary>
/// Get all the words in the input string and separate them.
/// </summary>
static string[] SplitWords(string s)
{
//
// Split on all non-word characters.
// ... Returns an array of all the words.
//
return Regex.Split(s, @"\W+");
// @ special verbatim string syntax
// \W+ one or more non-word characters together
}
}Output:
This
is
a
Sample
Test
Jul 3, 2010
How to find the System Name in C#
using System.Security.Principal; to find the System name.
Below is the code:
lblSysNo.Text = WindowsIdentity.GetCurrent().Name.ToString();
Jul 1, 2010
How to pass double couted paramaters to Command line utilities programatically + c#
string driver = @"-f KML C:\FWTools2.4.7\bin\zeeee.kml
C:\FWTools2.4.7\bin\Morocco.tab"
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.Arguments = driver;
proc.Start();
proc.WaitForExit(); // use if you want your program to wait for the process to complete.
proc.Close();
single argument to a command line utility.
May 17, 2010
How to Add a Water mark text to an image using C#.
public Bitmap WaterMarkToImage(string ImagePath, string watermark)
{
Bitmap bmp;
bmp = new Bitmap(ImagePath);
Graphics graphicsObject;
int x, y;
try
{
//create graphics object from bitmap
graphicsObject = Graphics.FromImage(bmp);
}
catch (Exception e)
{
Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
graphicsObject = Graphics.FromImage(bmpNew);
graphicsObject.DrawImage(bmp, new Rectangle(0, 0,
bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width,
bmp.Height, GraphicsUnit.Pixel);
bmp = bmpNew;
}
int startsize = (bmp.Width / watermark.Length);
//get the font size with respect to length of the string
//x and y cordinates to draw a string
x = 0;
y = bmp.Height / 2;
System.Drawing.StringFormat drawFormat =
new System.Drawing.StringFormat(StringFormatFlags.NoWrap);
//drawing string on Image
graphicsObject.DrawString(watermark, new Font("Verdana",
startsize, FontStyle.Bold),
new SolidBrush(Color.FromArgb(100, 255, 255, 255)), x, y, drawFormat);
//return a water marked image
return (bmp);
}
Method Call:
System.Drawing.Bitmap bmp =
WaterMarkToImage(@"D:\images\IMG_2933.jpg", "Intraspatial Softech");
bmp.Save(@"D:\images\c1.jpg");
Sep 4, 2009
How to convert decimal value to Degree Mins Secs and viceversa in C#
private string convertToDegrees(decimal decValue)
{
//Method to convert to Decimal values to Degrees.
int Degree = 0, Mins = 0, Secs = 0;
decimal dec_Mins = 0.0M, dec_Secs = 0.0M;
string output = null;
Degree = (int)decValue;
dec_Mins = Math.Abs(decValue - Degree) * 60;
Mins = (int)dec_Mins;
dec_Secs = Math.Abs(dec_Mins - Mins) * 60;
dec_Secs = Math.Round(dec_Secs);
Secs = (int)dec_Secs;
output = Degree + "°" + Mins + "." + Secs;
return output;
}
The above method takes decimal as input and output degree.
The below method does the vice versa
DEGREE TO DECIMAL CONVERTION ON SERVER SIDE :
public string ConvertDegToDec(string value)
{
double vDeg, vMin, vSec, vConv1;
string result = string.Empty;
// attempt to convert if valid data
string[] lines = Regex.Split(value, "ø");
string[] lines1 = Regex.Split(lines[1], "'");
string[] lines2 = Regex.Split(lines1[1], "\"");
vDeg = Double.Parse(lines[0]);
vMin = Double.Parse(lines1[0]);
vSec = Double.Parse(lines2[0]);
vConv1 = vDeg + (vMin / 60) + (vSec / 3600);
result = vConv1.ToString();
return result;
}
Aug 13, 2009
How to generate a random unique 5 digit number + C#
Below is the method used to generate random 5 digit number.
public int getRandomID ()
{
return r.Next(10000,99999);
}
The number 10000, 99999 specifies the range.
Aug 12, 2009
How to find and remove Special Characters from a given string. + C#
public string RemoveSpecialChars(string str)
{
string[] chars = new string[] { ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "'", "\"", ";", "-", "_", "(", ")", ":", "", "[", "]" };
for (int i = 0; i < chars.Length; i++)
{
if (str.Contains(chars[i]))
{
str = str.Replace(chars[i], "");
}
}
return str;
}
Thanks
Mukunda
Dec 23, 2008
Threads Implementation in C# + source code
Introduction to Threads In C# :
Threads: Threads are often called lightweight processes. However they are not process.es
A Thread is a small set of executable instructions, which can be used to isolate a task from a process.
Multiple threads are efficient way to obtain parallelism of hardware and give interactive user interaction to your applications.
C# Thread:.
. Net Framework has thread-associated classes in System.Threading namespace. The following steps demonstrate how to create a thread in C#.
Step 1. Create a System.Threading.Thread object.
Creating an object to System.Threading.Thread creates a managed thread in .Net environment. The Thread class has only one constructor, which takes a ThreadStart delegate as parameter. The ThreadStart delegate is wrap around the callback method, which will be called when we start the thread.
Step 2: Create the call back function
This method will be a starting point for our new thread. It may be an instance function of a class or a static function. Incase of instance function, we should create an object of the class, before we create the ThreadStart delegate. For static functions we can directly use the function name to instantiate the delegate. The callback function should have void as both return type and parameter. Because the ThreadStart delegate function is declared like this. (For more information on delegate see MSDN for “Delegates”).
Step 3: Starting the Thread.
We can start the newly created thread using the Thread’s Start method. This is an asynchronous method, which requests the operating system to start the current thread.
For Example:
// This is the Call back function for thread.
Public static void MyCallbackFunction()
{
while (true)
{
System.Console.WriteLine(“ Hey!, My Thread Function Running”); ………
}
}
public static void Main(String []args)
{
// Create an object for Thread
Thread MyThread = new Thread(new ThreadStart (MyCallbackFunction));
MyThread.Start() ……
}
Killing a Thread:
We can kill a thread by calling the Abort method of the thread. Calling the Abort method causes the current thread to exit by throwing the ThreadAbortException.
MyThread.Abort();
Suspend and Resuming Thread:
We can suspend the execution of a thread and once again start its execution from another thread using the Thread object’s Suspend and Resume methods.
MyThread.Suspend();
// causes suspend the Thread Execution.
MyThread.Resume() ;
// causes the suspended Thread to resume its execution.
Thread State:
A Thread can be in one the following state.
Unstarted - Thread is Created within the common language run time but not Started still.
Running - After a Thread calls Start method
WaitSleepJoin - After a Thread calls its wait or Sleep or Join method.
Suspended - Thread Responds to a Suspend method call.
Stopped - The Thread is Stopped, either normally or Aborted.
We can check the current state of a thread using the Thread’s ThreadState property.
Thread Priorty:
The Thread class’s ThreadPriority property is used to set the priority of the Thread.
A Thread may have one of the following values as its Priority:
Lowest
BelowNormal
Normal
AboveNormal
Highest.
The default property of a thread is Normal.
REF: Code project
How to select an item in a DropDownList by Value
1. //How to select an item in a DropDownList by Value
ListItem li = yourDropDownlist.Items.FindByValue(”yourValue”);
if (li != null)
yourDropDownlist.SelectedIndex = yourDropDownlist.Items.IndexOf(li);
2. //How to check if value exists in DropDownList
public static bool IsValueInDropdownList(DropDownList controlName,string strValue)
{
if (controlName.Items.FindByValue(strValue) != null)
return true;
else
return false;
}
How to Remove item from DropDownList by Value
ListItem li = dropdownlist.Items.FindByValue(strValue);
if(li != null)
dropdownlist.Items.Remove(li);
// 2nd method, combined form
dropdownlist.Items.RemoveAt(
dropdownlist.Items.IndexOf(dropdownlist.Items.FindByValue(strValue))
);
Aug 20, 2008
C# Generics with examples
Parametric Polymorphism is a well-established programming language feature. Generics offers this feature to C#.
The best way to understand generics is to study some C# code that would benefit from generics. The code stated below is about a simple Stack class with two methods:
Push () and Pop ().
First, without using generics example you can get a clear idea about two issues:
a) Boxing and unboxing overhead and
b) No strong type information at compile type.
After that the same Stack class with the use of generics explains how these two issues are solved.
Example Code
Code without using generics:
public class Stack
{
object[] store;
int size;
public void Push(object x)
{...}
public object Pop()
{...}
}
Boxing and unboxing overhead:
You can push a value of any type onto a stack. To retrieve, the result of the Pop method must be explicitly cast back. For example if an integer passed to the Push method, it is automatically boxed. While retrieving, it must be unboxed with an explicit type cast.
Stack stack = new Stack();
stack.Push(3);
int i = (int)stack.Pop(); //unboxing with explicit int casting
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.
No strong Type information at Compile Time
Another issue with the Stack class:
It is not possible to enforce the kind of data placed on a stack.
For example, a string can be pushed on a stack and then accidentally cast to the wrong type like integer after it is retrieved:
Stack stack = new Stack();
stack.Push("SomeName");
//pushing the string
int i = (int)stack.Pop();
//run-time exception will be thrown at this point
The above code is technically correct and you will not get any compile time error. The problem does not become visible until the code is executed; at that point an InvalidCastException is thrown.
Code with generics
In C# with generics, you declare class Stack
Within class Stack
Stack
Stack
Simply your type arguments get substituted for the type parameter. All of the Ts become ints or Customers, you don't have to downcast, and there is strong type checking everywhere.
public class Stack
{
// items are of type T, which is kown when you create the object
T[] items;
int count;
public void Push(T item) {...}
//type of method pop will be decided when you creat the object
public T Pop() {...}
}
In the following example, int is given as the type argument for T:
Stack OpenTag Int CloseTag
stack.Push(3);
int i = stack.Pop();
The Stack
You can use parameterization not only for classes but also for interfaces, structs, methods and delegates.
//For Interfaces interface IComparable OpenTag T CloseTag
//for structs struct HashBucket OpenTag T CloseTag
//for methods static void Reverse OpenTag T CloseTag
//for delegates delegate void Action OpenTag T CloseTag
Inside the CLR
When you compile StackOpenTag T CloseTag
Implementation of parametric polymorphism can be done in two ways
1. Code Specialization: Specializing the code for each instantiation
2. Code sharing: Generating common code for all instantiations.
The C# implementation of generics uses both code specialization and code sharing as explained below.
At runtime, when your application makes its first reference to StackOpenTag T CloseTag
The .NET Common Language Runtime creates a specialized copy of the native code for each generic type instantiation with a value type, but shares a single copy of the native code for all reference types (since, at the native code level, references are just pointers with the same representation).
In other words, for instantiations those are value types: such as Stack OpenTag int CloseTag
So StackOpenTag int CloseTag
This code sharing avoids code bloat and gives better performance.
To support generics, Microsoft did some changes to CLR, metadata, type-loader,language compilers, IL instructions and so on for the next release of Visual Studio.NET(code named Whidbey).
What you can get with Generics
Generics can make the C# code more efficient, type-safe and maintainable.
Efficiency: Following points states that how performance is boosted.
Instantiations of parameterized classes are loaded dynamically and the code for their methods is generated on demand [Just in Time].
Where ever possible, compiled code and data representations are shared between different instantiations.
Due to type specialization, the implementation never needs to box values of primitive types.
Safety: Strong type checking at compile time, hence more bugs caught at compile time itself.
Maintainability: Maintainability is achieved with fewer explicit conversions between data types and code with generics improves clarity and expressively.
Conclusion
Generics gives better performance, type safety and clarity to the C# programs. Generics will increase program reliability by adding strong type checking. Learning how to use generics is straightforward, hopefully this article has inspired you to look deeper into how you can use them.
Jul 25, 2008
Handy Keyboard Shortcuts for c# 2005
Handy Keyboard Shortcuts for c# 2005
The following keyboard shortcuts I find invaluable. It's amazing how many people still use the mouse to do everything.
Document navigation :
Ctrl+Tab Switch documents
Ctrl+Shift+Tab Reverse switch documents
Ctrl+kk Drop a bookmark
Ctrl+kn Itterate through bookmarks
F7 Switch from HTML to Codebehind view
Ctrl+- Navigate backward through last cursor locations
Code Navigation :
F12 Goto Definition
Ctrl+] Jump to matching brace
Editing :
Ctrl+c Copy a whole line
Ctrl+v When a whole line in the clipboard (as above) this will instet a whole copied line.. handy for quick duplication
Ctrl+u Change to lower case
Ctrl+Shift+U Change to UPPER case
Macros :
Ctrl+Shift+R Record a quick Macro
Ctrl+Shift+P Run the quick Macro you just recorded
Comments
Ctrl+kc Comment out selected lines
Ctrl+ku Uncomment selected lines
Formatting
Ctrl+kd Autoformat selected lines
Hope this is more useful to attract others!Happy Programming