Stephen Daly - ASP.net/C# developer & technology enthusiast

Image upload with a specific width & height ratio

While working on the message board for my brothers band site (Black Soul Strangers) today, i needed to let users upload a profile picture but i didnt want it to exceed the 60px*60px and i also wanted to keep the Width*Height ratio. Here is the code i developed to do this: 

// This method uploads the file
public void uploadFile(object sender, EventArgs e)

{

    string SaveLocation = "";

    string filename = "";

   
int MAXFILESIZE = 10000;
    int MAXWIDTH = 60;

    int MAXHEIGHT = 60;

    float width, height;

 // Checks to see if there is a file to be uploaded

   if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
    {

       if (FileUpload1.PostedFile.ContentLength <= MAXFILESIZE)

        {

            SaveLocation = Server.MapPath(".") + "\\images\\profilepics\\";

            EnsureDirectory(new System.IO.DirectoryInfo(SaveLocation));

            filename = FileUpload1.PostedFile.ContentType;

            string[] filetype = filename.Split('/');
            filename = User.Identity.Name.ToUpper() + "." + filetype[1];
            SaveLocation = SaveLocation + "\\" + filename;
            string SaveLocationSQL = "images/profilepics/" + filename;
            FileUpload1.PostedFile.SaveAs(SaveLocation);

            Bitmap i = new Bitmap(SaveLocation);                  

            height = MAXHEIGHT;
            width = (height / i.Height) * i.Width;
 

            if (width > MAXWIDTH)
             {

               height = (
MAXHEIGHT / width) * height;

               width = MAXWIDTH;
             }

            i.Dispose();
            FileUpload1.Dispose();

            BSSUser u = new BSSUser();

            u.UserID = userid;

            u.PicUrl = SaveLocationSQL;

            u.PicHeight = Convert.ToInt32(height);

            u.PicWidth = Convert.ToInt32(width);

            u.changeProfilePic(u);

            Response.Redirect("MyAccount.aspx");

        }

     else
        {

            lblFileUpload.Text = "TOO LARGE - MAX SIZE IS 10KB";

            lblFileUpload.ForeColor = System.Drawing.Color.Red;

         }

   }

  // Returns null if there is no file to be uploaded
  else

    {

       Response.Redirect("Error.aspx");

    }

}


// checks if the directory exists. If not, it will create it

public void EnsureDirectory(System.IO.DirectoryInfo DirInfo)

{

   if (DirInfo.Parent != null)

       EnsureDirectory(DirInfo.Parent);

   if (!DirInfo.Exists)

     {

       DirInfo.Create();

     }

}


Posted by: Stephen
Posted on: 08/03/2009 at 9:09 AM
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Backup your website from your FTP server to your local machine

This is a side project i started for myself. I will upload various parts of the code over time.

Background

I needed a piece of software to copy my websites from my FTP server. So off I went to Google... as i was looking at all the paid software, i said to myself, "come on ste, your a nerd, why don’t you just develop it yourself". So that’s what I did. It has also let me gain on my Visual C# experience. I have decided that I will continue to make tools like this during my free time and I will put them on my brand spanking new website : Smart Future Tools (www.SFTools.com). This will enable me to present my free tools to the world and also get some valuable feedback so i can improve the tools and also improve myself as a better coder.

Features

  • Backup your site manualy
  • Schedule backups
  • Recieve backup email alerts/reports
  • All passwords are encrypted
  • Views the logs of each backup

 Platform

  • Visual C#
  • Linq
  • XML

Screen Shots

 

1) Manually run a backup.

You can see the status of the backup is shown along with the current activity at the bottom. 

 

2) Managing the schedules that will run in the background.

3) Managing the FTP accounts

4) Managing the email settings or the email alerts/reports 





Posted by: Stephen
Posted on: 18/01/2009 at 3:15 PM
Tags: , , , , , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

One method to enable/disable controls instead of using two

I always try to think about how to improve my code or other people's code. One thing I notice is some people using two methods for enable and disable controls/buttons. Wouldn't it be much better to just have one method? This would mean less code and only one location to update the code.
 

Here is the old way:

    private void EnableControls()

    {

        lvMovieList.Visible = true;

        btnSearch.Enabled = true;

        btnRescan.Enabled = true;

        txtSearch.Enabled = true;

        btnTV.Enabled = true;

        pnlAdvancedSearch.Enabled = true;

        tcFindMovies.Enabled = true;

    }

    private void DisableControls()

    {

        lvMovieList.Visible = false;

        btnSearch.Enabled = false;

        btnRescan.Enabled = false;

        txtSearch.Enabled = false;

        btnTV.Enabled = false;

        pnlAdvancedSearch.Enabled = false;

        tcFindMovies.Enabled = false;

    }

 

