Friday, September 24, 2010

 

Using Predicate Delegates and Lambda Expressions

Lets see what new in C#:
Old way of iteration of each item in List can be avoided by using either Predicate (which is fastest in term of performance) or using Delegate or by using Lambada Expression.

Code:

private static void TestFeatureProgression()
{
// Example 1:
// Olden days methodolgy for finding odd numbers in an array
// back before even Generics were available
ArrayList al = new ArrayList(){20, 1, 3, 4, 8, 9, 44, 47 };
int[] intList = new int[] {20, 1, 3, 4, 8, 9, 44, 47 };
ArrayList oddIntegers = new ArrayList();

foreach (int i in intList)
{
if ((i % 2) > 0)
{
oddIntegers.Add(i);
}
// if
} // foreach

DisplayNumbers(oddIntegers, "using an array search");

// or since we now have generics, we can jump ahead and
// convert the arraylist to a generic list and pass it to
// the method that displays a List<>
DisplayNumbers(new List<int>(oddIntegers.ToArray(typeof(int)) as int[]),
"using array search printed from generic list");


// Now, we bring in Generics and their power. Not only is a
// List more powerful than an ArrayList, but it is
// strongly typed so that unlike an arraylist, you cannot add
// a string to the List. First we will create a
// list of integers with automatic initialization just as we
// previously did with the creation of an array.
// which will be used by all three examples
List<int> list = new List<int>() { 20, 1, 3, 4, 8, 9, 44, 47 };


// Example 2):
// first, a Predicate delegate is a reference that returns a bool
// note that IsOddNumber is a separate method shown below
Predicate<int> callBack = new Predicate<int>(IsOddNumber);

// now you can pass the Predicate delegate to the FindAll method of the generic List
List<int> oddNumbers = list.FindAll(callBack);

// at this point all even numbers are in the list evenNumbers
DisplayNumbers(oddNumbers, "using Predicate delegate");

// Example 3):
// now shorten code by using an anonymous method
// note that we no longer need to declare and use the IsOddNumber method
list = list.FindAll(delegate(int i) { return (i % 2) > 0; });

DisplayNumbers(oddNumbers,
"using anonymous method");

// Example 4:
// a lambda expression can even shorten it more
// the => (lambda) symbol means that the parameter (list) on the left side
// of the lambda symbol is to be processed by the expression on the right side
// of the lambda symbol. The expression was originally a formally coded delegate
// and in Example 2, it required a method to be the target of the Predicate.
// In the second example we shortened the code by the use of an anonymous method
// allowing us to do away with the Predicate and its target method (IsOddNumber).
// In Example 4 shown below, the FindAll method of the list object will call
// the implied anonymous method for each object in the List.
// To sum up the following line of code in english:
// My list of paramaters "[int] i" will be processed by the expression "(i % 2) > 0"
oddNumbers = list.FindAll(i => (i % 2) > 0);

DisplayNumbers(oddNumbers,
"using a lambda expression");

// you could
}


/// target for the Predicate<> delegate
static bool IsOddNumber(int i)
{
// is it an even number?
return (i % 2) > 0;
}

private static void DisplayNumbers(ArrayList oddNumbers, string s)
{
Console.WriteLine("Here are your odd numbers " + s);
foreach (int oddNumber in oddNumbers)
{
Console.Write("{0}\t", oddNumber);
}
// foreach
Console.WriteLine(Environment.NewLine + Environment.NewLine);
}
// method: DisplayNumbers

private static void DisplayNumbers(List<int> oddNumbers, string s)
{
Console.WriteLine("Here are your odd numbers " + s);
foreach (int oddNumber in oddNumbers)
{
Console.Write("{0}\t", oddNumber);
}
// foreach
Console.WriteLine(Environment.NewLine + Environment.NewLine);
}



Output of the above code is as under:



Here are your odd numbers using an array search
1 3 9 47


Here are your odd numbers using array search printed from generic list
1 3 9 47


