Friday, September 24, 2010
Using Predicate Delegates and Lambda Expressions
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
// a string to the List
// 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
// 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: Predicate Delegate Lambda Expression
Thursday, September 02, 2010
Get System Folder Path while runnig Library class
Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
Wednesday, July 15, 2009
Creating a Test Application to Convert
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
{
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)
{
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
{
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
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
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
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
http://aspalliance.com/538
How to write an Office Plug-In/Add-In Using C#.NET
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.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#
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
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
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
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.
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
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#
<modifier> <return type> this [argument list] 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.
// C#: INDEXER 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
//C#: Indexer : Inheritance Indexers & Polymorphism
//C#: Indexer : Polymorphism Abstract Indexers
//C#: Indexer : Abstract Indexers & Properties
|