Using LINQ with Generic Dictionary in C#

Here is quick example for how to manipulate a Dictionary object for some constraint and get a new Dictionary Object from that, using LINQ.

Suppose we have a Dictionary as follows, which hold some of the values which might be null

 Dictionary<string, string> dictionaryWithNullValues = new Dictionary<string, string>();

Adding Items to Dictionary

            dictionaryWithNullValues.Add("one", "one");
            dictionaryWithNullValues.Add("two", null);
            dictionaryWithNullValues.Add("three", "three");
            dictionaryWithNullValues.Add("four", "four");
            dictionaryWithNullValues.Add("five", null);

Problem: we need a new dictionary object, almost same as the old one, but without the null values, from the old dictionary. Here is how we do this, using my beloved LINQ

   dictionaryWithoutNullValues =
   dictionaryWithNullValues
   .Where(d => d.Value != null)
   .ToDictionary(s => s.Key, s => s.Value);

To check the difference between both Dictionary Objects and verify, if this has worked, call the following properties on both old and new Dictionary Objects

Console.WriteLine("OldDictionary Keys: " + dictionaryWithNullValues.Keys.Count);
Console.WriteLine("OldDictionary Values: " + dictionaryWithNullValues.Values.Count);

Console.WriteLine("NewDictionary Keys: " + dictionaryWithoutNullValues.Keys.Count);
Console.WriteLine("NewDictionary Values: " + dictionaryWithoutNullValues.Values.Count);

Working with Files in c# – intoduction

Here are some of many classes available to work with files

using TextReder and TextWriter classes

string filePath = @"E:\TestDocument.txt";

// open file to read
TextReader tr = File.OpenText(filePath);
Console.WriteLine(tr.ReadToEnd());

// must close file after reading
tr.Close();

string filePath = @"E:\TestDocument.txt";

// open file to read
TextReader tr = File.OpenText(filePath);
Console.WriteLine(tr.ReadToEnd());

// must close file after reading
tr.Close();

using StreamReader and and StreamWriter classes

// open file to read file 
StreamReader sr = new StreamReader(filePath); 
Console.WriteLine(sr.ReadToEnd());

// must close file after writing
sr.Close();

// open file to write
StreamWriter sw = new StreamWriter(filePath);
sw.AutoFlush = true;
Console.WriteLine(sw.Encoding);
Console.WriteLine(sw.FormatProvider);
sw.WriteLine("Hello World");

// must close file after writing
sw.close()

Reading / writing To IsolatedStorageFile using IsolatedStorageFileStream

// declare file IsolatedStorageFile
IsolatedStorageFile isoStore = 
IsolatedStorageFile.GetUserStoreForAssembly();

// create file Stream
IsolatedStorageFileStream isoFS =
                new IsolatedStorageFileStream("temp.txt", FileMode.Create, FileAccess.Write);

// write to file
sw = new StreamWriter(isoFS);
sw.WriteLine("in iso storage" + "\n");           
sw.WriteLine("in iso storage FInished");

// must remember to close or the resouce is kept locked
sw.Close();

// read from IsolatedStorageFile
isoFS = new IsolatedStorageFileStream("temp.txt", FileMode.Open, FileAccess.Read);
sr = new StreamReader(isoFS);
Console.WriteLine(sr.ReadToEnd());

Working with Folder properties in C#

Here is a simple programs that evaluates different properties for a folder in Windows

class Folder : IComparable
    {
        public string name;
        public string path;
        public int size;
        public Folder(string _name, string _path, int _size)
        {
            name = _name;
            path = _path;
            size = _size;
        }

        #region IComparable Members

        public int CompareTo(object obj)
        {
            Folder folder = (Folder)obj;
            return folder.size.CompareTo(this.size);
        }

        #endregion
    }
class SizeClculator
    {
        public static ArrayList directories = new ArrayList();

        public static void GetFolders(string path)
        {
            DirectoryInfo di = new DirectoryInfo(path);
            if (di.GetDirectories().Length > 0)
            {
                foreach (DirectoryInfo dir in di.GetDirectories())
                {
                    GetFolders(dir.FullName);
                }
            }
            else
            {
                int size = 0;

                if (di.GetFiles().Length > 1)
                {
                    FileInfo[] fileInfo = di.GetFiles();
                    foreach (FileInfo fi in fileInfo)
                    {
                        size = size + (int)fi.Length;
                    }
                }
                directories.Add(new Folder(di.Name, di.FullName, size));
            }
        }
        public static ArrayList GetFoldersList()
        {
            return directories;
        }
    }
