Saturday, June 14, 2014

Resetting Root Password in Ubuntu

There are a number of references for how to reset your root password in Ubuntu, if you've forgotten it that reference booting into recovery mode. I've found a simple way to do it that only requires a couple of steps.

  1. Enter the following command: sudo passwd root
  2. You will be prompted to enter your new password twice
  3. Enter su root and your new password

DONE! Very short and to the point!

Thursday, May 10, 2012

Stock Purchase Calculator

Today I released Stock Purchase Calculator v1.0.0 to Google Play. The application provides a way to quickly get an idea of how many stocks you can buy with a certain amount of money and how much you could make if you sold the stock at a certain price?

The application provides the total purchase and total sell amounts for a given number of stock shares minus broker commissions. In addition both net profit and loss, net change, and the stock symbol for a given company are reported.

The following is a direct link to the application on Google Play:

https://play.google.com/store/apps/details?id=com.lancespence.spc&feature=search_result#?t=W251bGwsMSwyLDEsImNvbS5sYW5jZXNwZW5jZS5zcGMiXQ..

Tuesday, October 25, 2011

Displaying User Associated Membership Image

I recently came across a post in the ASP.NET forums where a user had a need to allow users of his web site to upload an image during account creation. The user’s image was then redisplayed upon successful login into the website. I decided to put a little sample together detailing how this could be accomplished.

Database Setup

Let’s start first with the database setup. I’m using SQL Server 2008, but SQL Server 2008 Express, SQL Server 2005, and SQL Server 2005 Express should work equally as well.
Using SQL Server Management Studio I created a new database called TestDB. I then added the ASP.NET Membership, Roles, and Profile providers to the database with the following command:
aspnet_regsql –S . –E –A mrp –d TestDB
You can enter aspnet_regsql /? for a list of available options.
Once I had all of the appropriate tables, stored procedures, views, etc. added to my database I created a table called aspnet_UserImages. This table contains the following columns:
  • UserId
  • ImageId
  • Image
I created a foreign key linking the UserId column from the aspnet_Users table to the UserId of the aspnet_UserImages table. In addition the Delete Rule within the aspnet_UserImages table was set to Cascade. Doing this allows the user’s image associated with the UserId to be deleted from the aspnet_UserImages table when the user’s account is removed via the Web Site Administration Tool or via SQL Server Management Studio directly.
image
I’ve included two stored procedures along with the sample that insert and retrieve the uploaded image associated with the user’s account. I’ve also included a script that will create the aspnet_UserImages table along with the foreign key constraint mentioned earlier.
New User Registration
I’ve converted the CreateUserWizard to a template and added a FileUpload control to it, so that users can upload an image of their choice at the time they create their account.
The code is pretty straightforward a few things to note though. First I save the user’s entered username into a session variable and later retrieve it when the user logs in, so that it can be used in retrieving the image that is associated with the user’s account. Another thing I’ve done is incorporated code to resize the uploaded image, so that you can control to a degree the amount of space the images will consume within your database. Finally I check the file extension, so that only the types defined are accepted, if a non-supported file type is uploaded the user account is not created.
image
image
protected void NewUserWizard_CreatingUser(object sender, LoginCancelEventArgs e)
{
Label invalidFile = (Label)CreateUserWizardStep1.ContentTemplateContainer.FindControl("ErrorLabel");
FileUpload userImage = (FileUpload)CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserImageFileUpload");

// Check whether we have a file to save or not.
if (userImage.HasFile)
{
// Check that the file type is supported.
string fileExtension = Path.GetExtension(userImage.PostedFile.FileName);

switch (fileExtension)
{
case ".gif":
break;
case ".jpg":
case ".jpeg":
break;
case ".png":
break;
default:
invalidFile.Visible = true;
invalidFile.Text = "Supported file types are GIF, JPG, PNG.";
e.Cancel = true;
break;
}
}
}



User login

I have a default.aspx page that the user is redirected to upon successful authentication. This page contains the code that gets the user’s Guid and then passes it to a Generic Handler via querystring, which in turn gets the image associated with the user’s account and displays it.

