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!

Advertisements

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!

 

C# Enums – Handling Long Descriptive String Values – Using Reflection

Consider the following scenario, you have an Enum, for which you have ‘Description’ attributes as shown below

public enum Status
 {
 [Description("Status is Incomplete")]
 Incomplete = 0,
 [Description("Status is Complete")]
 Complete = 1,
 [Description("Status is Reserved")]
 Reserved = 2,
 [Description("Stauts is Confirmed")]
 Confirmed = 3,
 [Description("Stauts is Cancelled")]
 Cancelled = 99
 }

You want to display these values in a drop down, where the text field is same as the Enum’s ‘Description’ text and the drop down value field same as the Enum’s int value.

If you have one Enum with such requirements, you would probably hard code it (I know), but in real world applications, you would have nearly 30 to 40 Enums, used at more than one place in the application, hence hard coding to the drop down is not an option. Also, let suppose we have the project requirement that the drop down should update itself when Enum is updated.

In short, we want a dynamic drop down, whose source is Enum values and if we add/remove values to the Enum, the drop down will update it self.

How to go about this ?

Lets use .NET extension and reflection and try to achieve this

The following code will use return the ‘Description Attribute’ of any Type of source using reflection

public static string GetDescriptionAttr(this T source)
 {
 FieldInfo fi = source.GetType().GetField(source.ToString());

 if (fi == null)
 return string.Empty;

 var attribute = (DescriptionAttribute) fi.GetCustomAttributes(typeof (DescriptionAttribute), false)[0];

 if (attribute == null)
 return string.Empty;

 return attribute.Description;
 }

Once this code is in place, we could write a helper function which will convert Enums to ListItemCollection where ‘Description’ attribute is used as text and Enum’s int value is used as ‘value’ field for the drop down option.

 public static ListItemCollection EnumToList(Type enumType)
 {
 var list = new ListItemCollection();

 foreach (var type in Enum.GetValues(enumType))
 {
   list.Add(new ListItem(String.Format(" {0}", type.GetDescriptionAttr()), ((int)type).ToString()));
 }

 return list;
 } 

And finally, in the code behind, you just need to pass in the Enum value to this helper method, which will use reflection and return the dynamic list for the drop down

MyDropDown.DataSource = EnumToList(typeof(Status));
MyDropDown.DataBind();

Thanks !

C# Enums – Handling NULL Values – Some Tips

 

As a  C# developer, we work with Enums in almost every project and use them in variety of ways.

The Enum values could be defined in the database, or they could be part of an API.  However, once we have the string value, we want to use them as Enum and perform our tasks.

Problem :

What to do if the string value is not equivalent to one of the pre-defined Enum Values

Approach :

To solve these problems, .NET framework provides methods

In .NET 4 and above, you can use Enum.TryParse<T> generic method to convert a string into an Enum

If the parsed value is not equivalent to one of the Enum values, you could return a null and then check for null every where in the code before using this Enum.

Consider the following Enum

 

 /// <summary>
 /// Direction Enum
 /// </summary>
 public enum Direction
 {
 /// <summary>
 /// NORTH direction
 /// </summary>
 NORTH = 1,
 /// <summary>
 /// SOUTH Direction
 /// </summary>
 SOUTH = 2,
 /// <summary>
 /// EAST Direction
 /// </summary>
 EAST = 3,
 /// <summary>
 /// WEST Direciton
 /// </summary>
 WEST = 4
 
 }

This is a very simple Direction Enum and expected values are 4 known directions.

Consider we are building a console application and asking user to input one the direction and then trying to convert it into one of our Enum with following function

 

 /// Parse the input  Enum value
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private static Direction ParseInput(string input)
 {
 if (String.IsNullOrEmpty(input))
 return null;

 if (String.IsNullOrWhiteSpace(input))
 return null;

 Direction direction;
 if (Enum.TryParse<Direction>(input.ToUpper(), out direction))
 {
 return direction;
 }

return null;

 }

 

This is absolutely fine piece of code, which will return you correct Enum value otherwise it will return null.

But whenever this function will be called in rest of the project, you have to check for the ‘null’ value exception all the time

