Posts

File helpers using LINQ

When dealing with files, it is useful to have standard set of helpers to be used that we can relay on. This is when LINQ comes in handy. In this article I will present you with some useful functions that you can use in your daily programming.

Simple operation should be simple. Hence, when getting the number of lines in the text file, one line of code is just enough.

 public static long GetNumberOfLines(string filePath)
 {
     return File.Exists(filePath) ? File.ReadAllLines(filePath).Count() : 0;
 }

Getting the biggest file in the folder is also very easy with LINQ

   public static string FindTheLargestFileInDirectory(string path)
    {
        return Directory.Exists(path) && Directory.GetFiles(path).Count() > 0 ? 
               Directory.EnumerateFiles(path).Select(i => new FileInfo(i))
               .OrderByDescending(i => i.Length).FirstOrDefault().FullName : null;
    }

Similar when getting all files with the size of less than 1 Kb

   public static IEnumerable<string> FindFilesLessThanOneKiloBytesInThisFolder(string path)
    {
        return Directory.Exists(path) && Directory.GetFiles(path).Count() > 0 ?  
             Directory.EnumerateFiles(path).Select(i => new FileInfo(i))
             .Where(i => i.Length < 1024).Select(i => i.FullName) : null;
    }

You can use this function if you need to get files created in last 7 days

   public static IEnumerable<string> FindAllFilesCreatedLessThanWeekAgo(string path)
   {
        return Directory.Exists(path) && Directory.GetFiles(path).Count() > 0 ? 
               Directory.EnumerateFiles(path).Select(i => new FileInfo(i))
               .Where(i => i.CreationTime > DateTime.Now.AddDays(-7))
               .Select(i => i.FullName) : null;
   }

And finally if you want to get the oldest file in the folder (common scenario when deleting old logs) you can try this

   public static string FindOldestFileInFolder(string path)
   {
        return Directory.Exists(path) && Directory.GetFiles(path).Count() > 0 ? 
               Directory.EnumerateFiles(path)
               .Select(i => new FileInfo(i))
               .OrderByDescending(i => i.LastAccessTime).FirstOrDefault()
               .FullName : null;
   }

If you want to compare two files and get identical lines this may be useful to you

   public static IEnumerable<string> FindIdenticalLinesInTwoFiles(string filePath1, string filePath2)
    {
        if (File.Exists(filePath1) && File.Exists(filePath2))
        {
            return File.ReadAllLines(filePath1).Where(i => !string.IsNullOrEmpty(i))
                   .Intersect(File.ReadAllLines(filePath2).Where(i => !string.IsNullOrEmpty(i)));
         }

       return null;
    }

When collecting system information this function may be useful as well. It simply gets all extensions of the files in the directory and counts number of files associated with them.

 public static Dictionary<string, int> ListAndCountTheNumberOfDifferentFileExtensions(string path) 
   {
       return Directory.EnumerateFiles(path)
              .Select(i => new FileInfo(i))
              .GroupBy(i => i.Extension)
              .OrderByDescending(i => i.Count())
              .ToDictionary(i => i.Key, i => i.Count());            
    }

As you can see using LINQ is so easy that allows you to focus more on the business problems and less on coding itself.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Extension methods in C#

Extension methods enable you to add your own methods to already existing system types without deriving from those types. Extension methods are always static but they are called as a instance methods on the extended types. We can extend types like string, double, DateTime etc. as well as LINQ queries which already are extensions of IEnumerable type.

Extended types can be used as a helper methods that you can compile and use in all your projects.

Lets start with the simple string extensions. First example simply checks if string has a value. The second one strips html tags from the string.

    /// <summary>
    /// Determines whether this instance of string is not null or empty.
    /// </summary>
    public static bool HasValue(this string text)
    {
        return !string.IsNullOrEmpty(text);
    }

    /// <summary>
    /// Strips html tags from the string
    /// </summary>
    public static string HtmlStrip(this string input)
    {
        input = Regex.Replace(input, "<style>(.|\n)*?</style>", string.Empty);
        input = Regex.Replace(input, @"<xml>(.|\n)*?</xml>", string.Empty);
        return Regex.Replace(input, @"<(.|\n)*?>", string.Empty);
    }   

Similar is with the double extensions

    /// <summary>
    /// Rounds the value to last 10s
    /// </summary>
    public static double RoundOff(this double i)
    {
        return ((double)Math.Round(i / 10.0)) * 10;
    } 

The sample below is very useful when displaying dates. It displays friendly string with the time left to an event, it extends DateTime type.

 public static string ToDateLeftString(this DateTime input)
    {
        var oSpan = DateTime.Now.Subtract(input);
        var TotalMinutes = oSpan.TotalMinutes;
        var Suffix = " ago";

        if (TotalMinutes < 0.0)
        {
            TotalMinutes = Math.Abs(TotalMinutes);
            Suffix = " from now";
        }

        var aValue = new SortedList<double, Func<string>>();
        aValue.Add(0.75, () => "less than a minute");
        aValue.Add(1.5, () => "about a minute");
        aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
        aValue.Add(90, () => "about an hour");
        aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
        aValue.Add(2880, () => "a day"); // 60 * 48
        aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
        aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
        aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 
        aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
        aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));

        return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;
    } 