image

image

private void DisplayUserImage()
{
if (Session["UserName"] != null)
{
MembershipUser user = Membership.GetUser(Session["UserName"].ToString());
Guid userGuid = (Guid)user.ProviderUserKey;
UserImage.ImageUrl = "Image.ashx?userGuid=" + userGuid;
}
}


The handler that retrieves the user’s image associated with their account.

public void ProcessRequest (HttpContext context)
{
string userGuid = string.Empty;

// Check that the querystring value is not null.
if (context.Request.QueryString["userGuid"] != null)
{
userGuid = context.Request.QueryString["userGuid"];
}
else
{
throw new ArgumentException("Missing user id.");
}

context.Response.ContentType = "image/jpeg";

// Pass the user's guid in, so that we can get the image associated with the logged in user.
Stream strm = GetImage(userGuid);
byte[] buffer = new byte[2048];
int byteSeq = strm.Read(buffer, 0, 2048);

while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}

public Stream GetImage(string id)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString))
{
try
{
using (SqlCommand cmd = new SqlCommand("GetUserImage", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserId", id);

conn.Open();
byte[] img = (byte[])cmd.ExecuteScalar();

try
{
return new MemoryStream(img);
}
catch
{
return null;
}
finally
{
conn.Close();
}
}
}
catch (SqlException sqlEx)
{
throw sqlEx;
}
}
}

public bool IsReusable 
{
get
{
return false;
}
}



MembershipWithImage

Thursday, June 9, 2011

Useful .Net Tools

I thought I’d share a small list of free and open source .Net tools that you might find useful during your development efforts. I’ll continue to add to this list as I learn of new tools.
Profiling Tools
Slimetune - http://code.google.com/p/slimtune/
xteprofiler - http://www.xteprofiler.com/
Prof-It for C# - http://dotnet.jku.at/projects/Prof-It/Default.aspx

Decompilers
JustDecompile - http://www.telerik.com/products/decompiling.aspx
dotPeek EAP - http://www.jetbrains.com/decompiler/
ILSpy - http://wiki.sharpdevelop.net/ilspy.ashx

Load Testing Tools
loadUI - http://www.eviware.com/loadUI/whats-new-in-loadui-15.html
openSTA - http://opensta.org/
storm - http://storm.codeplex.com/

Functional Testing Tools
soapUI - http://www.eviware.com/soapUI/what-is-soapui.html
WebAii Testing Framework - http://www.telerik.com/automated-testing-tools/webaii-framework-features.aspx

Sunday, May 23, 2010

Pre-populating the Login Control’s Username and Password

We’ve all visited websites that provide a test or demo site and allow you to login for the purpose of testing features out using specific user accounts with assigned roles. If you have a website or web application that needs to provide this type of functionality, I’m going to show you how you can save the user a few keystrokes by filling in the Username and Password for them, so that all they have to do is click the Login button.

What I have done is created three accounts: Admin, User, and Guest along with a Default.aspx page which resides under the respective folder. The folder structure is as follows for these accounts:

Admin/Default.aspx

User/Default.aspx

Guest/Default.aspx

I’ve created a login page (Login.aspx) and dropped a Login Control on it. The Login Control has been converted to a template and I’ve added a label and dropdown list to it. The dropdown list contains the user accounts that will be selected for logging in.

image

Within the Load event of the Login Control I get a reference to the dropdown list and password textbox controls, so that they can be used in selecting the proper user and populating the password textbox. I add an attribute to the password textbox, which sets the password, so that the user does not have to type it in. Something to be mindful of is that the password is viewable in plain text if you view the pages source. Because these accounts are being used to save the user a few of keystrokes for a test or demo site login this isn’t much of an issue.