class Program
    {
        static void Main(string[] args)
        {
            string filePath = @"D:\Common\Test";
            SizeClculator.GetFolders(filePath);
            ArrayList al = SizeClculator.GetFoldersList();
            al.Sort();
            foreach (Folder folder in al)
            {
                Console.WriteLine("Name:" +
                    "  || " + folder.name +
                    "  || Path: " + folder.path +
                    "  || Size: " + folder.size);
            }
            Console.ReadKey();
        }
    }

Working with StringBuilder in C#

This Post will look in to several Methods provided with StringBuilder class. There are several ways to declare and initialize an instance of StringBuilder class.

// declare StringBuilder instance
StringBuilder sb;

// default constructor
sb = new StringBuilder();

// new stringbuilder with initial capacity 
sb = new StringBuilder(10);

// new stringbuilder with with a new string
sb = new StringBuilder("codingphobia.com");

// initial with initial capacity
// and max limit over capacity
sb = new StringBuilder(10, 100);

// new stringbuilder with with a new string
// and max limit over capacity
sb = new StringBuilder("codingphobia.com", 1000);

// new stringbuilder with new string
// start index to place string
// length of string
//  max limit over capacity
sb = new StringBuilder("codingphobia.com", 10, 16, 1000);

Here are some of the built-in methods

// append string to stringbuilder
Console.WriteLine(sb.Append("First"));

// get current capacity
Console.WriteLine("current string capacity: " + sb.Capacity);

// compare string with stringbuilder
Console.WriteLine(sb.Equals("First"));

// get the hash code for the string builder
Console.WriteLine(sb.GetHashCode());

// get the type for the object
Console.WriteLine(sb.GetType());

// get the length for the string
Console.WriteLine(sb.Length);

// gt the capacity for stringbuilder
Console.WriteLine(sb.Capacity);

// gt the max capacity for stringbuilder
Console.WriteLine(sb.MaxCapacity);

// get the string anfd write to console
Console.WriteLine(sb);

// insert char at specific index
Console.WriteLine(sb.Insert(2, '-'));

// replace a char at specific index
Console.WriteLine(sb.Replace('-', ' '));

// remove a char from specific index
Console.WriteLine(sb.Remove(2, 1));

Following methods allows us to extend our stringbuilder with appending value at the end.

// Add string at the end of stringbuilder
sb.Append("new string");

// Add string with end of line at the end of stringbuilder
sb.AppendLine("new string");

// Add string at the end of stringbuilder, 
// with information about the format etc
sb.AppendFormat(new CultureInfo("en-US"),
                "# # # ### ##", new char[] { 'A', 'S', 'D', 'F' });

Following methods show how can we extend our string builder using insert method which has 18 overloads.
most common are as follows

 // insert char at 0 index 
 sb.Insert(0, '0');

 // insert bool at 0 index
 sb.Insert(0, true);

 // insert char Array at 0 index
sb.Insert(0, new char[] { '0', '1' });

// insert double value at 0 index
sb.Insert(0, 10.00);

// insert decimal value at 0 index
sb.Insert(0, 10);

// insert char Array value, from  index 2 to 3,
// at index 0 of string builder
sb.Insert(0, new char[] { '1', '2', '3', '4' }, 1, 1);

// insert string at 0 index
sb.Insert(0, "a String");

How to check if printer is ready using c#

Say we have a document and we need to print it directly from our program instead of asking for help from PrintDialog or some other built-in feature. Before we send command to the printer, to print, we do need to check that printer is ready for command execution and there is no problem with it. Other wise, printer may raise error for any reason like, out of paper or ink problems or any thing else. This will cause an exception to be raised which is going to make the customer think .$5^&*…. about us which is not desirable.

So, is there any way to check if the device is ready ? before we send the print command ?

Here are two of the several methods, we can use to do so

METHOD 1:

        public bool CheckMyPrinter(string printerToCheck)
        {
          ManagementObjectSearcher searcher = new  
              ManagementObjectSearcher("SELECT * FROM   Win32_Printer"); 

          bool IsReady = false;
          foreach (ManagementObject printer in searcher.Get())
          {    
            if (printer["Name"].ToString().ToLower().Equals(printerToCheck))
            {     
              if (printer["WorkOffline"].ToString().ToLower().Equals("false"))
                {
                  IsReady = true;
                }                    
            }      
          }
          return IsReady ;
        }

METHOD 2: Will throw Exception, but you can catch it and work accordingly

            bool printerStatus = false;
            try
            {
                PrintDocument pd = new PrintDocument                                            
                              { 
                                PrinterSettings = new  PrinterSettings 
                                    { 
                                       PrinterName = "Name"
                                    } 
                               };
                printerStatus = pd.PrinterSettings.IsValid;
            }
            catch (System.Exception ex)
            {
            }