Here are your odd numbers using Predicate delegate
1 3 9 47


Here are your odd numbers using anonymous method
1 3 9 47


Here are your odd numbers using a lambda expression
1 3 9 47

Labels:


Thursday, September 02, 2010

 

Get System Folder Path while runnig Library class

using System.IO;

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

Wednesday, July 15, 2009

 

Creating a Test Application to Convert

1. Create a new Web Application in Visual Studio 2003
2. Go to the code behind for WebForm1
3. In WebForm1 Create a Public Static Method which returns a string.
4. Add a Class File
5. In the Class File Create a Public Static Method which returns a string.
6. In WebForm1_PageLoad call the ClassFile method and the WebForm1 Method
7. Create a new WebForm
8. Add a reference to the method in WebForm1 in to WebForm2
9. Add a new Folder
10. Add another Page in to there
11. Add a reference to the Method in WebForm1 into WebForm3

Converting the Application

12. Convert the Applications to 2005 Format

13. Look at the Conversion Wizard Report
a. Note Code Files being moved to the Code Folder

Moved file Global.asax.cs to the App_Code\ directory.
Moved file Class1.cs to the App_Code\ directory.
Moved file AssemblyInfo.cs to the App_Code\ directory.

14. Note how WebForm1 & WebForm2 run fine.
15. Note how WebForm3 doesn’t work at all
a. Show the code behind of this file and the lack of WebForm1 class being available.
16. Note how the project will not build with the erroneous entries.

Precompile the Web Site

17. Fix any errors so the site will “Rebuild All”.
18. Publish the Web Site using the publish tool.
19. Show the content of the Bin folder.
a. Note how WebForm1.aspx and WebForm2.aspx share the same filenames (just before the .dll) whereas WebForm3 has a different filename.

Version Switcher on Windows XP

1. Show two sites
2. Make warning Regarding Production Servers
3. Point out it can be done from the command line
 

function to test dates

private void TestDates()
{
DateTime dt = DateTime.Now;
string timeHHMMSS = dt.ToString("HHmmss");

Console.WriteLine(dt);
Console.WriteLine(int.Parse(timeHHMMSS));
Console.WriteLine(timeHHMMSS);
TimeSpan ts = dt.TimeOfDay;
Console.WriteLine(ts.ToString());
timeHHMMSS = dt.ToString("HHmm");
Console.WriteLine(timeHHMMSS);
}
 

function to test HHMM -- HoursMins using regular expression (REGEX)

private string TestHHMM()
{
string InputString = DateTime.Now.ToString("HHmm"); // "2200";
if (InputString.Length >= 2)
InputString = InputString.PadLeft(4, '0');
Regex RegexObj = new Regex("^([0-1]\\d|2[0-3])([0-5][0-9])$");
if (RegexObj.IsMatch(InputString))
Console.WriteLine("true");
else
Console.WriteLine("false");
return RegexObj.Replace(InputString, "$1:$2");
}
 

function to test date MonthYear from input string

private string TestDateMonthYear()
{
string InputString = "200819";
Regex RegexObj = new Regex("^(\\d{4})([0]?[1-9]|1[0-2])$");
return RegexObj.Replace(InputString, "$2/$1");
}

Tuesday, April 05, 2005

 

Get No Of Days In Month

GetNoOfDaysInMonth
Function (dateTimeVar investmentPaidDate)

numberVar intDay := 1;

dateVar monthStartDate := CDate (Year (investmentPaidDate), Month (investmentPaidDate) ,1) ;
dateVar monthEndDate := CDate (Year (investmentPaidDate), (Month (investmentPaidDate))+1 ,1);
monthEndDate = DateAdd ("d", -1 , monthEndDate );

intDay = DateDiff ("d", monthStartDate , monthEndDate );

intDay;
 

Get No Of days in Year

GetNoOfDaysInYear

Function (dateTimeVar investmentDate)

numberVar intDay := 1;