Something like

var direction = ParseInput(Console.ReadLine())

if (direction != null)
{
  //then your logic  
}

 

How about adding an extra Enum to your class as NONE and returning it instead of the ‘null’ value?

 

Your updated Enum would be

 

 /// <summary>
 /// Direction Enum
 /// </summary>
 public enum Direction
 {
 /// <summary>
 /// NORTH direction
 /// </summary>
 NORTH = 1,
 /// <summary>
 /// SOUTH Direction
 /// </summary>
 SOUTH = 2,
 /// <summary>
 /// EAST Direction
 /// </summary>
 EAST = 3,
 /// <summary>
 /// WEST Direciton
 /// </summary>
 WEST = 4,
 /// <summary>
 /// NONE direction
 /// </summary>
 NONE = 99

 
 }

 

And your updated function would be

/// <summary>
 /// Parse the input  Enum value
 /// </summary>
 /// <param name="input"></param>
 /// <returns></returns>
 private static Direction ParseInput(string input)
 {
 if (String.IsNullOrEmpty(input))
 return Direction.NONE;

 if (String.IsNullOrWhiteSpace(input))
 return Direction.NONE;

 Direction direction;
 if (Enum.TryParse<Direction>(input.ToUpper(), out direction))
 {
 return direction;
 }

return Direction.NONE;

 }


This approach would solve your the problem of checking for ‘null’ value all over the project and you can simply use a switch() statement every time this function is called.

Thanks !

Sitecore : Adding a Twitter Pod using LINQ To Twitter

In almost all the projects I have done in past year or so, a common requirement among the clients have been that they want the ability to add Twitter Pods on pages and also have the ability to change the account name based upon their campaign or department.

For the purpose of the post, I will be using Sitecore CMS and LINQ To Twitter library to show how simple it is to create a Twitter Pod/module.

Let suppose we only want to display top  tweet from an account/twitter handle, which is define in the Sitecore CMS

Steps:

1. Create a data template property in the CMS as ‘Twitter Account Name’ or whatever you like

2. Create a standard .NET User Control and lets call it ‘TwitterPod.ascx’

3. Reference LINQ to Twitter library in your project (download it from here http://linqtotwitter.codeplex.com/ and also read its documentation)

4. As per Twitter API 2.0 you need to get Consumer Key, Consumer Secret, Access Token, Access Token Secret values from http://dev.twitter.com for any applications that you are creating. Log-in there and follow the steps to get these values.

5. Add these Twitter API 2.0  values to web.config

6. Let suppose this is your .ascx control markup

<div><asp:HyperLink ID="HyperLinkFollowAccount" runat="server" Target="_blank"></asp:HyperLink></div>

<div class="twitter">
<asp:HyperLink ID="HyperLinkFirstTweet" runat="server">
<p><asp:Literal ID="LiteralFirstTweet" runat="server"></asp:Literal>
<p>Posted <asp:Literal ID="LiteralFirstPostedTime" runat="server"></asp:Literal></p>
</asp:HyperLink>
</div>

7. Add these ‘static strings’ to your User Control class

private static string ConsumerSecret

{

get { return WebConfigurationManager.AppSettings["ConsumerSecret"]; }

}

private static string ConsumerKey

{

get { return WebConfigurationManager.AppSettings["ConsumerKey"]; }

}

private static string AccessToken

{

get { return WebConfigurationManager.AppSettings["AccessToken"]; }

}

private static string AccessTokenSecret

{

get { return WebConfigurationManager.AppSettings["AccessTokenSecret"]; }

}

8.  Twitter API 2.0 requires OAuth Authentication, to get that add this to Page_Load of your User Control

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = ConsumerKey,
ConsumerSecret = ConsumerSecret,
OAuthToken = AccessToken,
AccessToken = AccessTokenSecret
}
};

using (var twitterCtx = new TwitterContext(auth))
{
LoadTwitterFeeds(twitterCtx);
}
}
catch(Exception ex)
{
Sitecore.Diagnostics.Log.Error(ex.Message, this);
}
}
}

9.  LoadTwitterFeeds(twitterCtx) is your custom function where you can add your logic of getting tweets via Twitter API 2.0 and displaying them

