Saturday, May 18, 2013

When to comment your code

The other day I was browsing through some of the organizations I follow on twitter when I stumbled across this post from Ardalis.com.  This is a great article for programmers just getting starting as well as season professionals.  It gives you a great insight about when its the proper time to add comments to your code.  I think there are times that programmers in general struggle with whether or not it's the proper time to comment code.  I believe the main reason maybe that most of us think we write clean code or our naming convention is second to none.  Personally, I try to only comment in complex situations where I absolutely need to describe a function or procedure to perhaps give myself or another programmer an idea so he/she knows what's going on.  The thing to remember is that, what makes since to you may not make since to the programmer that follows behind you.  Also, know one likes coming in on a project where every other line is commented or there are giant paragraphs that start with some thing like, "// Dear maintainer:".  On top of that, it's also extremely irritating at lease to me when there's code that was added three plus years old and the code itself is actually not in the project anymore.  Anyway, below is the link to the article, hope it helps you or anyone else needing some clarification or understanding when and/or where not to add comments into an application.  Happy coding!!!  Article Link

Friday, May 10, 2013

Locating IP Original Origin C#

I recently was trying to write a function that would allow me to trace an IP back to it's origin or at least return the city and state.  I didn't want to use Google API or any other type of fancy API.  After a few hours of R.N.D., I found a link to a generic site that's soul purpose is to grab your current location and return XML.  As I started to write my function to parse the XML.  I realized my typical way of parsing XML was having issues because of the way this sites XML tree was assembled.  After giving it some thought, I came to the conclusion that I needed to add a namespace manager to my XML document which is called XmlNamespaceManager.  In the example below you'll see my simple approach and how I was able to resolve this issue.  Hope this helps anyone having similar issues especially when it comes to consuming XML.  Happy Coding!!!
 private const string _hostIPUrl = "http://api.hostip.info/";

 public string GetLocation() 
  {
   WebClient client = new WebClient();
   Uri uri = new Uri(String.Format("{0}", _hostIPUrl));
   List location = new List();

   string xmlString = client.DownloadString(uri).ToString();

   XmlDocument doc = new XmlDocument();

   doc.LoadXml(xmlString);

   XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
   manager.AddNamespace("gml", "http://www.opengis.net/gml");

   XmlNode cityLocation = doc.SelectSingleNode("//HostipLookupResultSet/" +
   "gml:featureMember/Hostip/gml:name/text()", manager);

   return cityLocation.Value;
  }

Wednesday, May 8, 2013

Simple Server File Sharing

In the past I worked for a company that had a file server that was running on IIS 6 to store all of their documentation to insure all company documents where being saved to the same location instead of perhaps to someones local machine.  They wanted me to setup individual folders for everyone in the company on the server so they could upload, share and track all documents.  In the example below, I've listed out the basic steps to setup file sharing on your server and map it to your local drive.  Happy Coding!!!

Server Configuration
1. Create folder somewhere on your local directory (C:/New Directory).
2. Right click on new folder and select Properties.
3. Select the Sharing tab.
4. Select the Share this folder radio button.
5. Next, select the Security tab.
6. Select Users role type.
7. Give Users Read and Write permissions or give them Full Control.
8. Select OK.
9. Create virtual directory in IIS 6 (Web Sites > www Web Site > New Directory).
10. Set local path.
11. Check (Read, Write, and Directory browsing) under Local path.
12. Select OK

Local Server Share Configuration
1. Open Start window.
2. Select Computer.
3. If you’re running on Windows Vista, select Map network drive above your local drives. Else locate your Map network drive button.
4. Select which drive you want to map to.
5. Insert \\Server Address\DavWWWRoot\share into the Folder text box.
6. Finally, you'll more then likely need to already connected to VPN or connected to your company network to map to your new shared folder.

Developing a Custom VMConnect Application

I was looking around at some .NET forums and happened to stumble across this tutorial on how to build a custom VM with C#.  It's differently a must read if your looking to either use the code in the tutorial or creating one from scratch.  You'll find out it's must easier then you expect.  Have Fun!!

