asp.net webpages: Error when trying to save back to database if DB helper already used - webmatrix

I have an if statement which checks whether or not an entry exists in my DB.
The code correctly checks if an email address is already present, however if the email does not exist i get an error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding
on a null reference at CallSite.Target(Closure , CallSite , Object ) at
ASP._Page__footer_cshtml.Execute()
But if i remove the code that gets the existing email, these lines:
var getrecord = db.QuerySingle("Select Email from Registrations where email = #0", email);
emailexists = getrecord.email;
the data is saved back to the DB with no problems. Not sure if its because i'm using the same Db helper?
try
{
var db = Database.Open("MiniDB");
var getrecord = db.QuerySingle("Select Email from Registrations where email = #0", email);
emailexists = getrecord.email;
if (emailexists != ""){
msg = "This Email address is already registed";
saved = false;
}
else {
var insertCommand = "INSERT INTO Registrations (Email, Name, regDate) VALUES(#0, #1, #2)";
db.Execute(insertCommand, email, name, regDate);
saved = true;
}
}
catch (Exception ex)
{
msg = ex.ToString();
saved = false;
}

One thing I ran into while retrieving (then testing) values within my database in WebMatrix was, depending on the field within the database, that after querying the database and storing the value in a variable, "", null, and System.DBNull.Value were three different things and checking for empty string or simply null was throwing errors for me in much the same way as your example.
Hopefully, I am helping with this (this may not be your issue, but I know it stumped me under similar circumstances, for quite a while, as I had never seen DBNull before).
This DBNull value traveled from the database to the variable I assigned the field value to, as it was a Session Variable and treated like an object. I'm not sure if this DBNull value would still be allowed to be stored in a regular variable (and not converted to regular null). Also, I believe I was using binary data (images) at the time, not sure if that would make a difference either but...
In the end, for my code, when checking to see a field (in the database) was empty, null, etc. I used something like this (only with a session variable instead of your regular variable):
if (emailexists != "" && emailexists != null && emailexists != System.DBNull.Value)
{
//code goes here.
}
I hope this helps!

Related

OptionSetValueCollection not taking a null value. Throws Generic SQL error when setting up the value to null

I'm creating a new record in CRM plugin(by reading the data from a related record) and the data that I'm passing may / may not contain "OptionSetValueCollection". Whenever the value for the OptionSetValueCollection is null the IOrganization.Create is throwing a Generic SQL exception.
Currently I'm checking the submitted value for null and when not null I'm not submitting a value for the created object.
My question is why does OptionSetValueCollection not taking null? Is this a platform issue?
I've also tried creating a List<OptionSetValue> object and adding the incoming OptionSetValues from the OptionSetValueCollection and then passing it to the target attribute, tried passing in null and also used the null-coalescing operator all with no luck.
//Earlybound code
Account account = new Account(){
Name = newBrand,
new_accounttype = new OptionSetValue((int)new_AccountType.Brand),
TerritoryId = siteRequestRecord.new_territoryid,
new_category1 = siteRequestRecord.new_category1 ?? null,
};
if (category2 != null)
{
account.new_category2 = siteRequestRecord.new_category2;
}
service.Create(account);
Seems to be a long outstanding issue.
There is a bug related to multiselect optionset - if you set it to null during creation that will trigger an error. But the same code that sets field to null works fine during update.
So if you set it to null during Create just don't set field value and as a result you'll get blank value of a field.
If I understand you want to set Optionset to null. use below code it shall work and set null for your optionset
new_accounttype = null;

Oracle db gives ORA-01722 for seemingly NO REASON AT ALL

