There are many ways to remove duplicate elements from a generic List collection in the C# language, but some are easier to implement then other, or some might not fit your code. An easy solution, is using the LINQ extension methods can be very useful when you have a List collection. It is lightweight, and is can also be implemented anywhere in your solution.
For my example, I used the Linq "Distinct" method (System.Linq) to get a unique list of categories for books. I first get a list of my books from the database, and then use the "distinct" method, and then also cast the list back to a generic list with the duplicate items removed.
/// <summary>
/// Returns the distinct list of categories.
/// </summary>
/// <returns>List<string></returns>
private static List<string> ReturnDistinctListofCategories()
{
// List with duplicate elements.
List<string> list = new List<string>();
list.Add("code");
list.Add("coding");
list.Add("asp.net");
list.Add("tips");
list.Add("code");
list.Add("coding tips");
list.Add("asp.net tips");
// We now have a list with duplicate items
// Get distinct elements and convert into a list again.
List<string> distinctClientList = list.Distinct().ToList();
//DEBUG: Test the result
foreach (string value in distinctClientList)
{
Debug.WriteLine(value);
}
return distinctClientList;
}
I hope this can help you. Like I stated before, there are numerous ways to do the same as my code.
ed683bc3-4e68-4d25-b7cc-24b804ec9fe4|0|.0
If you are working with Enumerations (enum) in C#, you will know how easy it is to use within your code. Enum's are strongly typed constants which are unique types and allows you to assign symbolic names to integral values.
Enum is also a reserved keyword and is a value type, which means we can use it as a string, if the need arises. I have added an example where I would like to write out the Gender value of a enum. Because I can't just write the value to screen, I need to convert it to a string, which is actually very easy.
The following example demonstrates converting an enumerated value to a string.
public class GenderSample {
enum Gender {Male = 1, Female = 2};
public static void Main() {
Enum GenderOptions = Gender.Male;
Console.WriteLine("The value of this instance is '{0}'",
GenderOptions.ToString());
}
}
Output: The value of this instance is 'Male'.
c8ce2f91-df20-4652-a1f3-966d8901be11|0|.0
This week I was asked by a friend how you would reverse a sentence, with minimial effort and that works in all scenarios. This was a nice challenge for me, so started working on something.
I first though of using recursion with a substring method to reverse the sentence, which worked fine, however this looked a bit messy and I thought it might impact on the performance of the program. I searched MSDN and the ASP.NET website for an alternative option, and surprisingly I found an article which Justin Rogers wrote, which did exactly what I was looking for... You can use the 'Array.Reverse()' method that is already provided to you by the .Net framework.
Here is an example of how to efficiently reverse the characters in a string:
static public string Reverse(string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
Input: Hello World
Output: dlroW olleH
The example above is just for demostration. In my case, I was using large strings, therefore this method was the preferred option. In some cases you can use recursion with a substring method, which will be a better choice on performance.
I though I would share Justin's article, so you can read it here.
71ef8e12-950f-4e5b-86b5-b5a06cfe75b4|0|.0
Caching is one of the least used but a very powerful feature of ASP.NET. It can save you time and also unnecessary trips to the database. If you need to cache any type of information in ASP.NET such as a DataSet, DataTable, or an ArrayList, you can use the cache. This works a lot like a 'session' or 'application variable', but it has some added cache-related methods as well. Scalable web applications should have the ability to store items, whether data objects, pages, or event parts of a page, in memory. This allows you to avoid recreating information, expensive database calls or even connections to 3rd party web services.
However sometimes you might want to clear all these cached objects in one go for some specific reason. Like I said web applications should be scalable and build towards high-performance. This is where you will need to use the 'Cache.Remove()' method, as the built-in cache object in ASP.NET does not support a 'Cache.Clear()' method.
Here is an example of storing a datatable and in the cache:
DataTable dtCacheExample = new DataTable();
//code here: add rows to datatable
Cache["dtCacheExample"] = dtCacheExample;
ArrayList arrCacheExample = new ArrayList();
//code here: add items to arraylist
Cache["arrCacheExample"] = arrCacheExample;
To clear the cache use the following:
// Retrieve a dictionary enumerator used to iterate through the
// key settings and their values contained in the cache.
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator;
while (CacheEnum.MoveNext) {
Cache.Remove(CacheEnum.Key.ToString);
}
8e26116a-ba08-4d4b-848c-7c650f297a60|0|.0
As a .NET developer, you can sometimes spend hours finding errors and handling them when you do not know the core logic of the system, and decent good documentation is not that easy to come by. There are several ways to address erros, by using exceptions. Exceptions are designed to handle errors and most commonly in a "try/catch" statement.
It is good practice to not catch the generic errors, and try and debug from there. If you do this, you are unsure what your code is actually doing - which can result in the business living with the concequences. The key is to know which errors you might expect and catch those and handle them accordingly. An exception I found to be hard to track, is the "OverflowException" exception.
From MSDN: An OverflowException exception is thrown when a casting, conversion or arithmetic operation in a checked context results in an overflow. An overflow occurs when an operation produces a value too large for the destination type, infinity, or Not a Number (NaN).
For example, mathematical operations can cause these type of exceptions. A way to check for this error is to use the 'checked' keyword. The 'checked' keyword is used to detect overflow conditions. You should note that an 'OverflowException' exception occurs only in a checked context.
Here is a code example on how to check for this type of exception, and how to handle it.
public static void Main()
{
try
{
checked
{
int aInt;
int bInt;
int Sum;
aInt = 2000000000;
bInt = 2000000000;
Sum = aInt + bInt;
}
}
catch (OverflowException oExcep)
{
Console.WriteLine("A mathematical operation caused an overflow.");
// Good idea to log this error and deal with it when doing debugging
// I am using my own Logging module.
Logger.LogException(oExcep, "A mathematical operation caused an overflow.");
}
}
fa69f69a-97e0-4542-8292-0b7001e6ade9|0|.0
The "Environment" class of the System namespace is handy for getting and setting various operating system related information. The "Environment" class to retrieve information such as the current directory, network details, machine name, OS versions, environment variable settings, contents of the call stack, time since last system boot, and the version of the common language runtime.
There is a lot of information that can be extracted with the "Environment" class. Below is a small code snippet that might help you get started.
public static void GetEnvironmentDetails()
{
Console.WriteLine();
Console.WriteLine("-- Environment members --");
// Invoke this sample with an arbitrary set of command line arguments.
Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
String[] arguments = Environment.GetCommandLineArgs();
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
// <-- Keep this information secure! -->
Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
// <-- Keep this information secure! -->
Console.WriteLine("MachineName: {0}", Environment.MachineName);
Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
// <-- Keep this information secure! -->
Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
Console.WriteLine("TickCount: {0}", Environment.TickCount);
// <-- Keep this information secure! -->
Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
// <-- Keep this information secure! -->
Console.WriteLine("UserName: {0}", Environment.UserName);
Console.WriteLine("Version: {0}", Environment.Version);
Console.WriteLine("GetFolderPath: {0}",
Environment.GetFolderPath(Environment.SpecialFolder.System));
String[] drives = Environment.GetLogicalDrives();
Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
}
41ec2b83-c8de-4281-852f-b801e05e233b|0|.0
The 'is' operator is used to check whether the run-time type of an object is compatible with a given type, and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.
For example:
public static void RunThis()
{
// For this example the following obj is a class already created
object obj = new MyClass();
CastCheck(obj);
}
public static void CastCheck(object obj)
{
// For this example the following classes are already created
Class1 a;
Class2 b;
if (obj is Class1)
{
Console.WriteLine("obj is Class1");
a = (Class1)obj; // do something with a
}
else if (obj is Class2)
{
Console.WriteLine("v is Class2");
b = (Class2)obj; // do something with b
}
else
{
Console.WriteLine("obj is neither Class1 nor Class2.");
}
}
The 'is' operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.
aa01e2db-916a-47ec-bcf9-5a2faf80e9f4|0|.0
The 'as' operator is a "type", and is just like the cast operator except that it will return NULL on a conversion failure instead of throwing an exception. The 'as' operator is used to perform conversions between compatible types and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.
For example:
Object objValue = new Object();
string strA = (string)objValue; //Cast throws an Exception
string strB = objValue as string; //No exception is thrown, but strB is set to NULL
The 'as' operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.
d068c41b-f1e6-44cf-b775-829302744af6|0|.0
The phrase "iterating through a directory tree" can also mean "iterating through a folder tree structure". Both statements are valid, when you talk about Windows 'directories' of 'folders'. Iteration means to access each file in each nested subdirectory under a specified root folder, to any depth, unless you specify how many levels 'down' you would like to search. You do not necessarily have to open each file. You can just retrieve the name of the file or subdirectory as a string, or you can retrieve additional information in the form of a System.IO.FileInfo or System.IO.DirectoryInfo object.
The following example shows how to iterate through files and folders in a directory tree without using recursion. You should be careful to modify this code to suit your needs.
static void Main()
{
//Specify the starting folder
string folder = "C:/myfolder/tips/dascode/";
RetrieveTreeStructureFiles(folder);
Console.WriteLine("Press any key");
Console.ReadKey();
}
public static void RetrieveTreeStructureFiles(string root)
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack dirs = new Stack(2);
if (!System.IO.Directory.Exists(root))
{
throw new ArgumentException();
}
dirs.Push(root);
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories(currentDir);
}
// An UnauthorizedAccessException exception will be thrown if we do not have
// discovery permission on a folder or file.
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e.Message);
continue;
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
foreach (string file in files)
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo(file);
Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
}
catch (System.IO.FileNotFoundException e)
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
Console.WriteLine(e.Message);
continue;
}
}
foreach (string str in subDirs)
{
dirs.Push(str);
}
}
}
f15a2334-2bd0-4400-ac9b-f1fdc954f50c|0|.0
Every now and again you might want to use the "delete" or "update" commands from a gridview. However, once you click the button to delete the item from the list or in most cases from the database - you have no safety check. The user might make a mistake, and it can be a costly mistake. An easy way to force the user to think about this action, is to use javascript and ask the user if he/she is sure they want to delete the item.
In the RowDataBound event of the GridView control, you will find the 'Delete' command button control by specifying the cell index. All you have to do is add an 'attribute' to the control, and the "onclick" event. This will trigger a javascript confirmation alert to the user, which asks the user if he/she is sure they want to delete the item. Only when the user confirms the action, will the item be deleted.
Here is a simple example using C# and javascript.
1: if (e.Row.RowType == DataControlRowType.DataRow)
2: {
3: // check for controls in the gridrow cell. Index starts at 0.
4: if (e.Row.Cells[3].HasControls())
5: {
6: LinkButton btnDelete = ((LinkButton)e.Row.Cells[3].Controls[0]);
7: btnDelete.Attributes.Add("onclick",
8: "return confirm('Are you sure you want to delete this item?');");
9: }
10: }
It is important to note that you should always check if the control exists or not. This will be very useful, when the 'Edit' command button is used along with 'Delete' command button.
61fca6d3-7a51-4466-8faf-c657d4859b18|1|3.0