The last example extends the IEnumerable type so we are actually adding a new LINQ function.

    /// <summary>
    /// Selects the item with maximum of the specified value.
    /// </summary>
    public static T WithMax<T, TKey>(this IEnumerable<T> list, Func<T, TKey> keySelector)
    {
        return list.OrderByDescending(i => keySelector(i)).FirstOrDefault();
    } 

When testing above methods you will get following results

  static void Main(string[] args)
    {
        //DateTime extended method
        var myDate = DateTime.Now.AddDays(7);
        var dateLeft = myDate.ToDateLeftString(); //result: "6 days from now"

        //System.String extended method
        var myNoHtmlString = "<br><b>test</b>".HtmlStrip(); //result: "test"

        //or 
        var hasStringValue = "test string".HasValue(); //result: true

        //System.Double extension
        double myTo10sRoundedValue = (66.3).RoundOff(); //result: 70

        //Linq extensions
        List<int> list = new List<int>() { 1, 2, 3 }; 
        var max = list.WithMax(i => i); //result: 3
    }

I have included sample project below so you can do some testing yourself.
ExtensionMethods

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

LINQ – filtering data structures

Using Language-Integrated Query (LINQ) has become very common in recent years as it is an easy way to retrieve data from various data structures eg. arrays. The code itself is also very clean and much shorter comparing to non LINQ implementations.

In this article I will show you how easy filtering data can be using LINQ.

Lets create client class first.

public class Client
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public IEnumerable
Addresses { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string Country { get; set; } }

Next we create Client data source with some dummy data

 public IEnumerable ClientDB
{
    get
    {
        var clients = new List();

        #region load dummy data
        clients.Add(new Client()
        {
            ID = 1,
            Name = "Client1",
            Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “UK” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 2, Name = “Client2”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “IT” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); clients.Add(new Client() { ID = 3, Name = “Client3”, Addresses = new List
() { new Address() { Street = “street1”, City = “city1”, Country = “ES” }, new Address() { Street = “street2”, City = “city2”, Country = “US” } } }); #endregion return clients; } }

Now we can filter data from our structure before we can display it on the gridview. We only want to display clients with the UK address.

   
protected void Page_Load(object sender, EventArgs e)
    {
        var clients_With_UK_AddressOnly = ClientDB;

        //lets filter data
        clients_With_UK_AddressOnly = from client in ClientDB
                                        where client.Addresses.Count(a =&gt; a.Country == "UK") &gt; 0
                                        select client;

        //or you can do it shorter using "Any" function
        clients_With_UK_AddressOnly = ClientDB.Where(c =&gt; c.Addresses.Any(a =&gt; a.Country == "UK"));

        GridView1.DataSource = clients_With_UK_AddressOnly;
        GridView1.DataBind();
    }

As you can see when using LINQ, we can do a lot with the data in just one line of code. The code itself if less prone to errors and more elegant.

LINQ-data-filtering

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

ASP.NET View state manager

In this article I will show you how to reduce view state of your asp.net pages by saving it into server session. This solution is perfect for dashboards but is not advisable if you have a lot of users as this can consume a huge amount of server resources.

Basically It can reduce page view state for up to 80%. In my case the total page size was reduced to 200Kb from about 1Mb 🙂

How it works

It saves and loads view state by overriding the page LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium methods. You can configure it to save to other “Persistent Mediums” as well.

    protected override object LoadPageStateFromPersistenceMedium()
    {
        //If server side enabled use it, otherwise use original base class implementation
        if (true == viewStateSvrMgr.GetViewStateSvrMgr().ServerSideEnabled)
        {
            return LoadViewState();
        }
        else
        {
            return base.LoadPageStateFromPersistenceMedium();
        }
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        if (true == viewStateSvrMgr.GetViewStateSvrMgr().ServerSideEnabled)
        {
            SaveViewState(viewState);
        }
        else
        {
            base.SavePageStateToPersistenceMedium(viewState);
        }
    }

When using it you only need to implement from “BasePage” in you pages, the rest is done automatically.

 public partial class _Default : BasePage
 {
 }

You can download complete solution below.
ViewStateHelper

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...

Sql connection helper

Hi everyone,

This is my first post here, so I will start with an very simple and quite useful example of the SQL connection object helper. When using ado.net it basically helps reducing amount of code needed to instantiate connection.

public class Connection
{
    public Connection()
    {

    }

    public static SqlConnection Current
    {
        get
        {
            SqlConnection con = null;
            if (HttpContext.Current.Session["sqlconnection"] == null)
            {
                HttpContext.Current.Session["sqlconnection"] = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ToString());
            }
            con = (SqlConnection)HttpContext.Current.Session["sqlconnection"];
            if (con.State != ConnectionState.Open) { con.Open(); }
            return con;
        }

    }
}

All you need to do is to use Current property of that object to create connection instance or reuse it if already created eg.

    using (SqlCommand cmd = new SqlCommand("getData", Connection.Current))
    {
           cmd.CommandType = CommandType.StoredProcedure;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
               while (reader.Read())
               {
                   //to do get data
               }
            }
     }

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...