LINQ to SQL in silverlight exception - sql

This is a continution of my previous question: Could not find an implementation of the query pattern
Now I managed to query my database I can't seem to get the content on my webpage.
I try to return the code using the following code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new Service1Client();
client.GetPersoonByIDCompleted += new EventHandler<GetPersoonByIDCompletedEventArgs>(client_GetPersoonByIDCompleted);
client.GetPersoonByIDAsync("1");
}
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
textBox1.Text = e.Error.ToString();
else
label1.Content = e.Result.Voornaam.ToString();
}
However when I press the button I get the following errors:
Object reference not set to an instance of an object.
at
SilverlightApplication1.MainPage.client_GetPersoonByIDCompleted(Object
sender, GetPersoonByIDCompletedEventArgs e) at
SilverlightApplication1.ServiceReference1.Service1Client.OnGetPersoonByIDCompleted(Object
state)
The weird thing is it works when I do not use LINQ, but normal SQL.
string sql = "SELECT ID, naam, voornaam, leeftijd FROM tblPersoon WHERE id=#pmID";
Persoon pers = null;
string connstr = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connstr))
{
SqlCommand com = new SqlCommand(sql, cn);
com.Parameters.AddWithValue("pmID", id);
cn.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
pers = new Persoon();
pers.ID = reader.GetString(0);
pers.Naam = reader.GetString(1);
pers.Voornaam = reader.GetString(2);
pers.Leeftijd = reader.GetInt32(3);
}
}
return pers;
}
LINQ result:
SQL result:
Thank you for helping me, I grealy appreciate it!
Thomas

You get that particular exception by trying to reference the "e.Result" property when it's not valid, i.e., when the method call returned an exception instead of a value. Before you reference e.Result, confirm that e.Error == null, and if it doesn't, indulge yourself in some error handling or messaging code, e.g.:
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An error occurred: " + e.Error.ToString());
}
else
{
label1.Content = e.Result;
}
}
Or something of that sort.

Related

How do I define a data source for a panel?

