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.


Tuesday, December 16, 2014

Understanding Generics


Understanding Generics:

Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.




namespace Apps
{
    class UnderstandingGenerics
    {
        static void GenericsTest<T>(T lhs, T rhs)
        {
            Console.WriteLine("{0}, {1}", lhs, rhs);
        }
        static void Main(string[] args)
        {
            int a = 10, b = 2;
            Char c = 'r', d = 's';
            GenericsTest<int>(a, b);
            GenericsTest<char>(c, d);
        }
    }
}

Thursday, September 25, 2014

HyperLinks in text file C#

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

namespace HyperLinksFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                StreamReader sfilecontent1 = new StreamReader(@"D:\log");
                StreamWriter dfilecontent2 = new StreamWriter(@"D:\test.txt");
                string line;
                while ((line = sfilecontent1.ReadLine()) != null)
                {
                    //string[] words = line.Split(',');
                    //string k = words[1];
                    //dfilecontent2.Write(k.Trim() + "\r\n");

                    if (line.Contains("http"))
                    {
                        dfilecontent2.Write(line+"\r\n"+"\r\n");
                    }
                }
                sfilecontent1.Close();
                dfilecontent2.Close();
                Console.WriteLine("File created Successfully!");
            }
            catch (Exception ex1)
            {
                Console.WriteLine(ex1.Message);
            }
        }
    }
}

Tuesday, August 26, 2014

Understanding Static Constructor (C# reference)

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

namespace Apps
{

    class statiConstructor
    {
        private static int a;
        static statiConstructor()
        {
            a = 10;
            Console.WriteLine("Static Constructor with static member value=" + a);
        }
        public static void MethodCall()
        {
            Console.WriteLine("Method Call ");
        }
    }
    class UnderstandingStaticConstructor
    {
        public static void Main()
        {
         // In particular, a static constructor is called once, automatically, when the class is used for the first time.
            statiConstructor k = new statiConstructor();

            statiConstructor.MethodCall();
            statiConstructor.MethodCall();

        }
    }
}



Output:

Static Constructor with static member value = 10
Method Call
Method Call