Pages

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Dec 8, 2011

How to set html link visible false depending on Eval function in grid view

Below is the html link in the grid view item template that sets visibility depending on the IsOnline values.

<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#

Use EntityFunction to truncate the time part from a DateTime String.

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#

This usage of double coutes in a string can be easily done using @.
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 is really a mind twisting question. But if you dint give a try to solve this , you may think that its so simple.
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#

Lets make use of the Namespace 
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#

Invoking a Command Line Utility From C#:


For eg. let's consider FWTools which has a command line utility named 
ogr2ogr for converting tab to kml
Below is the code to invoke the command line utility ogr2ogr

Invoking Command Line without parameters:

// Create an instance for System.Diagnostic.Process
Process proc = new Process();
// Provide the utility name with location
proc.StartInfo.FileName = @"C:\FWTools2.4.7\bin\ogr2ogr.exe";
// Start the process
proc.Start();

Invoking Command Line with normal parameters:
Note: -f, KML, sourcepath, destpath are arguments separted by space
Process proc = new Process(); 
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();

Invoking Command Line with Double couted parameters:

Usually space in the arguments list denote that each are separate
argument separated by space.

In the above code KML is the name of the driver used to convert 
Tab to KML.

And to convert ESRI's shape file to MapInfo's Tab file the driver 
used is "MapInfo File", which itself has a space

so by default command line arguments will consider it as a
two parameter one is "MapInfo" and other is "File"
so the program goes wrong.

Below is the solution, how to pass the double couted paremeter

string driver = "-f " + @"""" + "MapInfo File" + @"""" +
 @" C:\FWTools2.4.7\bin\test.tab C:\FWTools2.4.7\bin\test.shp";

By using this methodology, we can pass "MapInfo File" as a 
single argument to a command line utility.

May 17, 2010

How to Add a Water mark text to an image using C#.

 Below is the method which will add a text as a water marked text to an image.


 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#

DECIMAL TO DEGREE CONVERTION ON SERVER SIDE :

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 ()

{

Random r = new Random()

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#

Here is the method which can remove all the special characters from a given stirng

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

Thread in C# :
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

// 1st method, 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

Introduction:
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 {...}, where T is the type parameter.

Within class Stack you can use T as if it were a type. You can create a Stack as Integer by declaring
Stack or Stack as Customer object by declaring
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
OpenTag(T)CloseTag
{
// 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 = new Stack OpenTag Int CloseTag ();
stack.Push(3);
int i = stack.Pop();

The Stack type is called a constructed type. In the Stack type, every occurrence of T is replaced with the type argument int. The Push and Pop methods of a Stack operate on int values, making it a compile-time error to push values of other types onto the stack, and eliminating the need to explicitly cast values back to their original type when they are retrieved.
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 (T[] arr)
//for delegates delegate void Action OpenTag T CloseTag (T arg)

Inside the CLR
When you compile StackOpenTag T CloseTag , or any other generic type, it compiles down to IL and metadata just like any normal type. The IL and metadata contains additional information that knows there's a type parameter. This means you have the type information at compile time.
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 system looks to see if anyone already asked for Stack . If not, it feeds into the JIT the IL and metadata for Stack and the type argument int.


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 , Stack OpenTag Long CloseTag , Stack OpenTag Double CloseTag , Stack OpenTag Float CloseTag, CLR creates a unique copy of the executable native code.

So StackOpenTag int CloseTag gets its own code. Stack OpenTag Long CloseTag gets its own code. Stack OpenTag Float CloseTag gets its own code. Stack OpenTag int CloseTag uses 32 bits and Stack OpenTag Long CloseTag uses 64 bits. While reference types, Stack OpenTag Dog CloseTag is different from Stack OpenTag Cat CloseTag , but they actually share all the same method code and both are 32-bit pointers.

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