protected void UploadImage_Click(object sender, EventArgs e)
{
HttpPostedFile postedFile = ImageUploader.PostedFile;
string fileExtension =
Path.GetExtension(Path.GetFileName(postedFile.FileName));
if (ImageUploader.HasFile && fileExtension.ToLower() == ".jpg" ||
fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
{
Stream fs = postedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] image = br.ReadBytes((int)fs.Length);
Guid UserId = (Guid)Membership.GetUser().ProviderUserKey;
string cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
string sqlcmd = "insert into ProfileImage values(@UserId, @ImageData)";
SqlCommand cmd = new SqlCommand(sqlcmd, con);
cmd.Parameters.AddWithValue("@UserId", UserId);
cmd.Parameters.AddWithValue("@ImageData", image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
ErrorLabel.Visible = true;
ErrorLabel.Text = "Upload Success!";
ErrorLabel.ForeColor = System.Drawing.Color.Green;
}
}
else
{
ErrorLabel.Visible = true;
ErrorLabel.Text = "Upload failed: Only jpg, gif, and png allowed.";
ErrorLabel.ForeColor = System.Drawing.Color.Red;
}
Above is the code I am using to upload a file to the database for a user image. I need to know how to write a unit test that can return a GUID and not a null value to ensure the code works as intended.
Essentially, I want to add the currently logged in user userid from the membership provider as well as the uploaded image to the database so it can be easily retrieved later. When I test it by modifying the database to accept something other than the uniqueidentifier and the code to insert a temp userid, the insertion works. But now I want to make sure that I can actually obtain the currently logged in userid and add that to the database.
When I test this code, it says for the error that the
Guid UserId = (Guid)Membership.GetUser().ProviderUserKey
part is returning a null value, even if I add a user to the membership tables. How can I properly test the retrieval of a currently logged in user userid?