Strange Guid.NewGuid() behaviour - asp.net

I have searched the site for an answer to this question, but I cannot seem to figure this one out.
I have use the NewGuid() method many times and it has worked greate. But now for some reason it creates an empty Guid.
Here is my code:
// Class of the Guid Object
public class CardUserAccount
{
// User ID of the user's profile
public Guid UserId { get; set; }
}
//Page object where method is called
Public partial class CreateSale : System.Web.UI.UserControl
{
// Create the UserProfile object
public CardUserAccount profile = new CardUserAccount();
protected void ContinueButton_Click(object sender, EventArgs e)
{
Guid _userId = Guid.NewGuid();
profile.UserId = _userId;
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
// Method to add object to database
SubmitProfile(profile);
}
I then call a simple linq to entities method to add the object to the entity object.
I have double checked it and I am not overwriting it anywhere.
However could it be a problem that I am creating the profile object outside of the page_load method. I thought this would not affect the object during postback.
I would appreciate the help

Is this actual code? Because you declare and initialize the variable, then do nothing with it.
If you intend to overwrite a field value, you should not declare that field inside this method.

Related

Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'WebApplication.Title via a reference conversion, boxing conversion,

here is the situation.
-There are two listboxes(lb1-lb2). In one(lb1) all data displayed that taken from database.
-When I want to click data from lb1 the content has to be displayed in other listbox(lb2).
-They are two different tables that has relationship in database.
-I've used entity framework and to reach objects of datables I did object initializer.
-I've handeld the selectedIndexChanged property to provide that dynamism I've done the following code
Title choosen;
private void lb1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lb1.SelectedIndex == -1) return;
choosen = lb1.SelectedItem as Title; //underlines and gives error in here
}
it throws an error as: Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'WebApplication2.Title' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
What should I do? What am I missing? thanks for your help
you Cannot convert type 'System.Web.UI.WebControls.ListItem' to your class Title
try this
Title choosen;
private void lb1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lb1.SelectedIndex == -1)
return;
choosen.name = lb1.SelectedItem.Text;//set object properties
choosen.value= lb1.SelectedItem.Value;
}
public class Title { //your Title class has some properties so..i assume some properties
public string name { get; set; }
public string value { get; set; }
}
You can't directly convert SelectedItem to Title
try below
choosen = new Title(){ TitleText = lb1.SelectedItem.Value};
I assume you have column called TitleText in your title table, change as you need

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

EF: Update entity stored in session

I'm using EF 5 with Web Forms (ASP.NET 4.5), with the "one DbContext instance per request" approach.
But this situation is a bit complicated: I have a multi-step create/edit screen, and I store the current entity in Session, then I manipulate it and in the final step, I commit it to the Database.
Creating a new instance was fine, but I can't for the life of me edit an existing entity... Because it's another request, my original DbContext instance was lost and when I attach it to a new one, I get the An entity object cannot be referenced by multiple instances of IEntityChangeTracker error.
My code is far too complex to post here, but I'll try and summarize it accurately:
My DbContext:
public class AppContext : DbContext
{
// DbSet declarations...
public static AppContext Current {
get { var context = HttpContext.Current.Items["Contexts.AppContext"] as AppContext;
if (context == null)
{
context = new AppContext();
HttpContext.Current.Items["Contexts.AppContext"] = context;
}
return context;
}
}
}
An example of what the page code looks like:
protected void Page_Load(object sender, EventArgs e)
{
int? id = null; // After this, I try to get it from the QueryString, parse it, etc.. Omitted for sake of brevity
// If I have an ID, it means I'm editing...
Session["Product"] = id.HasValue ? new Product() : AppContext.Current.Products.Find(id));
MethodToPopulateFields(); // Internally, it uses the Session variable
}
protected void Step1(){ // through n
// Manipulates the Session["Product"] based on page input...
}
protected void Save(){
var product = Session["Product"] as Product;
if(product.ID == 0)
product = AppContext.Current.Products.Add(product);
// throws an exception:
// AppContext.Current.Entry(product).State = EntityState.Modified;
// this too:
// AppContext.Products.Attach(product);
AppContext.Current.SaveChanges();
}
I know I can get the old entity from the database, update it manually and save, all in the last step, but I really don't want to do that...
Thank you.
Try calling
AppContext.Current.Entry(product).State = EntityState.Detached;
in the first method.

Why does HttpContext.Current need to used within a class, but not a method

For instance if I'm inside the Page_Load method and I want to get query string data I just do this:
public partial class Product_Detail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["p"];
}
}
but if I am inside the class, but not within any method I have to use:
public partial class Product_Detail : System.Web.UI.Page
{
string id = HttpContext.Current.Request.QueryString["p"];
protected void Page_Load(object sender, EventArgs e)
{
}
}
Why is that?
Member variable initialisers - which is what your id assignment is -- can't use instance methods or properties. Page.Request is an instance property, and therefore isn't available to member initialisers.
I would surmise it is because class members are not created until the class is instantated. Because of this you cannot access the Request property except within your class methods.
Properties of the current class (including this) are not accessible until the constructor. Since field initializers happen before the constructor is executed, properties (and fields, and methods) are not accessible.
You cannot refer to an instance's properties for a field's initializer—when the field is initialized the instance isn't fully constructed yet (i.e., there's no this pointer).

Password Field with Asp.Net Dynamic Data

I have a User table that I want to use with Dynamic Data. The Problem is that I have the Password Field that I need to encrypt using MD5. I am Using Entity Framework, How I do this?
On alternate idea would be to create a custom FieldTemplate (use UIHint to override the field field template) to encrypt this field.
I found this solution, but If anyone has a better Idea, let me know
public partial class SigecRendicionesEntities
{
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges
+= new EventHandler(context_SavingChanges);
}
// SavingChanges event handler.
private static void context_SavingChanges(object sender, EventArgs e)
{
// Validate the state of each entity in the context
// before SaveChanges can succeed.
foreach (ObjectStateEntry entry in
((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified))
{
// Find an object state entry for a SalesOrderHeader object.
if (entry.Entity.GetType() == typeof(Usuario))
{
Usuario usr = entry.Entity as Usuario;
string hashProvider = "MD5CryptoServiceProvider";
usr.Clave = Cryptographer.CreateHash(hashProvider, usr.Clave);
}
}
}
}

Resources