DropDownList userLogin = (DropDownList)DemoLogin.FindControl("UserDropDownList");
TextBox passwd = (TextBox)DemoLogin.FindControl("Password");
switch (userLogin.SelectedValue)
{
   case "Admin":
       DemoLogin.UserName = userLogin.SelectedValue;
       passwd.Attributes.Add("value", "Adm!n123");
       break;
   case "User":
       DemoLogin.UserName = userLogin.SelectedValue;
       passwd.Attributes.Add("value", "U$er123");
       break;
   case "Guest":
       DemoLogin.UserName = userLogin.SelectedValue;
       passwd.Attributes.Add("value", "Gue$t123");
       break;
   default:
       DemoLogin.UserName = string.Empty;
       passwd.Attributes.Add("value", "");
       break;
}


The only other thing needed is within the Login Control’s LoggedIn event to check the role of the user and then redirect them to the appropriate Default.aspx page.



if (Roles.IsUserInRole(DemoLogin.UserName, "Admin"))
{
   Response.Redirect("~/Admin/Default.aspx");
}
else if (Roles.IsUserInRole(DemoLogin.UserName, "User"))
{
   Response.Redirect("~/User/Default.aspx");
}
else if (Roles.IsUserInRole(DemoLogin.UserName, "Guest"))
{
   Response.Redirect("~/Guest/Default.aspx");
}
else
{
   Response.Redirect("~/Login.aspx");
}


image 



While this is pretty trivial, it does save a few keystrokes by allowing the user to just select the user account they wish to login as and then all they have to do is click the login button.



PopulateLoginSample.zip

Thursday, May 6, 2010

Display a list of locked users

I’ve created a simple example that both shows how you can display to the user the number of failed login attempts and disable their login after the specified max number of attempts you define. I’ve also created a simplified admin screen that displays all users that currently are locked out and allows you to select and unlock them after logging in as a user with the admin role.
This example uses a Master Page and within the code-behind is where you keep track of the number of failed login attempts. I’ve set the maxInvalidPasswordAttempts = 3 within the web.config as this is where the hard limit is defined.
<add name="AspNetSqlMembershipProvider" connectionStringName="MyAspNetDB" applicationName="/" 
passwordFormat="Hashed"
passwordAttemptWindow="30"
minRequiredNonalphanumericCharacters="1"
minRequiredPasswordLength="7"
maxInvalidPasswordAttempts="3" 
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>


Back in the Master Page’s code-behind I’ve defined a member variable called failedLoginCount that will contain the number of failed logins. In addition I’ve added a Page_Init that stores the failedLoginCount in ViewState. I choose to use ViewState because this is a very small amount of information that will be stored, so it won’t inflate the ViewState tremendously.


public int failedLoginCount;

protected void Page_Init(object sender, EventArgs e)
{
ViewState.Add("FailedLoginCount", failedLoginCount + 1);
}

protected void Page_Load(object sender, EventArgs e)
{
failedLoginCount = (int) ViewState["FailedLoginCount"];
}


Now within the Login Control’s LoggedIn event the role the user is a member of is checked and if they are in the Administrator role they are redirected to the Admin page; otherwise they are assumed to be a standard user and directed to the Standard users page.


protected void Login1_LoggedIn(object sender, EventArgs e)
{
Login logIn = (Login) LoginView1.FindControl("Login1");
if (Roles.IsUserInRole(logIn.UserName, "Administrators"))
{
Response.Redirect("~/Admin/Admin.aspx");
}
else
{
Response.Redirect("~/Standard/Standard.aspx");
}
}


It is within the Login Control’s LoginError event that failedLoginCount is checked to see if it equals the maxInvalidPasswordAttempts value that is defined within the web.config file. I get a reference to the Login control that is contained within a LoginView Control and then set the FailureText letting the user know that their account has been disabled and they need to contact the administrator once their failedLoginCount equals 3. This is followed by locking the user’s account, more formally setting IsApproved to false, which indicates that the user cannot be authenticated. If the failedLoginCount is not equal to 3 the failedLoginCount gets incremented and added to the ViewState key defined as well as the current count is displayed to the user.


