Posts filed under ‘ASP.NET’

ASP.NET / C# Image Optimization

ASP.NET Image Optimization Code

Original Source:

May 6, 2008 at 11:30 am 2 comments

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

A Couple of Quick Tips on Setting Up IIS 5 (XP)

It’s not always obvious whats up with IIS if all not going according to plan. The error messages are not always as clear as they could be. None of it’s that tricky once you’ve set up a couple of sites, however, there are some things to watch out for:

 1. IIS 5 must be installed before you  install the .NET framework. Lots of problems arise if the two components are not installed in that order. It’s probably advisable to reinstall any instances of SQL Server that you’ll be using too.

 2. Make sure that anonymous access is enabled. Default Website > Properties > Directory security.

 3. If you want to put your application at a level higher than wwwroot (e.g. wwwroot/mysite/default.aspx), then you need to set up a virtual directory, even if it’s just going to be the same name. This is because it is an error to place a web.config file at a level higher than the application root.

 This page explains how to set up a virtual directory in IIS 4 or 5:

 http://www.microsoft.com/technet/security/prodtech/IIS.mspx

 With these simple rules adhered to, you should be able to start testing your C# or VB web pages.

March 25, 2008 at 2:32 am 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

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

Posts by Month

Posts by Category