C# – Limit Paragraph Length using Simple Extension Method

Happy New Year 2016 !

In most of the web applications, you will encounter a scenario where you have to display the summary of the page in limited amount of space. For example, on a section level page, sometimes you are required to display sub section summary information but due to design constraints, you can only display 80 characters.

The .NET framework provides .Substring() method to limit the string length and generate a new sub-string but this method is not clever enough to distinguish between words and empty spaces in a long paragraph and can result in a sub-string where a word has been truncated in the middle of being displayed, giving bad output to the end user.  How can we solve this ?

Here is a simple string extension method that will nicely truncate the paragraph and it will also add “…” at the end of the returned string value.

Step 1 : Add this extension method class in your project

namespace StringExtensions.LimitSentenceLength
{
    public static class StringExtensions
    {
        public static string LimitSentenceLength(this string paragraph, int maximumLenght)
        {
            //null check
            if (paragraph == null) return null;

            //less than maximum length, return as it is
            if (paragraph.Length <= maximumLenght) return paragraph; 
            //split the paragraph into indvidual words 
            string[] words = paragraph.Split(' '); 
            //initialize return variable 
            string paragraphToReturn = string.Empty; 
            //construct the return word 
            foreach (string word in words) 
           { 
            //check if adding 3 to current length and next word is more than maximum length. 
            if ((paragraphToReturn.Length + word.Length + 3) > maximumLenght)
            {
              //append "..."
              paragraphToReturn = paragraphToReturn.Trim() + "...";
              //exit foreach loop
              break;
             }
             //add next word and continue
             paragraphToReturn += word + " ";
            }
           return paragraphToReturn;
        }
    }
}

Step 2 : From your main application, you can call this method as following :

using System;

namespace StringExtensions.LimitSentenceLength
{
    class Program
    {
        private static string Paragraph => "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

        static void Main(string[] args)
        {
            Console.WriteLine(Paragraph.LimitSentenceLength(50));
            //Lorem ipsum dolor sit amet, consectetur...
            Console.WriteLine(Paragraph.LimitSentenceLength(100));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut...
            Console.WriteLine(Paragraph.LimitSentenceLength(150));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam,...
            Console.WriteLine(Paragraph.LimitSentenceLength(200));
            //Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut...
        }
   
    }
}

How simple is that !!!

Sample code is available on GitHub

Naveed’s Blog 2015 in review

The WordPress.com stats helper monkeys prepared a 2015 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 22,000 times in 2015. If it were a concert at Sydney Opera House, it would take about 8 sold-out performances for that many people to see it.

Click here to see the complete report.

C# – Random ordering of IEnumerable using Extensions

This is just a quick post about random ordering of IEnumerable types using C# extension. For example you have a IEnumerable of type ‘Employee’ object and you want to randomly pick 7 employee objects, how would you do that? This blog post will create a simple extension method for IEnumerable and show how to use it.

Step 1 : Create an extension class for IEnumerable as below :

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

namespace Sample
{
    public static class EnumerableExtentions
    {
       public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
        {
            var range= new Random();
            return source.Randomize(range);
        }

        private static IEnumerable<T> Randomize<T>(this IEnumerable<T> source, Random range)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (range== null) throw new ArgumentNullException("range");

            return source.RandomizeAlgorithm(range);
        }

        private static IEnumerable<T> RandomizeAlgorithm<T>(this IEnumerable<T> source, Random range)
        {
            var temp = source.ToList();

            for (int i = 0; i < temp.Count; i++)
            {
                int j = range.Next(i, temp.Count);
                yield return temp[j];

                temp[j] = temp[i];
            }
        }
    }
}

Step 2 : Use it within your main code as below :

           //get all employees
            var employees = Employee.GetAllEmployee();
            //print in sequence
            PrintEmployees(employees);
            //randomize using extension
            var randomEmployees = Employee.GetAllEmployee().Randomize();
            //print them again
            Console.WriteLine("**************");
            PrintEmployees(randomEmployees);

Job Done!

Sample code is available on GitHub

Note : I am using Fisher–Yates shuffle  algorithm for randomizing the collection.

Getting started with MongoDB 3.0 using some new features of C# 6.0

Recently, I had to work on an application which used MongoDB as a back-end database. As it was my first MongoDB based project using C#, I went through a learning curve and thought it will be a good idea to do a step-by-step guide. So, if you are new to MongoDB, here is a quick post to get you up and running

Step 1: Download and install VS 2015 Community edition, it’s free for personal use with registered email address!

VS2015_Install

Step 2: Download MongoDB and install it on your local machine.

MongoDB_Install