protected void Login1_LoginError(object sender, EventArgs e)
{
string emailLink = "<a href=mailto:admin@somesite.com>";
emailLink += "Site Administrator";
emailLink += "</a>";

Login logIn = (Login)LoginView1.FindControl("Login1");

if (failedLoginCount == 3)
{
logIn.FailureText = "Your account has been disabled. Please contact the site administrator: " + emailLink;

MembershipUser user = Membership.GetUser(logIn.UserName);
user.IsApproved = false;
}
else
{
logIn.FailureText = "Failed login attempt [" + ViewState["FailedLoginCount"].ToString() + "]";
failedLoginCount++;
ViewState.Add("FailedLoginCount", failedLoginCount);
}
}


image


image


image


Now for the Admin portion I simply have a GridView Control that displays the list of users on the site whose accounts are currently locked out. A simple SQL query provides the list of users. I’ve coded this in-line, but in a real application I highly suggest that you put this into a Stored Procedure.


SELECT UserName, Email, LastLockoutDate, IsLockedOut 
FROM vw_aspnet_MembershipUsers 
WHERE IsLockedOut = 1


The unlocking of users takes place within the RowUpdating event of the GridView by calling UnlockUser() on the reference to MembershipUser. The following is the code for the admin section.


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}
}

private DataTable GetLockedUsers()
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyAspNetDB"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT UserName, Email, LastLockoutDate, IsLockedOut FROM vw_aspnet_MembershipUsers WHERE IsLockedOut = 1", conn))
{
cmd.CommandType = CommandType.Text;

try
{
conn.Open();
da.SelectCommand = cmd;
da.Fill(dt);

if (dt.Rows == null || dt.Rows.Count < 1)
{
LockedUsersLabel.Text = string.Empty;
return dt;
}

cmd.ExecuteNonQuery();
}
catch (SqlException sqlEx)
{
LockedUsersGridView.Rows[0].Cells[0].Text = sqlEx.ToString();
}
}
}

return dt;
}

protected void LockedUsersGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
LockedUsersGridView.PageIndex = e.NewSelectedIndex;
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}

protected void LockedUsersGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
LockedUsersGridView.EditIndex = e.NewEditIndex;
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}

protected void LockedUsersGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
LockedUsersGridView.EditIndex = -1;
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}

protected void LockedUsersGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox userName = LockedUsersGridView.Rows[e.RowIndex].FindControl("UserNameTextBox") as TextBox;

if (userName != null)
{
MembershipUser user = Membership.GetUser(userName.Text.Trim());
user.UnlockUser();
Membership.UpdateUser(user);
}

LockedUsersGridView.EditIndex = -1;
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}

protected void LockedUsersGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
LockedUsersGridView.PageIndex = e.NewPageIndex;
LockedUsersGridView.DataSource = GetLockedUsers();
LockedUsersGridView.DataBind();
}


Hopefully you’ll find this useful as a basis for creating a more advanced admin screen for user management.


image


image


image


image


image


image

DisplayLockedUsers.zip

Monday, December 21, 2009

Optimized Cable Experience

I just thought I’d take a moment and share the experience I had with Optimized Cable Company. I was searching for a set of HDMI-DVI and DVI-DVI cables for two monitors and decided to try the products of Optimized Cable Company. I found their selection of cables to be of high quality and their prices to be competitive. What prompted me; however, to write about this was the excellent customer service they provided. So often we are quick to post and talk about our bad experiences and rarely do we share the positive experiences we have with companies.

The positive experience I had with Optimized Cable Company is one of those great experiences you rarely hear about. When I ordered my set of cables, which were delivered very quickly (I might add), I realized I had not paid close enough attention to the connectors. One of my monitors had an HDMI connector, while the other had DVI; however, both of my video cards had DVI connectors. When I realized my ordering error I promptly called them and explained my mistake and they said to just send them back the incorrect cable and they would promptly send me the correct cable, which was slightly more expensive than the one I originally ordered. They did an even exchange and I received the cable I intended to purchase at no additional cost to me or hassle.

Based on the quality of the cables I received, prompt delivery, and the ease of doing business with them. I will direct my future needs for cables to them and highly recommend them for all of your cable needs.

Thank you Optimized Cable Company!

Optimized Cable Company

http://www.optimization-world.com/