Here is the better improved way: 

    private void ChangeControls(bool onOff)

    {

        lvMovieList.Visible = onOff;

        btnSearch.Enabled = onOff;

        btnRescan.Enabled = onOff;

        txtSearch.Enabled = onOff;

        btnTV.Enabled = onOff;

        pnlAdvancedSearch.Enabled = onOff;

        tcFindMovies.Enabled = onOff;

    }

 

So now when you want to disable controls you pass in false and pass in true when you want to enable the controls.

E.G: ChangeControls(true);

 

If you need one control set to true when disabling all other controls.

Then you can do this:

btnCancel.Enabled = onOff ? false : true;

 

I know this is pretty basic stuff but im sure some people out there will gain from reading it.


Posted by: Stephen
Posted on: 28/11/2008 at 11:09 AM
Tags: , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

More free handy tools & plug-ins

It has been a while since my last post about useful tools. Actually, its been a while since i have made any type of post because i have been really busy with work, catching up with my friends & saving the world! Wink Anyway, i am still alive and i have some posts ready to publish. 

 

Xobni - This is a really cool plug-in for outlook. It will tell you how much email you receive from people. You can see the ranking of each user by the amount of mails you send/receive. It can tell you the average response time from a user. It can also do lots lots & lots more. Its defo worth a try!!

UltraVNC - This is a nice piece of free software that will allow you to display the screen of another computer (via internet or network) on your own screen. I use this alot at home to control my media pc which is connected to my plasma screen. So now my laptop is like my new remote control!

FlashGet - This is a handy piece of software to manage all your downloads. You can make multiple connections to a download to improve your download speed. If you use FireFox then you should also download the FlashGot Add-On.

CDBurnerXP - This is a free application to burn CDs and DVDs, including Blu-Ray and HD-DVDs. It also includes the feature to burn and create ISO's.

 

Have fun and keep checking back for more useful tools Smile


Posted by: Stephen
Posted on: 24/09/2008 at 12:23 PM
Tags: , , , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Goodbye India, Hello Ireland!!!

I cannot believe that in 2 more days, I will be leaving India to go back home!! The 9 months working over here have really flown by. As much as I am really excited to get back home to all my family and friends, I am REALLY going to miss India. I have met so many wonderful people over here and have learnt so much about life, myself, different cultures, and different ways of life. I have even learnt to eat chicken curry for breakfast, dinner and tea! I have seen many wonderful and interesting things while over here that I never taught I would see. I have been to temples, watched the sunset at the south tip of India were the 3 oceans meet, celebrated festivals, went to the gateway of India, seen 4 pretty girls shave their hair off for charity, done traditional dancing with sticks in the back garden of a palace with 500+ Indians for Dandia, went to lots of different beaches and many other random places. I am also going to miss simple things like walking through India listening to The Kinks, Beatles & Oasis thinking to myself "I am in India!".
 
I am sure you're wondering that it can’t be all good….well, just like anywhere including Ireland there is a few things I wont be missing…. I won’t be missing the same food all the time, the polluted air, the near death experiences on the road with the crazy auto rickshaw drivers (They apparently have traffic rules, but I am yet to see someone obey them) and finally I won't miss the journey to work crossing over the bridge where nobody should look left or right as you may see a man with a bucket of water on a mission to freshen up the air with his manly aroma. It is not a pretty sight but at the end of the day, that is life. 

 

The best part of coming here would have to be all the friends I have made – (in no particular order):

Colm (I love auto drivers!), Tayo (Trust me), Babar, Justin (Better looking at it than looking for it!!), Imran (I feel sick!), Zee (I also feel sick!!), Din(Allllriiiight), Trisha, Peter (God bless you!), Rob(Im all alone in Kolkota), Hannah, Sunit(Alright man...), Shekhar (Watch out for that mirror!!), Neel (Loves me for all the weird bugs I find doing my “Monkey Testing”), Surendra (Watch you dont spill coke on that pizza!!), Abhishek(Mmmmm coke on pizza is really yummy!!), Prada (Can I ask you “1” question steo?), Ravneet (Hey man, hi 5!), Ste, Ujjval (aka The Man), Wikram, Zara(But why…), Anil (Sneaky Sneaky).

 

To my Indian friends i say Goodbye!! And to my Irish friends i say "Whats the craic?"!

 


Posted by: Stephen
Posted on: 23/04/2008 at 3:34 PM
Tags: , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (3) | Post RSSRSS comment feed

