Posts filed under ‘C#’

ASP.NET / C# Image Optimization

ASP.NET Image Optimization Code

Original Source:

May 6, 2008 at 11:30 am 2 comments

Simple C# Delegate Example

Simple example of passing a delegate to a method to extend the functionality of the recieving method. This allows us to reuse the code in the recieving method since it can be combined with the method passed with the delegate to produce new functionality.

using System;
using System.Collections.Generic;
using System.Text;

// Delegates are used here to provide a method containing common functionality
// a way of using a method passed in (via a delegate) to extend functionality.
// This is a way of re using code since common functionality is extended via
// the use of delegates that pass in specialist functionality


    public class UserClass
    {
        // Method that takes a delegate as a parameter and uses it to complete its work
        public void ReturnText(ProcessDelegate newDelegate)
        {
            string stubString = "Stub ";

            string getDelegateResponse = newDelegate();

            stubString += getDelegateResponse;

            Console.WriteLine( stubString );
        }
    }

    public delegate string ProcessDelegate();

    public class MainClass
    {
        // Instance method to be passed to delegate
        string AppendText()
        {
            Random random = new Random();

            string txt = "";

            txt += random.Next(0, 100000).ToString();

            return txt;
        }

        // Static method to be passed to delegate
        static string StaticAppendText()
        {
            Random random = new Random();

            string txt = "";

            txt += random.Next(0, 100000).ToString();

            txt += (" (Static)");

            return txt;
        }

        static void Main(string[] args)
        {
            // Create an instance of the class which contains a method that uses a delegate
            UserClass newUserClass = new UserClass();

            // Call the user class's method passing a methed of an instance object
            MainClass newMainClass = new MainClass();
            newUserClass.ReturnText(new ProcessDelegate(newMainClass.AppendText));

            // Call the user class's method passing a static method
            newUserClass.ReturnText(new ProcessDelegate(StaticAppendText));

            Console.ReadLine();
        }
    }

May 5, 2008 at 4:23 pm Leave a comment