Developing a Custom VMConnect Application 

Tuesday, May 7, 2013

.NET 4.0 Routing

One of the cool features in .NET 4.0 is the RouteCollection object. If your currently using MVC then this is already built-in.  When I first tried to implement this into one of my sites, the main issue I ran across was moving it to the production server.  I made sure my site was running on .NET 4.0 and added "System.Web.Routing.dll" to my bin folder but the routing still wasn't working. As you'll see in my snippet, after creating all my routes I had to create an additional one with "Route.MapPageRoute" for it to work on production.  It seemed as if it needed a starting anchor for everything to work correctly even though it was working fine on my local machine.  I probably could have resolved this issue much easier in IIS if my server was dedicated, but that wasn't the case.  There are probably better ways to do this, but this worked for me at the time.  Anyway, hope this helps anyone having the same issues. Happy Coding!!!

public static void RegisteredRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Home", "", "~/Default.aspx");   
        routes.Add(new Route("Contact", new ContactRouteHandler()));
    }

WPF Button Menu

I'm currently working on a WPF application that needed a button that would allow users to click and display menu options.  By default when you've got a menu associated with your button you need to right click on the button to display your menu.

By setting "ContextMenuService.IsEnabled=False" in your button and adding the code below to your button click this should resolve that issue.  In the example below you'll see how to setup your button to display a menu when clicked.  Have Fun ☺
< Button x:Name="btnMenu" Content="Menu" HorizontalAlignment="Left" Height="30" ContextMenuService.IsEnabled="False"  Width="100" Click="btnMenu_Click">
 < Button.ContextMenu>
  < ContextMenu>
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < MenuItem Header="Menu 1" />
     < Separator />
     < MenuItem Header="Second Menu">
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < MenuItem Header="Menu 2" />
     < Separator />
     < MenuItem Header="Third Menu" />
     < / MenuItem>
  < / ContextMenu>
 < / Button.ContextMenu>