10.

private void LoadTwitterFeeds(TwitterContext service)
{
try
{

string accountName = Sitecore.Context.Item["Twitter Account Name"] as string;

var tweets = (from tweet in service.Status

where tweet.ScreenName == accountName &&
tweet.Count == 1 &&
tweet.ExcludeReplies == true &&
tweet.IncludeRetweets == true &&
tweet.Type == StatusType.User
select tweet).FirstOrDefault();

if (tweets != null)
{

HyperLinkFollowAccount.NavigateUrl = "http://twitter.com/" + accountName.Replace("@", "");
HyperLinkFollowAccount.Text = "Follow " + accountName + " on Twitter";

LiteralFirstTweet.Text = tweets.Text;
LiteralFirstPostedTime.Text = tweets.CreatedAt.ToString();
HyperLinkFirstTweet.NavigateUrl = "https://twitter.com/" + tweets.User.Identifier.ScreenName + "/status/" + tweets.StatusID.ToString();}

catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error(ex.Message, this);
}
}

11. Create a Sublayout for this User Control and add it to the Sitecore Layouts.

Note: You can also pass in the ‘Twitter Account Name’ as a parameter of the SubLayout
Note++: Umbraco and Episerver CMS can also use the same code with different CMS based API.

Thanks

Sitecore : Getting image field in code behind

This is just a quick post to show how to get image URL via code behind.

This is mostly useful when you are binding children items to a repeater or returning image URL in a JSON webservice

public static string GetImageURL(Item currentItem)
{
          string imageURL = string.Empty;
          Sitecore.Data.Fields.ImageField imageField = currentItem.Fields["Image"];
          if (imageField != null && imageField.MediaItem != null)
          {
            Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
            imageURL = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
          }
return imageURL;
}

Cheers

Sitecore vs Umbraco – A developer’s view

One Friday afternoon, I was sitting at my desk and fixing bugs (as usual), a member of sales team came up to me and said

“Hey Naveed, we have this interesting new client and they are not sure about which CMS to go for, they have finalised Sitecore and Umbraco as the last two, can you help”

I replied: “Sure, why not, what are their business requirements ?”

Sales person: “They are medium to large size organisation and have usual requirements like news, events, forums, blogs, video content etc, they want a simple to use CMS with multiple authors and security levels”
I replied: “Ok, Sitecore and Umbraco are both equally powerful in content generation and management, they both are based on .NET stack (.NET,C#,SQL) and both are highly customisable, so far they both can be their potential CMS, do you have more specific requirements ?”

Sales person: “Yes, in future, they would like to integrate with Sharepoint and their back-end CRM system”

I replied :”Sitecore comes with a sharepoint connector out-of-box whereas for Umbraco we have to custom build one. As long as their back end CRM exposes API, we can integrate any of the CMS system with their back end, this will be custom build in both cases, do you have any other requirements ?”

Sales person: “It is not a requirement but in their wish list to have personalised content for different regions or profile history”

I replied: “Sitecore comes with Customer Engagement Platform (CEP) and Online Marketing Suite (OMS) which can make their life easy in future, however, Umbraco lacks these customised modules. So it looks like Sitecore can be their potential candidate for CMS, also do you have any idea about their budget for the website?”

Sales person: “Yes, it’s a five figure sum, not sure what exactly their budget is”

I replied: “If they are tight on budget and can compromise on add-ons then Umbraco would be good to start off with but will have high maintenance cost if they go down the route implementing customised modules. However, paying for Sitecore licenses up front will give them added benefit to use some of the modules out of the box and will have low maintenance cost, I guess best would be to give them a demo of both CMS systems to the client and let them make informed decision”

Sales person: “Sounds like a plan, ok I will let them know, cheers”

Conclusion:

No CMS is right or wrong for your business out of the box, you have evaluate them against your own business requirements for the website. Open source may be cheaper to start off with but will have maintenance costs down the line.

Disclaimer: I have worked with both CMS systems and hold them up in same respect for what they do, I am not a sales person or work for either of the CMS systems, this is just my opinion as a third party developer