Send an email in ASP.Net or a Visual C# app

In this example/demo, i will explain how to send an email from your ASP.Net website or C# application using your GMail account but it can be easily be modified to use other email accounts.

If you want to use a different email account then you need the following checklist:

  • Port number - This is usually "25" but can be different as some block this port to prevent spam which i know we all hate!
  • SMTP host address - usually "smtp.YourEmailDomain.com" but this can also be different
  • SSL - Is ssl needed? if yes then make sure the property is set to true
  • Email & Password - The email and password of your email account

The code example below has some details hardcoded in for easier viewing but when you add it to your website/application then i would advise to make the details like port/email/password/smtp as parameters.

First make sure you add the following namespace:

using System.Net.Mail;

 

public void sendGmail(string emailTo, string subject, string body)

{

    //Creates a new message and sets the From address

    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();

    msg.From = new MailAddress("YOUREMAIL@gmail.com", "Your Name");

    // Adds addresses the To/CC/Bcc fields

    msg.To.Add(emailTo);

    msg.CC.Add("CCEmailAddress@whatever.com");

    msg.Bcc.Add("BccEmailAddress@whatever.com");

    //Creates a new attachement and adds it to the message

    Attachment file = new Attachment("c:/test.txt");

    msg.Attachments.Add(file);

    // Sets the subject text and the Encoding

    msg.Subject = subject;

    msg.SubjectEncoding = System.Text.Encoding.UTF8;

    // Sets the body text and the Encoding

    msg.Body = body;

    msg.BodyEncoding = System.Text.Encoding.UTF8;

    // Sets the mail to be a HTML message

    msg.IsBodyHtml = true;

 

    // Creates a new SMTP client to send the above message

    SmtpClient client = new SmtpClient();

    // Sets the login credentials for your email account

    client.Credentials = new System.Net.NetworkCredential("YOUREMAIL@gmail.com", "YOURPASSWORD");

    // Sets the port number for the Gmail server

    client.Port = 587;

    // Sets the smtp server to Gmails

    client.Host = "smtp.gmail.com";

    // Enables SSL

    client.EnableSsl = true;

    // This will send the message based on all the previous details

    client.Send(msg);

}

 

Acronyms

SSL: Secure Sockets Layer

SMTP: Simple Mail Transfer Protocol


Posted by: Stephen
Posted on: 08/04/2008 at 2:38 PM
Tags: , , , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (1) | Post RSSRSS comment feed

Free online tools + services to get you through your day

I continually find myself in situations where I need to do something on a machine that doesn’t have the software I need and I don’t have admin access to install some freeware to perform the small task. Therefore, I always do a Google search with the word "online" in it. E.G: DOC to PDF online or convert PNG to GIF online. Well, here is a new section in my ever grown Toolbox page which will focus on free online tools/services.

Online Tools & Services

  • DOC to PDF - On this site, you upload your document and its gets emailed to you in a few minutes when it is ready. I used this allot in college when handing up my project documents because PDF looks more professional than DOC. NOTE: I would advise not using this with any confidential documents.
  • Image Optimizer (GIF, JPG, + PNG) - This site will convert and optimize your images online for free. Very useful when you want to display transparent PNG images in IE without using the CSS filter hack so I convert them to gif.
  • Image to Icon - I used this site to create my URL icon that you can see in the address bar. I created a quick tutorial that can be found here that will quickly show you how to add it to your site.
  • Monitor your website - I use the free version that pings my sites every hour and gives me daily reports on the uptime. I have changed hosting just because of this site. Would recommend the paid version if you have a critical application and want it monitored every minute and want an SMS alert when it is down.
  • Stat counter for your website - If you have a site and you want to track your visitors then this site is great. All you need to do is create an account + then add some JavaScript code to your site. Fast, easy and effective!
  • Validate CSS - If you have done work with CSS then I would be disappointed if you haven’t already used this site to validate your CSS code to make sure it is compliant on all browsers and so you keep your IE hacks in a different CSS file.

Posted by: Stephen
Posted on: 03/04/2008 at 1:50 AM
Tags: , , , , , , , , , , , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Translate the language on your site using google api

I got an email this morning from CodeProject with a link to the Google api for language translation. I taught it was interesting so i decided to start exploring it and created 3 demos/examples here:

  1. Translate language on page load
  2. Translate language as you type
  3. Translate to a specific language

 

What i plan to do when i get some free time is to enable users to translate this site into their own language by clicking on their country flag.  

Note: You can download the source code at the end.

Demo 1 