< / Button>
private void btnMenu_Click(object sender, RoutedEventArgs e)
  {
    (sender as Button).ContextMenu.IsEnabled = true;
    (sender as Button).ContextMenu.PlacementTarget = (sender as Button);
    (sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
    (sender as Button).ContextMenu.IsOpen = true;
  }

Sunday, May 5, 2013

Async Emails C#

In the past I've had to send multiple emails at a time with a list that ranged anywhere from 1-500.  Ideally when it comes to mass emails, you should setup a dedicated IP to prevent your site from possibly becoming blacklisted.  That said, if your needing to send multiple emails what better way to accomplish that task and not slow down your application then to do it asynchronously.  I hope this example helps to get you started.  Have Fun!!!
protected void Page_Load(object sender, EventArgs e)
        {
            MailMessage msg = new MailMessage();
            MailAddress from = new MailAddress("[YOUR EMAIL]");
            msg.Subject = "[SUBJECT]";
            msg.Body = "[BODY]";

            List emailList = new List();

            emailList.Add("email@email1.com");
            emailList.Add("email@email2.com");

            foreach (string str in emailList)
            {
                SendEmail(msg, str, from, true);
            }

        }

        public static void SendEmail(MailMessage m, string to, MailAddress from, Boolean Async)
        {
            SmtpClient smtpClient = null;
            NetworkCredential SMTPUserInfo = new NetworkCredential("[YOUR EMAIL]", "[YOUR PASSWORD]");

            smtpClient = new SmtpClient("[SMTP SERVER]", 587);
            smtpClient.Credentials = SMTPUserInfo;
            smtpClient.EnableSsl = true;

            m.To.Clear();
            m.To.Add(to);
            m.From = from;
            if (Async)
            {
                SendEmailDelegate sd = new SendEmailDelegate(smtpClient.Send);
                AsyncCallback cb = new AsyncCallback(SendEmailResponse);
                sd.BeginInvoke(m, cb, sd);
            }
            else
            {
                smtpClient.Send(m);
            }
        }

        private delegate void SendEmailDelegate(System.Net.Mail.MailMessage m);

        private static void SendEmailResponse(IAsyncResult ar)
        {
            SendEmailDelegate sd = (SendEmailDelegate)(ar.AsyncState);

            sd.EndInvoke(ar);
        }

Saturday, May 4, 2013

Email messages with embedded images

In the past I've had multiple projects where I've needed to create email templates that contained images for email blast and etc..  One of the biggest issues I've come across is that most email clients don't allow you to display images.  The reasoning behind this is because images you include are being downloaded from the web which could propose security risk to either the client and or the one receiving the email.  In this example you'll see the convention to access a linked resource is "cid:name" of the linked resource, which is the value of IMG tag SRC attribute.  There's one thing to consider when doing it this way.  The function will increase the size of the email, because the images will be embedded.  Have fun!!
public void SendImbeddedEmail()
{
var logo = new LinkedResource(@"C:\logo.jpg");
string from = "[EMAIL ADDRESS]";
string to = "[EMAIL ADDRESS]";
var subjust = "[EMAIL SUBJECT LINE]";
logo.ContentId = Guid.NewGuid().ToString();
var body = string.Format(@"< html >< body >< h1 >
Image< /h1 >
< img cid:="" src="" />< /body >< /html >", logo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(logo);

SmtpClient client = new SmtpClient("[SMTP SERVER]");
using (var message = new MailMessage(from, to)
 {
   Subject = subjust,
   Body = body,
   IsBodyHtml = true
 })
    {
      message.AlternateViews.Add(view);
      client.Send(message);
    }
}

Removing blue highlight from folders on desktop

Hello- If you've managed to accidently make all your folders background on your desktop blue and have tried everything to remove the blue highlight from your desktop folders and haven't had any luck, then give this a try. Below is what helped me.
  1. Right click on your desktop
  2. Click on properties
  3. Click on Desktop
  4. Click on Customize Desktop
  5. Click on Web 
  6. Ensure no web pages are checked
  7. Check Lock Desktop Items
  8. Click OK

Google Weather

This weather function can be created a few different ways. I created labels and plugged in the values. You can also, put this into a method or place it in your Page_Load. Have Fun!!
HttpWebRequest  theGoogleRequest  = null;   
HttpWebResponse theGoogleResponse = null;   
XmlDocument     theGoogleXMLdoc   = null;   
StringBuilder   theStringBuilder  = new StringBuilder();   

try{   
theGoogleRequest  = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api?weather="
+ "Lenexa, KS");   
  
theGoogleResponse = (HttpWebResponse)theGoogleRequest.GetResponse();
theGoogleXMLdoc   = new XmlDocument();
  
theGoogleXMLdoc.Load(theGoogleResponse.GetResponseStream());
  
XmlNode root = theGoogleXMLdoc.DocumentElement;
XmlNodeList nodeList  = root.SelectNodes("weather/current_conditions");
XmlNodeList nodeList1 = root.SelectNodes("weather/forecast_conditions");
  
current_temp.Text = nodeList.Item(0).SelectSingleNode("temp_f").Attributes["data"].InnerText;   
hi_temp.Text = nodeList1.Item(0).SelectSingleNode("high").Attributes["data"].InnerText;   
lo_temp.Text = nodeList1.Item(0).SelectSingleNode("low").Attributes["data"].InnerText;   
condition_icon.Text = "< img src=" + "'" + "http://google.com" +
nodeList.Item(0).SelectSingleNode("icon").Attributes["data"].InnerText + "'" + "  alt='' /> ";
condition.Text = nodeList.Item(0).SelectSingleNode("condition").Attributes["data"].InnerText;   
  
string theWindSpeed = nodeList.Item(0).SelectSingleNode("wind_condition").Attributes["data"].InnerXml;   
  
Match theMatch = Regex.Match(theWindSpeed, "(?:\\d+)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (theMatch.Success)
{   
 condition_wind.Text = theMatch.Value;   
}               
}   
catch (System.Exception ex)   
{   
 ErrorHelper.LogError("weather:Page_Load", ex);   
}   
finally   
{   
 theGoogleResponse.Close();   
}  

Insert CSV file into generate DB table

Hello !!- This function at the time was one of the hardest one's I ever created because I was given a two hour window for development and testing.  So if that's what your currently facing this function will do the job.  Basically the way it works is, first we create a data table and then read the csv file into it. Next create a db table, this can be the name of the file that's been uploaded, or whatever you want to call it. Next, we need to loop through the data table until it reaches 0.  While the loop is running, it's going to create headers as well rows in the data table.  Finally, when it starts to create the new db table. It will go though the data table, grab the row headers and set them to the db table headers then create a new row for each row in the data table.  Now, I've created this function in the Page_Load event, but this can be broken down into separate methods and improve this function to handle more conditions and situations you may be having.  Hopefully this will get you on the right track and hopefully I was able to break this concept down enough to easily understand.  I've included a link to my function. Good Luck :-)

private string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
        DataTable dt = new DataTable();
        string line = null;
        int i = 0;
     
        using (StreamReader sr = File.OpenText(@"c:\myfile.csv"))
        {
            while ((line = sr.ReadLine()) != null)
            {
                string[] data = line.Split(',');
                if (data.Length > 0)
                {
                    if (i == 0)
                    {
                        foreach (var item in data)
                        {
                            dt.Columns.Add(new DataColumn(item)); 
                        }
                        i++;
                    }
                    DataRow row = dt.NewRow();
                    row.ItemArray = data;
                    dt.Rows.Add(row);
                }
            }
        }
        CreateDatabaseTable(dt, "ImportedData3");

        var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        var bulk = new SqlBulkCopy(connection, SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls);
        using (bulk)
        {
            bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(0, 0));
            bulk.BatchSize = 25;
            bulk.DestinationTableName = "ImportedData3";
            bulk.WriteToServer(dt);
        }
        DataHelper.DeleteTableRow("ImportedData3");
    }
    private void CreateDatabaseTable(DataTable dt, string tableName)
    {
        string sqlQuery = string.Empty;
        string sqlDBType = string.Empty;
        string dataType = string.Empty;
        int maxLength = 0;
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat(string.Format("CREATE TABLE {0} (", tableName));
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            dataType = dt.Columns[i].DataType.ToString();
            if (dataType == "System.Int32")
            {
                sqlDBType = "int";
            }
            else if (dataType == "System.String")
            {
                sqlDBType = "nvarchar";
                maxLength = 500;
            }
            if (maxLength > 0)
            {
                sb.AppendFormat(string.Format(" [{0}] {1} ({2}), ", dt.Columns[i].ColumnName, sqlDBType, maxLength));
            }
            else
            {
                sb.AppendFormat(string.Format(" [{0}] {1}, ", dt.Columns[i].ColumnName, sqlDBType)); 
            }
        }
        sqlQuery = sb.ToString();
        sqlQuery = sqlQuery.Trim().TrimEnd(',');
        sqlQuery = sqlQuery + " )";
        using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
            sqlConn.Open();
            SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }
    }

Friday, May 3, 2013

SQL Server 2008 Service Broker

Hey Everyone- If your wanting to use SQL CACHING for your web application. You'll need to enable service broker on your database.  Below is the code that needs to be execute in SQL Manager. Have Fun!!
ALTER DATABASE YOUR_DATABASE SET ENABLE_BROKER 

Using JQUERY with ASP.NET - A Beginner's Guide

As everyone knows, JQUERY is starting to become pretty relevant in today's programming especially with .NET programmers. So if you click the link below you'll find a great resource on becoming a JQUERY NINJA!!!! :-)   http://www.dotnetcurry.com/ShowArticle.aspx?ID=231