dateVar yearStartDate := CDate (Year (investmentDate), 1 , 1) ;
dateVar yearEndDate := CDate (Year (investmentDate), 12 , 31);

intDay = DateDiff ("d", yearStartDate , yearEndDate );

intDay;
 

ESC key

Do this

create a button on the same form where you have to get hold of ESC key!

in the form properties check out CancelButton and set its value to the the button designed right now. now write the routine for that button if it is clicked.

you can also assign it at runtime like this:
(C#) this.CancelButton=button24;
(VB.NET) Me.CancelButton=button24

With Best Regards,
Mitesh V. Mehta
 

Pivot Tables with ADO.NET and Display in Horizontal Paged DataGrid

This article describes a simple method to pivot a DataTable producing rows for each column and a column for each row. The pivoted DataTable is then displayed in a DataGrid using horizontal paging to view a limited number of Columns in each page. This is a common display technique used to compare, for instance, product features, where the product names appear across the top of the DataGrid with the Features listed down the side.

http://aspalliance.com/538
 

How to write an Office Plug-In/Add-In Using C#.NET

There are many Win/Web applications where we would use Office...this
article throws light on how to add office plug-in/add-in using C#.NET
into your application.

Pls find more information about article here...
http://msd2d.com/newsletter_tip.aspx?section=dotNet&category=C%20Sharp&id=e2227b60-6db6-4933-921a-88a1cd227c4f


With Best Regards,
Mitesh V. Mehta
 

String Enumerators

using System;
using System.Reflection;

enum EnumError
{
OverLimit,
UnderLimit,
Normal,
}

class EnumErrorDescriptions
{
const string OverLimit = "Oh you have exceeds your limit!";
const string UnderLimit = "Oh! you are much below your limit!";
const string Normal = "Oh! you are within your limit!";

internal static string GetErrorMessage (EnumError err)
{
string enumName = err.ToString();

FieldInfo fi = typeof(EnumErrorDescriptions).GetField
(enumName, BindingFlags.Static|BindingFlags.NonPublic);
if (fi==null)
{
// Oops! You could throw an exception here if you wanted -
// or return another constant, maybe.
return "Unknown error";
}
return (string)fi.GetValue(null);
}
}

class Test
{
static void Main()
{
Console.WriteLine (EnumErrorDescriptions.GetErrorMessage
(EnumError.OverLimit));
}
}



Basically enum provides only integer values, but through this mechanism you can get string values through enum (string enumeration).


With Best Regards,
Mitesh V. Mehta

Tuesday, November 23, 2004

 

Optional Parameters with C#

If you are creating component or library, then you have to consider many aspects of component development. One of the aspects is trying to provide a feature, which is not supported by the language in which components or library is being created. One of such thing is creating optional method parameters in C#, Languages like VB.Net natively supports such kind of parameters. So if you want to create optional method parameters in C# for VB.Net here is the way out.

In the namespace System.Runtime.InteropServices there is a one attribute defined, OptionalAttribute Just apply it to the argument you want to make as optional. That’s it…

For example…

public string GetName([Optional]string param)
{
if (param == null) //Check for null.
param = "Aamir"; //Set the default value.
return param;
}

Any yes, remember for C# optional parameters are not optional…

Saturday, October 23, 2004

 

Security related C# code samples

Code access security with C#
CodeAccessSecuritySample.exe : http://download.microsoft.com/download/f/c/5/fc59614c-f610-4ab5-a9bb-82b784741313/CodeAccessSecuritySample.exe
Demonstrates the use of .NET Framework Code Access Security, in which code can have permissions independent of the person executing the code.

Web Services Security with C#
WebServiceSecuritySample.exe: http://download.microsoft.com/download/f/c/5/fc59614c-f610-4ab5-a9bb-82b784741313/WebServiceSecuritySample.exe

Examines how to use IIS to perform user authentication so that no changes to the Web Service are required in order to provide superior security.

All the samples can be found @
http://msdn.microsoft.com/vcsharp/downloads/samples/23samples/default.aspx


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Tuesday, September 21, 2004

 

ToolTip in Windows

Well if you have been doing Web development for a long time in .Net now, if
you switch to windows it would pretty much possible for you to search for
the standard ToolTip property for all the controls and guess what you won't
find it... :-)
Windows UI is much more richer than web and so the windows controls try to
leverage that... For this reason there is a special ToolTip control which is
provided to you in the windows environment which you can associate with any
of your controls...
Now what are some of its advantages the code below will tell you:

ToolTip mvmTip = new ToolTip();
mvmTip.InitialDelay = 1500;
mvmTip.ReshowDelay = 1000;
mvmTip.SetToolTip(this.txtZipCode, "You need to provide a zip code only
if you are in US or Canada");

Similarly you also have GetToolTip() method... Well so go ahead and try
explore more on the ToolTip control...


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

 

System.IO.FileSystemInfo

This is nothing new, but I felt the need to share since so many miss it.
Many a times I see stuff like this being done (even I also did for sometime):

string FolderPath = FilePath.Substring(0, FilePath.LastIndexOf(@"\"));

Obviously they are trying to get the full path to a file. Next time your thinking about doing something like that consider:

System.IO.FileInfo fi = new System.IO.FileInfo(FilePath);
string FolderPath = fi.DirectoryName;

Much easier.

Take a look at all the other goodies in the System.IO.FileInfo class:

fi.Extension
fi.FullName
fi.Name
fi.Length
fi.Directory.FullName
fi.Directory.Name
fi.Directory.Root.FullName
fi.DirectoryName

Not to mention these methods:

fi.Open();
fi.OpenRead();
fi.OpenText();
fi.OpenWrite();

More: http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemIOFileInfoClassTopic.asp



With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Wednesday, September 01, 2004

 

Add shortcut for uninstall in the Programs menu.

Your query is incomplete! We need more info to be able to help you.
What exactly is your query? Is it
a. You have added the path to your application as a shortcut under Start->Programs menu and now you want another shortcut named "uninstall application" which will delete all related files for this application?
b. Or you already have an installer project built for your app but when you run the installer, it doesn't add a menu entry for Uninstall ?
c. Or do you want to add your application's uninstall shortcut specifically under the Programs' menu for VS.NET 2003

Now some possible solutions:
For question (a) above, you don't need to write C# code. It can be accomplished using VBScript. Try this sample code :
'--------- code begin-------------
Set WshShell = CreateObject("WScript.Shell")
strProgramsPath = WshShell.SpecialFolders("Programs")

Set objShortcutLnk = WshShell.CreateShortcut(strProgramsPath & "\Uninstall Application.lnk")
objShortcutLnk.TargetPath = "my uninstaller.exe"
objShortcutLnk.Save
'---------code end ------------------
Save the above code to some file with vbs extension. Change "my uninstaller.exe" to refer to the uninstaller which you have created.
The above snippet creates a shortcut only for the current user. For All users, replace "Programs" above with "AllUsersPrograms"

b. In case you are not satisfied with VS.NET's inbuilt installer, you might want to try out one of the installers listed here:
http://www.sciencedaily.com/directory/Computers/Software/System_Management/Installers

c. Are you sure you want to do this? :)


With Best Regards,
Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Sunday, August 29, 2004

 

CheckDuplicate in Dataset

Hi,

Say the dataset ("MyDataset") has a table ("MyTable") that has following data in one of the columns ("COL1"): 'a', 'b', 'c', 'd' and 'e' (5 entries, since there are 5 rows). Say the user enters a value 'a' in a text (txtValue) box and clicks submit. In the submit button's click handler, you have to do is this (in C#):

DataRow[] drArray = MyDataSet.Tables["MyTable"].Select("COL1 = " + txtValue.Text.Trim());

if(drArray.Length > 0) //User has entered a value that already exists in the dataset
{
//Display message
}
else //User has entered a unique value
{
//Proceed with further processing.
}

This code will not check for case-insensitivity, i.e., if the user enters 'A' instead of 'a', it will take it as a unique entry. You will have to add further checks to ensure case-insensitivity. Hope this helps.

Mitesh Mehta
Email : miteshvmehta@gmail.com
http://cc.1asphost.com/miteshvmehta/

Monday, July 26, 2004

 

Indexers In C#



Indexers In C#


C# introduces a new concept known as Indexers
which are used for treating an object as an array. The indexers are
usually known as smart arrays in C# community. Defining a C# indexer is
much like defining properties. We can say that an indexer is a member
that enables an object to be indexed in the same way as an array.

 <modifier> <return type> this [argument list]

{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}


Where the modifier can be private, public,
protected or internal. The return type can be any valid C# types. The
'this' is a special keyword in C# to indicate the object of the current
class. The formal-argument-list specifies the parameters of the
indexer. The formal parameter list of an indexer corresponds to that of
a method, except that at least one parameter must be specified, and
that the ref and out parameter modifiers are not permitted.
Remember that indexers in C# must have at least one parameter. Other
wise the compiler will generate a compilation error.


The following program shows a C# indexer in action

// C#: INDEXER

// Author: miteshvmehta@gmail.com

using System;
using System.Collections;

class MyClass
{
private string []data = new string[5];
public string this [int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
}


class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc[0] = "Rajesh";
mc[1] = "A3-126";
mc[2] = "Snehadara";
mc[3] = "Irla";
mc[4] = "Mumbai";
Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]);
}
}


