Wednesday, April 8, 2015

Filtering and copying emails to a .txt file from all the .txt files in a Directory

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FilesExamples
{
    class EmailFilter
    {
        public static void emas()
        {

            try
            {
                string FolderPath = @"D:\Practice Applications\Supported Files\randomemailtext\filtered\Input path";
                string line;
                var Outputdirectory = new DirectoryInfo(@"D:\Practice Applications\Supported Files\randomemailtext\filtered");
                // Loop to search all the .txt files in the directory path
                foreach (string file in Directory.EnumerateFiles(FolderPath, "*.txt"SearchOption.AllDirectories))
                {
                    StringReader srr = new StringReader(File.ReadAllText(file));
                    string dynamicFile = "OutputSample" + ".txt";

                    var Ofile = new FileInfo(Path.Combine(Outputdirectory.FullName, dynamicFile));
                    using (Stream stream = Ofile.OpenWrite())
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        Console.WriteLine("Copying, Please Wait...");
                        while ((line = srr.ReadLine()) != null)
                        {
                            const string MatchEmailPattern =
                            @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                            + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
                            Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            // Find matches.
                            MatchCollection matches = rx.Matches(line);
                            // Report the number of matches found.
                            int noOfMatches = matches.Count;
                            // Report on each match.

                            foreach (Match match in matches)
                            {
                                writer.Write(match.Value + "\r\n");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Monday, April 6, 2015

Singleton Design Pattern


Singleton Design Pattern


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class Singleton
    {
        // lazy initialization - only object is created first and reference is created when ever required.
        protected static Singleton testobj;

        // Default constructor is made private inorder to stop creating instances for the Singleton class.
        private Singleton()
        {

        }

       // this method will check if the object of the class already exists else it will create and returns it 
        public static Singleton GetObjectReference()
        {
            if (testobj == null)
            {
                testobj = new Singleton();
            }
            return testobj;
        }


        public void Print(string s)
        {
            Console.WriteLine(s);
        }
    }
}

An object reference is required for the nonstatic field method or property in c#


In this Example : Don't make your method (GetObject) static. It doesn't need to be static and it prevents you from using any non-static properties (like testobj). 

However if you need a method to be static, than it should not call the non-static members directly. Because the non-static member variables of a class always belong to an object.

If a method is static than non static members / properties cannot be accessed directly. otherwise create an instance to access non-static members or make the members as static. Else it will throw an error saying "an object reference is required for the nonstatic field method or property in c#" 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class Singleton
    {
        protected static Singleton _obj;
        private Singleton()
        {

        }

        public static Singleton GetObject()
        {
            if (_obj == null)
            {
                _obj = new Singleton();
            }
            return _obj;
        }

        public void Print(string s)
        {
            Console.WriteLine(s);
        }
    }
}


If static is removed than it errors out as mentioned. Because it cannot access an instance variable.