Step 2.1 Create a data directory or empty folder at C:\data\db (this is the default location for MongoDB to store files, but can be changed)

Step 2.2 Open CMD with administrative privileges and navigate to MongoDB install folder and start mongod.exe program. In my case the path was C:\program files\mongodb\server\3.0\bin and then the command mongod.exe

MongoDB_Starting

Step 3: Download RoboMongo which is an open-source GUI for MongoDB management.

RoboMongo_Install

Step 3.1 Assuming MongoDB is up and running, create a new “localhost” connection and test it.

Step 3.2 Click on View > Explorer and you will see list of localhost DBs.

RoboMongo_Connection

Step 4: Open VS 2015 and create a new Console Application (for production purposes, you might need a class library, but for demo I am using console application)

MongoDBTestApp

Step 5: Right click on References > NuGet Packages and install ‘Official .NET Driver for MongoDB’

MongoDB.Driver.NuGet

Step 6: Create your collection class, for purpose of this blog, I have created a Customer class.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;

namespace MongoDBTestApp
{
    public class Customer
    {
        //required field to perform read/write opertions on Bson or Binary Json
        [BsonElement("Id")]
        public ObjectId Id { get; set; }

        //C# 6.0 property initializers
        public string FirstName { get; set; } = "John";
        public string LastName { get; set; } = "Doe";
        public DateTime Timestamp  { get; set; } = DateTime.UtcNow;
    }
}

Step 7:  Insert objects as collection in Mongo DB

using MongoDB.Driver;
using System.Threading.Tasks;

namespace MongoDBTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //creates a MongoDB client from conn string
            var client = new MongoClient("mongodb://localhost");
            //gets the database within client, if it doesn't exists, creates it
            var database = client.GetDatabase("customer");
            //gets the collection from the database,if it doesn't exists, creates it
            var collection = database.GetCollection("customers");
            //insert into database
            Task.WaitAll(InsertCustomer(collection));
            
        }

        static async Task InsertCustomer(IMongoCollection collection)
        {
            await collection.InsertOneAsync(new Customer());
        }
        
    }
}

MongoDB_InsertCustomer

Step 8: Find your object from Mongo DB and display it

 static async Task FindCustomer(IMongoCollection collection)
        {
            //creates a filter to find Bson Document
            var filter = Builders.Filter.Eq(c => c.FirstName, "John");
            //runs the query to find it
            var query = await collection.Find(filter).ToListAsync();
            //gets the customer
            var customer = query.FirstOrDefault();
            //displays the customer using new C#6 string formatters
            Console.WriteLine($"Customer {customer.FirstName} {customer.LastName} is found!");

        }

MongoDB_FindCustomer

What you have now is a fully functional MongoDB application where you can store records and retrieve records, how easy was that!

All code is available from GitHub.

Thanks

Naveed.

C# – Read/Write CSV files using FileHelpers

This is 2015, and we shouldn’t be working with CSV files any more, but reality is, they are the most commonly used file exchange method around.

As a C# developer, we can make use of standard String and Array classes and we can read/write CSV files. However, there is a maintenance issue, imagine you have a CSV file with 15+ columns, and now you have been asked to update the code with additional columns.  Updating index based columns with additional column is a tedious and error prone task.

There is a better way, use FileHelpers. This is a free and Open Source C# library to handle CSV files related operations.

This can be installed as NuGet package within the project.

I am going to assume that the CSV file has got only 2 columns as following :

1.Name

2.Description

And the description column could have double quotes ” and a comma can be included within the double quotes.

Step 1 : Create a simple C# class for the CSV file and add field attributes using FileHelpers as following:

/* ProductHelper.cs */

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

namespace MyProject
{
    [DelimitedRecord(",")]
    [IgnoreEmptyLines()]
    [IgnoreFirst()]
    public class MyProduct
    {
        //Name
        public string Name{ get; set; }
	//Description, this attribute will handle the double quotes issue
        [FieldQuoted('"', QuoteMode.OptionalForBoth)]
        public string Description{ get; set; }
        
    }
}

Step 2 : The Second step would be to read the flat CSV file into this object.

        private void ReadCSVFile(string fileName)
        {
            try
            {   
                //file location, better to get it from configuration
                 string fileName = "C:\\temp\\MyProducts.csv";
                //create a CSV engine using FileHelpers for your CSV file
                var engine = new FileHelperEngine(typeof(MyProduct));
                //read the CSV file into your object Arrary
                var products = (MyProduct[])engine.ReadFile(fileName);

                if (products.Any())
                {
                   //process your records as per your requirements
                   foreach (var product in products)
                   {
                        //add it to your database, filter them etc
                        string name = product.Name
                        string description = product.Description
                        
                   }
                }
               
                
            }
            catch (Exception ex)
            {
                LogException(ex)
            }
        }