The indexers in C# can be overloaded just like
member functions. The formal parameter list of an indexer defines the
signature of the indexer. Specifically, the signature of an indexer
consists of the number and types of its formal parameters. The element
type is not part of an indexer's signature, nor is the names of the
formal parameters. The signature of an indexer must differ from the
signatures of all other indexers declared in the same class. C# do not
have the concept of static indexers. If we declare an indexer static,
the compiler will show a compilation time error.

Indexers & Inheritance


Just like any other class members, indexers
can also participate in inheritance. A base class indexer is inherited
to the derived class.

//C#: Indexer : Inheritance

//Author: miteshvmehta@gmail.com
using System;
class Base
{
public int this[int indxer]
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}

class Derived : Base
{

}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1[0] = 10;
Console.WriteLine(d1[0]);//Displays 'Base SET Base GET 10'
}
}


Indexers & Polymorphism


A Base class indexer can be polymorphicaly
overridden in a Derived class. But remember that the modifiers like
virtual, override etc are using at property level, not at accessor
level.

//C#: Indexer : Polymorphism

//Author: miteshvmehta@gmail.com

using System;

class Base
{
public virtual int this[int index]
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}

class Derived : Base
{
public override int this[int index]
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}

class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1[0]= 10;
Console.WriteLine(b1[0]);//Displays 'Derived SET Derived GET 10'
}
}


Abstract Indexers


An indexer inside a class can be declared as
abstract by using the keyword abstract. Remember that an abstract
indexer in a class carries no code at all. The get/set accessors are
simply represented with a semicolon. In the derived class we must
implement both set and get assessors.


If the abstract class contains only set accessor, we can implement only set in the derived class.


The following program shows an abstract indexer in action.

//C#: Indexer : Abstract

//Author: miteshvmehta@gmail.com

using System;

abstract class Abstract
{
public abstract int this[int index]
{
get;
set;
}
}

class Concrete : Abstract
{
public override int this[int index]
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}

class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1[0] = 10;
Console.WriteLine(c1[0]);//Displays 'SET GET 10'
}
}




Indexers & Properties


1. An index is identified by it's signature. But a property is identified it's name.

2. An indexer is always an instance member, but a property can be static also.

3. An indexer is accessed through an element access. But a property is through a member access.


Conclusion


The indexer is one of the key concepts of C#
and are very interesting aspects of the language.



This page is powered by Blogger. Isn't yours?