English Text:
This text will be translated on the page load to Spanish.

Translation:

 

Code: 

JavaScript

// This changes the text on the page load

google.load("language", "1");

function initialize()

{

    google.language.translate(document.getElementById("text1").innerHTML , "en", "es", function(result) {

    if (!result.error)

        {

            var container = document.getElementById("translation1");

            container.innerHTML = result.translation;

        }

    });

}

google.setOnLoadCallback(initialize);

HTML 

<script src="http://www.google.com/jsapi" type="text/javascript"> </script>

<b>English Text:</b><br />

<div id="text1">

This text will be translated on the page load to Spanish.

</div>

<br /><b>Translation:</b><br />

<div id= "translation1"> </div>

Demo 2 

As you type in the text in the text box, the language will auto translate below into Spanish.
NOTE: you should alwas put a space after the last word for it to work correctly
Type english Text:

Translation:

 

Code:

JavaScript

//This will translate the textarea as you type

function TranslateAsYouType()

{

    google.language.translate(document.getElementById("txtBox1").value, "en", "es", function(result) {

        if (!result.error)

        {

            var container = document.getElementById("translation2");

            container.innerHTML = result.translation;

        }

    });

}

HTML

<script src="http://www.google.com/jsapi" type="text/javascript"> </script>

<b>Type english Text:</b><br />

<textarea cols='40' rows='3' id='txtBox1' onkeypress='TranslateAsYouType()'></textarea>

<br />

<b>Translation:</b>

<div id="translation2">

</div>

 

Demo 3 

The following text will get translated to the language of your choice
French | German | Italian | Portuguese | Russian | Spanish | Dutch | Arabic

English Text:
This text will be translated to the language of your choice.

Translation:

 

Code:

JavaScript

//This function will translate to the selected language that is passed

function TranslateTo(lang)

    {

    google.language.translate(document.getElementById("text3").innerHTML, "en", lang, function(result) {

        if (!result.error)

        {

            var container = document.getElementById("translation3");

            container.innerHTML = result.translation;

        }

    });

}

HTML 

<script src="http://www.google.com/jsapi" type="text/javascript"> </script>

The following text will get translated to the language of your choice<br />

<a href="javascript:TranslateTo('fr')">French</a> |

<a href="javascript:TranslateTo('de')">German</a> |

<a href="javascript:TranslateTo('it')">Italian</a> |

<a href="javascript:TranslateTo('pt-PT')">Portuguese</a> |

<a href="javascript:TranslateTo('ru')">Russian</a> |

<a href="javascript:TranslateTo('es')">Spanish</a> |

<a href="javascript:TranslateTo('nl')">Dutch</a> |

<a href="javascript:TranslateTo('ar')">Arabic</a> |

<a href="javascript:TranslateTo('zh')">Chinese</a> |

<a href="javascript:TranslateTo('zh-CN')">Chinese Simplified</a> |

<a href="javascript:TranslateTo('zh-TW')">Chinese Traditional</a> |

<a href="javascript:TranslateTo('ko')">Korean</a>

<br /> NOTE:Some will only work if the language pack is installed on the users browser

 

<br /><br />

<b>English Text:</b><br />

<div id="text3">

This text will be translated to the language of your choice.

</div>

<br /><b>Translation:</b><br />

<div id= "translation3"> </div

 

Download: Translation.zip (2KB)

Links:

 


Posted by: Stephen
Posted on: 21/03/2008 at 2:52 PM
Tags: , , , , , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (7) | Post RSSRSS comment feed

Worked my 13th day in a row

Today i worked my 13th day in a row. It has been a long 2 weeks but it now feels like it has been worth while after seen the finished product. I have to give credit to all the Indian people that i have been working with because they have been working so hard and the commitment to the project has been magnificent!!

The only shame is that there has been no overtime pay Cry but we did get lots of free pizza’s!!!  Laughing 


Posted by: Stephen
Posted on: 08/03/2008 at 3:02 PM
Tags: ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed

Parsing a Querystring in JavaScript example

I was asked to get the value of a giving query string name through JavaScript. The following is the function I created to return the value of a specific query string.

function QueryString(name)

{

   url = window.location.search.substring(1);

   param = url.split("&");  

   for (i=0;i<param.length;i++)

   {

        value = param[i].split("="); 

        if (value[0] == name)

        {

             return this.unescape(value[1]);

        }

    }

}


Posted by: Stephen
Posted on: 17/02/2008 at 7:02 PM
Tags: , , ,
Actions: E-mail | Digg it! | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (0) | Post RSSRSS comment feed