And that’s it. In case you have to add more columns or remove any column, all you have to is to update the ‘MyProduct.cs’ class file and update the associated strongly typed code.

Now lets assume the opposite, that you have a some sort of data in the database or CMS or external data source and you want to write that into CSV file.

Using the same ‘MyProduct.cs’ class above, the write method will be as following:

        private void WriteCSVFile(List<SomeDataSource> dataSource)
        {
       
            try
            {
                //filehelper object
                FileHelperEngine engine = new FileHelperEngine(typeof(MyProdcuts));
                //csv object
                List<MyProduct> csv = new List<MyProduct>();
                //convert any datasource to csv based object
                foreach (var item in dataSource)
                {
                 
                 MyProduct temp = new MyProduct();
                 temp.Name = item.Name;
                 temp.Description = item.Description      
                 csv.Add(temp);
                       
                }
                //give file a name and header text
                string filename = "MyProducts.csv";
                engine.HeaderText = "Name,Description";
                //save file locally
                engine.WriteFile(Server.MapPath(filename),csv);
                
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }

Whoooa! that’s it.

Thanks!

C# – Simple FTP Service

Here is a quick snippet for FTP services using standard C#/.NET libraries.

The task is to download a file from a remote FTP server using standard C#/.NET libraries.

I assume that you have the FTP server details (Host, Username, Password).

The code is pretty straight forward, I have given comments where required.

/* FTPService.cs */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MyProject
{
    public class FTPService
    {
        //request object
        private FtpWebRequest ftpRequest = null;
        //response object
        private FtpWebResponse ftpResponse = null;
        //stream object to read
        private Stream ftpStream = null;
        
        //Host address like ftp://something.net/
        public string Host { get; set; }
        //ftp username
        public string Username { get; set; }
        //ftp password
        public string Password { get; set; }
        //local directory where the file will be downloaded.
        public string LocaDirectory { get; set; }

       

       
        public void GetFile(string fileName)
        {
            try
            {
		//create FTP request
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", Host, fileName));
		//add authentication details                
                ftpRequest.Credentials = new NetworkCredential(Username, Password);
                //set ftp options
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                // Get response from ftp server
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = ftpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(ftpStream);
                //download the file and copy it to local directory
                using (var file = File.Create(LocaDirectory + fileName))
                {
                    ftpStream.CopyTo(file);
                }


            }
            catch (Exception ex)
            {
            	LogError(ex);
            }

            finally
            {
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            
        }

        

       
    }
}

Then you can call this service in your project using the following snippet

        
        private static void DownlaodFTPFile()
        {
            FTPService service = new FTPService();

            service.Host = ConfigurationManager.AppSettings["Host"];
            service.Username = ConfigurationManager.AppSettings["Username"];
            service.Password = ConfigurationManager.AppSettings["Password"];
            service.LocaDirectory = ConfigurationManager.AppSettings["LocalDirectory"];

            string fileName = "DownloadFile.txt";

            service.GetFile(fileName);
        }

Always best practise to use web.config/app.config for hard-coded details, it takes time but it in long run it eventually pays off

Thanks!

C# – Simple Email Service

This is just a quick snippet for sending emails using standard .NET/C# components. Here, I assume that FTP server is already configured or you have the details.

/* EmailService.cs */
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySampleProject
{
    public class EmailService
    {
        public void SendEmail(string body)
        {

            System.Net.Mail.MailMessage oMailMsg = new System.Net.Mail.MailMessage();
            oMailMsg.To.Add(ConfigurationManager.AppSettings["ToEmailAddress"]);
            oMailMsg.Subject = ConfigurationManager.AppSettings["Subject"];

            oMailMsg.IsBodyHtml = true;
            oMailMsg.Body = body;

            System.Net.Mail.SmtpClient oSMTPClient = new System.Net.Mail.SmtpClient();
            oSMTPClient.Send(oMailMsg);
            

        }
    }
}

The standard SmtpClient will look for smtp settings in the web.config/app.config.

<system.net>
 <mailSettings>
 <smtp from="no-reply@mydomain.com">
 <network host="localhost" password="" userName=""/>
 </smtp>
 </mailSettings>
 </system.net>

Also, it is best practise to add ‘To’ email address and ‘Subject’ in config settings, for deploying code in different enviornments (QA / Staging / Production)

<appSettings>
 <add key="ToEmailAddress" value="me@mydomain.com"/>

 <add key="Subject" value="Some one has sent an email using website...Amazaing!"/>
 </appSettings>

 

Cheers!