Lotto Number Generator Form Class (C# .NET)

This code demonstrates another way to generate unique random numbers, using an if statement in nested for loops to check and reassign numbers where it is found they have already been selected.

Not to the most graceful way of going about this, but works none the less. There is another random number generator class in this blog which is a bit neater.

Download Code File: LottoForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lotto
{
public partial class LottoForm : Form
{
public LottoForm()
{
InitializeComponent();
}

Random m_random = new Random();

int[] selectedNumbers = new int[7];

private void goButton_Click(object sender, EventArgs e)
{
// For each array member, assign a random number
for (int numberCount = 0; numberCount < selectedNumbers.Length; numberCount++)
{

int newNumber = m_random.Next(1, 50);

for (int i = 0; i < numberCount; i++)
{
if (newNumber == selectedNumbers[i])
{
// MessageBox.Show(“A duplicate (” + newNumber + “) has occured”);
newNumber = m_random.Next(1, 50); // Assign a new number
// MessageBox.Show(“Replacing with ” + newNumber);
continue; // Test again
}
}

selectedNumbers[numberCount] = newNumber;

}

// Place the bonus number in the 7th space before sorting

textBox7.Text = selectedNumbers[6].ToString();

// Create and populate intemediary array which we can exclude the bonus number from
int[] nonBonusNumbersArray = new int[6];

for (int x = 0; x < nonBonusNumbersArray.Length; x++)
{
nonBonusNumbersArray[x] = selectedNumbers[x];
}

// Sort the intemediary array
Array.Sort(nonBonusNumbersArray);

// Place sorted numbers in non bonus text boxes
textBox1.Text = nonBonusNumbersArray[0].ToString();
textBox2.Text = nonBonusNumbersArray[1].ToString();
textBox3.Text = nonBonusNumbersArray[2].ToString();
textBox4.Text = nonBonusNumbersArray[3].ToString();
textBox5.Text = nonBonusNumbersArray[4].ToString();
textBox6.Text = nonBonusNumbersArray[5].ToString();

label9.Text = “”;
label9.Text += “Your new numbers are: \n\n”;
label9.Text += nonBonusNumbersArray[0].ToString();
label9.Text += “, “;
label9.Text += nonBonusNumbersArray[1].ToString();
label9.Text += “, “;
label9.Text += nonBonusNumbersArray[2].ToString();
label9.Text += “, “;
label9.Text += nonBonusNumbersArray[3].ToString();
label9.Text += “, “;
label9.Text += nonBonusNumbersArray[4].ToString();
label9.Text += “, “;
label9.Text += nonBonusNumbersArray[5].ToString();
label9.Text += ” (Bonus: “;
label9.Text += selectedNumbers[6].ToString();
label9.Text += “)”;

}

}
}

March 26, 2008 at 12:17 pm Leave a comment

Unique Random Number Generator Class (C# .NET)

This is a class for generating an absolute unique random number. The class works by removing selected numbers from a list once they’ve been selected, so it’s impossible for them to be selected again, thus making it possible to simulate real life random number selection in lottery type scenarios.

Pass the maximum and minimum numbers that you would like returned from the class to the constructor when creating the object.

Download Code File: GenerateUniqueRandomNumbers.cs

using System;
using System.Collections.Generic;
using System.Text;

/// <summary>
/// Class for generating unique random numbers within a given range. Removes numbers from list
/// once chosen from an instance of an object so that it is impossible for them to be selected again.
/// </summary>
public class GenerateUniqueRandomNumber
{
Random m_random = new Random();

int m_newRandomNumber = 0;

List<int> RemainingNumbers;

// Constructor
public GenerateUniqueRandomNumber( int requiredRangeLow, int requiredRangeHi )
{
// Get the range
int range = (requiredRangeHi – requiredRangeLow);

// Initialise array that will hold the numbers within the range
int[] rangeNumbersArr = new int[range + 1];

// Assign array element values within range
for (int count = 0; count < rangeNumbersArr.Length; count++)
{
rangeNumbersArr[count] = requiredRangeLow + count;
}

// Initialize the List and populate with values from rangeNumbersArr
RemainingNumbers = new List<int>();
RemainingNumbers.AddRange(rangeNumbersArr);
}

/// <summary>
/// This method returns a random integer within the given range. Each call produces a new random number
/// </summary>
/// <returns></returns>
public int NewRandomNumber()
{
if (RemainingNumbers.Count != 0)
{
// Select random number from list
int index = m_random.Next(0, RemainingNumbers.Count);
m_newRandomNumber = RemainingNumbers[index];

// Remove selected number from Remaining Numbers List
RemainingNumbers.RemoveAt(index);

return m_newRandomNumber;
}
else
{
throw new System.InvalidOperationException(“All numbers in the range have now been used. Cannot continue selecting random numbers from a list with no members.”);
}
}
}

March 26, 2008 at 12:00 pm Leave a comment

Porting Visual Studio .mdf Database File to SQL Server – ASP.NET

There is some confusing information out there on how to get your development database from visual studio into SQL Server so that you can run an ASP.NET website through IIS.

I’ve spent a whole evening getting this sorted and now am writing down explicit instructions on how I did it so that I (and hopefully you don’t have to spend time doing this again).

Prerequisites:

A database file in .mdf format.

IIS (Tested on IIS 5)

SQL Sever

SQL Server Management Studio Express (Free)

Download Link:

http://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&displaylang=en

1. In your web.config file, change the connection string to the following, replacing the database name and connection string name:

2. Attach the mdf file to SQL server by right clicking the databases node, selecting attach, and pointing to the .mdf file from Visual Studio. This will be deleted later, bear with me.

3. Create a back up of that attached database by right clicking the database name, going to tasks, then back up.

4. Back up as prompted and make a note of the back up location. The back up will create a back up file in format .bak.

5. Delete the attached data base.

6. Create a NEW (as opposed to attached) database in SQL Server management studio express by right clicking databases node and selecting new database.

7. Give the new database the same name as your .mdf file, excluding the extension.

8. You are given the opportunity to assign owners. Play around a bit here. I selected all available options here, which through an error, but some owners stuck anyway, so don’t worry too much here ( a security expert may say other wise! ). Roles are added via queries in a minute so this might not even be necessary.

9. Back in the tree view, click the new database name node, go to tasks again, and select restore.

10. Point to the recently created back up file and restore.

11. Now for some trickery pokery. We need to configure security for SQL server. In SQL Server management studio express, you can execute queries against your database. Type in the following queries one at a time only replacing machineName and databaseName. This will be the name of the windows pc you are installing the application on.

EXEC sp_grantlogin ‘machineName\ASPNET’

USE databaseName

EXEC sp_addrolemember ‘dbowner’, ‘machineName\ASPNET’

USE databaseName

EXEC sp_grantlogin ‘machineName\ASPNET’

That’s it. With some luck you should be good to go here!

March 25, 2008 at 2:16 am Leave a comment

Sending E-mail From C# Class Using G-mail

Here is a complete C# class that can be used to send mail using a g-mail (Google mail) account. This has been tested as working today.

I’ve used the web.config file to get authentication parameters and smtp server, but these can be replaced directly with strings if you like. Those strings will be:

SmtpUser: Your gmail user name. SmtpPassword: Your gmail password. SmtpClient: smtp.gmail.com

Also worth noting is that the port used is 587 instead of 465. If 587 doesn’t work, try 465.

The Code:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net.Mail;
using System.Net;

///
/// Summary description for MailSender
///
public class MailSender
{

    // Constructor #1 for general text only messages
    ///
    /// Constructor for basic email sending, does not required that IsHtml bool is specified.
    ///
    ///
    ///
    ///
    ///
    public MailSender(string from, string to, string subject, string body)
    {
        m_from = from;
        m_to = to;
        m_subject = subject;
        m_body = body;

        SendMailGmail(m_from, m_to, m_subject, m_body, false);
    }

    // Constructor #2 with ability to specify isHtml as true for sending HTML email
    ///
    /// Constructor with optional IsHtml parameter for sending of HTML email.
    ///
    ///
    ///
    ///
    ///
    ///
    public MailSender(string from, string to, string subject, string body, bool isHtml )
    {
        m_from = from;
        m_to = to;
        m_subject = subject;
        m_body = body;

        SendMailGmail(m_from, m_to, m_subject, m_body, isHtml);
    }

    ///
    /// Send email method configured for use with gmail.
    ///
    /// From
    /// To
    /// Subject
    /// Body text
    /// IsHtml
    private void SendMailGmail(string from, string to, string subject, string body, bool isHtml)
    {
        // Code from: http://www.andreas-kraus.net/blog/aspnet-20-aka-systemnetmail-with-gmail/

        System.Net.Mail.MailMessage message = new MailMessage(from, to, subject, body);
        message.Priority = MailPriority.High;
        message.IsBodyHtml = isHtml;

        SmtpClient smtp = new SmtpClient();
        smtp.Host = m_smtpClient;

        smtp.Credentials = new System.Net.NetworkCredential(m_smtpUserName, m_smtpPassWord);
        smtp.EnableSsl = true;
        // Not the usual port but works
        smtp.Port = 587;
        smtp.Timeout = 10;

        try
        {
            smtp.Send(message);
        }
        catch (Exception ex)
        {
            // Send error but pass false to prevent looping error emails
            ErrorLogger errorLogger = new ErrorLogger(ex, false);
        }
    }

    private string m_from = "";
    private string m_to = "";
    private string m_subject = "";
    private string m_body = "";

    private string m_smtpClient = ConfigurationManager.AppSettings["SmtpClient"];
    private string m_smtpUserName = ConfigurationManager.AppSettings["SmtpUser"];
    private string m_smtpPassWord = ConfigurationManager.AppSettings["SmtpPassword"];
}

March 24, 2008 at 8:28 pm 1 comment


Calendar

June 2017
M T W T F S S
« May    
 1234
567891011
12131415161718
19202122232425
2627282930  

Posts by Month

Posts by Category