I'm trying to use an Oracle database with ado.net, and it is proving a painful experience. I use Oracle Client (Oracle.Data namespaces).
The following query runs fine from a query window:
UPDATE PRINT_ARGUMENT
SET VALUE = 'Started'
WHERE REQUEST_ID = 1 AND KEYWORD = '{7D066C95-D4D8-441b-AC26-0F4C292A2BE3}'
When I create an OracleCommand however the same thing blows up with ORA-01722. I can't figure out why.
var cmd = cnx.CreateCommand();
cmd.CommandText = #"
UPDATE PRINT_ARGUMENT
SET VALUE = :value
WHERE REQUEST_ID = :requestID AND KEYWORD = :key";
cmd.Parameters.Add(new OracleParameter("requestID", (long)1);
cmd.Parameters.Add(new OracleParameter("key", "{7D066C95-D4D8-441b-AC26-0F4C292A2BE3}");
cmd.Parameters.Add(new OracleParameter("value", "Started");
cnx.Open();
try { int affected = cnx.ExecuteNonQuery(); }
finally { cnx.Close(); }
When I inspect the command in the debugger, the parameters appear to have mapped to the correct types: requestID has OracleDbType.Int64, key and value are both OracleDbType.Varchar2. The values of the parameters are also correct.
This gets even stranger when you consider that I have other queries that operate on the exact same columns (requestID, keyword, value) using the same approach - and they work without a hiccup.
For the record, the column types are requestID NUMBER(10,0); key VARCHAR2(30); value VARCHAR2(2000).
According to Oracle, ORA-01722 'invalid number' means a string failed to convert to a number. Neither of my string values are numbers, neither of the OracleParameters created for them are numeric, and neither
By default, ODP.NET binds parameters by position, not by name, even if they have actual names in the SQL (instead of just ?). So, you are actually binding requestID to :value, key to :requestID and value to :key.
Correct the order of cmd.Parameters.Add in your code, or use BindByName to tell ODP.NET to use the parameter names.
Since you are using named parameters, you have to tell the Oracle client about it. Otherwise your parameters are mixed up (key is assigned to :value):
OracleParameter parameter = new OracleParameter("requestID", (long)1);
parameter.BindByName = true;
cmd.Parameters.Add(parameter);
It's a strange and unexpected behavior, but that's how it is.

Updating an Entity Without Saving the Data back to the Database

I have created a new query like the following
var pressData = from press in dataContext.Releases
select new
{
Heading = press.Heading,
Description = press.Desc,
DatePublished = press.PublishDate.ToString(),
Body = press.BodyContent,
ID=press.ReleaseID,
CreatedBy=press.CreatedBy
};
Later in the code I want to update the entity from a session variable, but not save any data back to the database. Here is the code I am trying to accomplish this with....
var edit = pressData.Where(a => a.Heading == sectionPreview.HeadingContent && a.ID == sectionPreview.tionID).FirstOrDefault();
if (edit != null)
{
//WONT LET ME UPDATE THE Body VALUE
edit.Body = sectionPreview.SectionContent;
}
The code aboves purpose is to look at pressData and replace the body content with the new body from a session variable(not shown here), but NOT save it to the db. I want pressData to be filtered and updated only in the entity. So when I bind it to the control in this case it binds the data stored in my session.
this.rptSections.DataSource = pressData;
this.rptSections.DataBind();
I am getting a complier error stating
Property or indexer 'AnonymousType#1.Body' cannot be assigned to -- it is read only.
I checked the entity model and nothing is read only not any fields not anything. I must be missing something?
Anonymous Types encapsulate a read only property collection - for more information, read here. The compiler rewrites anonymous types as a constructor injections, ie:
select new
{
Heading = press.Heading,
Description = press.Desc,
DatePublished = press.PublishDate.ToString(),
Body = press.BodyContent,
ID=press.ReleaseID,
CreatedBy=press.CreatedBy
};
Is really rewritten as:
new Anonymous`1(press.Heading, press.Desc, press.PublishDate.ToString(), press.BodyContent, press.ReleaseID, press.CreatedBy)
And the properties are read only (public get, private / protected set, to use an easy comparison). If you want to solve your issue, instead of taking the data and making an anonymous object, create a real type and set properties on it.

SqlDateTime overflow thrown by Typed DataSet Insert

I'm using a Typed DataSet with an Insert statement; I have a table that has a smalldatetime field defined to accept null values. When I insert from a .NET 2.0 FormView, I get a "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."
Now, I've read this post, and the parameter as sent to the class constructor is defined as
global::System.Nullable<global::System.DateTime> DoB
So, it looks like it should accept a Nullable obj. Additionally, the generated code is testing the value sent.
if ((DoB.HasValue == true)) {
command.Parameters[6].Value = ((System.DateTime)(DoB.Value));
}
else {
command.Parameters[6].Value = global::System.DBNull.Value;
}
Specifically, the error is occurring when generated SqlClient.SqlCommand.ExecuteScalar() runs:
try {
returnValue = command.ExecuteScalar();
}
So, I guess my question is: how do I use a Typed DataSet to set a blank value (passed from a FormView on CommandName=Insert) to a null in a database?
Ok, so here's what worked for me. First, to reiterate, I've got a Typed DataSet with DataAdapters that's generating the ADO objects. So, on my page, I can create a ObjectDataSource with the type that points to my adapter, and then name the different access methods housed there-in.
No, I have an Insert to a table where basically all the columns are nullable; some varchar, some smalldatetime.
When I submit an empty form, I'd like nulls to be entered. They're not and lots of various errors are thrown. What I ended up doing is subclassing the ObjectDataSource to gain access to the Inserting event. (subclassed for reusability) In the Inserting event, I looped through the InputParameters, and if it was a string and == "", I set it to null. Also, you cannot set ConvertNullToDBNull to true; that causes the strings to fail. This successfully allowed the Nullable to remain null.

LINQ not updating on .SubmitChanges()

Is there any reason something like this would not work?
This is the logic I have used many times to update a record in a table with LINQ:
DataClasses1DataContext db = new DataClasses1DataContext();
User updateUser = db.Users.Single(e => e.user == user);
updateUser.InUse = !updateUser.InUse;
db.Log = new System.IO.StreamWriter(#"c:\temp\linq.log") { AutoFlush = true };
db.SubmitChanges();
(updateUser.InUse is a bit field)
For some reason it isn't working. When I check the linq.log it is completely blank.
Could there be a problem with my .dbml? Other tables seem to work fine but I've compared properties in the .dbml and they all match.
It's as if the db.SubmitChanges(); does not detect any updates being required.
The table could not be updated properly because it had no primary key. (Actually it had the column but the constraint was not copied when I did a SELECT INTO my dev table). The DataContext class requires a primary key for updates.
Is the InUse property a "normal" one as far as LINQ is concerned? (e.g. it's not autogenerated or anything funky like that?)
Alternatively, I don't suppose it's a Nullable<bool> is it, with a current value of null? If so, your update line isn't actually doing anything - for nullable Booleans, !null = null.

Resources