I was trying to display a table that is being saved in my sql server and I wanted it to be displayed in my panal but it kept showing this error saying 'panel' doesnot contain a definition for 'Datasource' and no extension method 'datasource' accepting a first argument of type 'panel' could be found (are you missing a using directive or an assembly reference?) please help..
public partial class Form17 : Form
{
public Form17()
{
InitializeComponent();
ShowTGBtbl();
}
private void button5_Click(object sender, EventArgs e)
{
}
private void Form17_Load(object sender, EventArgs e)
{
int w = Screen.PrimaryScreen.Bounds.Width;
int h = Screen.PrimaryScreen.Bounds.Height;
this.Location = new Point(0, 0);
this.Size = new Size(w, h);
}
SqlConnection Con = new SqlConnection(#"Data Source=LAPTOP-9514GUKU\SQLEXPRESS;Initial Catalog=Mydatabase.com;Integrated Security=True");
private void ShowTGBtbl()
{
Con.Open();
string Query = "select * from TGBtbl";
SqlDataAdapter sda = new SqlDataAdapter(Query, Con);
SqlCommandBuilder Builder = new SqlCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
TGBoverall.Datasource = ds.Tables[0];
Con.Close();
}

ADO.net Performing Multiple queries (ExecuteQuery & ExecuteScalar) and displaying the result in a web form control

Hey wish you all to have a happy holiday,
I am trying to display multiple query results from a SQL database table to a grid view control and a label. I have no problem with the grid view result, but the result from the ExecuteScalar command is not displaying inside my lable control with an ID="myCount". I could not figure out what went wrong with my code. I need your help.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MBSDB"].ConnectionString);
try {
conn.Open();
string query="SELECT * FROM tblBook";
using (SqlCommand mycmd = new SqlCommand(query, conn)) {
myGrid.DataSource = mycmd.ExecuteReader();
myGrid.DataBind();
}
string query2 = "SELECT count(title) FROM tblBook";
using (SqlCommand mycmd2 = new SqlCommand(query2, conn)) {
int count = (int)mycmd2.ExecuteScalar();
myCount.Text = count.ToString();
}
}
catch {
Exception(e);
}
finally { conn.Close(); }
}
Are you sure about there is no error. I think, the error occured and handling in the catch block and you are unaware of it.
You should change it;
(int)mycmd2.ExecuteScalar();
to
Convert.ToInt32(mycmd2.ExecuteScalar());
You can't unboxing an object like this; (int)mycmd2.ExecuteScalar()

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection

c# Object reference not set to an instance of an object error , tried to match textbox and databse value

i have a little problem in my code, i tried to match my textbox value to database, bu i get an error message ...
here is my codes:
my main code;
protected void btnAddNewTopic_Click(object sender, EventArgs e)
{
if (txtbAddNewTopic.Text == "")
{
MessageBox.Show("Please write topic!");
}
else if (goodob.Businness_Layer.AddNewTopic.NewTopicCheckSystem(txtbAddNewTopic.Text) == null)
{
MessageBox.Show("Your added topic is already in site!");
}
else
{
goodob.Businness_Layer.CreateNewTopic.crnewtopic(txtbAddNewTopic.Text);
MessageBox.Show("Your topic has successfully created!");
}
}
and my check code ;
public static goodob.Businness_Layer.AddNewTopic NewTopicCheckSystem(string topic)
{
goodob.Businness_Layer.AddNewTopic xyz = null;
string query = #"SELECT [topic_name]
FROM topic
WHERE topic_name = #topic";
goodob.Class1 connection1 = new goodob.Class1();
connection1.sqlcommand.CommandText = query;
SqlParameter topicparam = new SqlParameter("#topic_name", SqlDbType.VarChar);
topicparam.Value = topic;
connection1.sqlcommand.Parameters.Add(topic);
System.Data.SqlClient.SqlDataReader reader = connection1.sqlcommand.ExecuteReader();
if (!reader.HasRows)
{
connection1.close_connection();
return null;
}
return xyz;
}
i get an error in connection1.sqlcommand.CommandText = query; please help me!
You have done too much confusion in adding parameters,you should add your sqlparameter object i.e.topicparam insted of topic.
use #topic varibale on both places.
or alternativly you can try this short hand
cmd.Parameters.AddWithValue(" #topic",topic);
insted of
SqlParameter topicparam = new SqlParameter("#topic_name", SqlDbType.VarChar);
topicparam.Value = topic;
connection1.sqlcommand.Parameters.Add(topic);

Exception creating transaction after running sql server backup via SMO

I keep on getting the following error every time i try to create a new transaction after i have backed up my database using SMO (Sql Server Management Objects):
New transaction is not allowed because there are other threads running in the session.
I have created a little console app that demonstrates the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Data.SqlClient;
using System.Data;
namespace TestSMO
{
class Program
{
string username = "radandba";
string password = "belmont";
string servername = "e2idev\\e2isqlexpress";
string databaseName = "e2i";
string backupfilename = "c:\\e2i.bak";
Server server;
static void Main(string[] args)
{
Program prog = new Program();
prog.server = new Server(prog.servername);
prog.server.ConnectionContext.LoginSecure = false;
prog.server.ConnectionContext.Password = prog.password;
prog.server.ConnectionContext.Login = prog.username;
try
{
prog.server.ConnectionContext.Connect();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
return;
}
Console.WriteLine("Connected");
//prog.SelectData();
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.Database = prog.databaseName;
backup.Devices.Clear();
backup.Incremental = false;
backup.Devices.AddDevice(prog.backupfilename, DeviceType.File);
backup.BackupSetName = prog.databaseName + " database backup";
backup.BackupSetDescription = prog.databaseName + " database - Full backup";
backup.Initialize = true;
backup.CopyOnly = true;
backup.LogTruncation = BackupTruncateLogType.NoTruncate;
backup.CompressionOption = BackupCompressionOptions.Default;
backup.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Complete);
backup.Information += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(prog.backup_Information);
backup.PercentComplete += new PercentCompleteEventHandler(prog.backup_PercentComplete);
backup.SqlBackupAsync(prog.server);
}
void backup_PercentComplete(object sender, PercentCompleteEventArgs e)
{
Console.WriteLine("Backup progress: " + e.Percent);
}
void backup_Information(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
}
void backup_Complete(object sender, Microsoft.SqlServer.Management.Common.ServerMessageEventArgs e)
{
Console.WriteLine("Backup status: No:" + e.Error.Number + " Detail: " + e.Error.Message);
SelectData();
}
public void SelectData()
{
SqlConnection sqlCon = server.ConnectionContext.SqlConnectionObject;
try
{
if (sqlCon.State != System.Data.ConnectionState.Open)
sqlCon.Open();
SqlTransaction trans = sqlCon.BeginTransaction();
SqlDataAdapter adapter = new SqlDataAdapter("select * from version", sqlCon);
adapter.SelectCommand.Transaction = trans;
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row[0]);
}
trans.Commit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
sqlCon.Close();
}
Console.ReadLine();
}
}
}
You could try to enable MARS on connection (msdn about MARS)
In connection string should be: "MultipleActiveResultSets=true;"
As stated by Anders UP turned out it was the NoLogTruncation was affecting it.