How to save collapsed layout of AspxPivotGrid to SQL Database? - asp.net

I am using divexpress pivotgrid control.
I want to do save and restore the layout. I can do that simply by using Session.
But I don't know how to save it into my SQL Database.
This code without database
UPDATED
protected void ASPxButton1_Click(object sender, EventArgs e)
{
Session["Layout"] = ASPxPivotGrid1.SaveLayoutToString();
MemoryStream stream = new MemoryStream(byteArray);
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO [HQWebMatajer].[dbo].[ReportSave]([UserID],[ReportName],[UserFileName],[ReportData])VALUES('faisal.3012','TotalSales','faisalxxx',#ReportData)";
cmd.Parameters.AddWithValue("#ReportData", stream);
con.Open();
cmd.ExecuteNonQuery();
}
//divServer.InnerHtml = Session["Layout"].ToString();
}
protected void ASPxButton2_Click(object sender, EventArgs e)
{
string text = "";
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'";
con.Open();
string xxx = cmd.ExecuteScalar().ToString();
StreamReader reader = new StreamReader(xxx);
text = reader.ReadToEnd();
}
ASPxPivotGrid1.LoadLayoutFromString(text);
}
UPDATE: Saving to database is working, but when i try to restore from database it throws the following error
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\System.Byte[].
on this line
StreamReader reader = new StreamReader(xxx);
I don't know any idea about how to convert and where to convert. The same question asked in devexpress in this link.. They referred to this stackoverflow. But the convertion I don't understand how to make it into my scenario.
Thanks

select reportdata from [HQWebMatajer].[dbo].[ReportSave] where UserID='faisal.3012'
You check what is the output of the above line in the DB.
You may have not initialized the variable byteArray with grid data. Break code at
MemoryStream stream = new MemoryStream(byteArray);
and check what you are storing in to DB.

Related

Updating database from ASP.Net getting error "Connection property has not been initialized"

I am trying to retrieve a value from my database, increment it by 1, and then update the database with this new value.
My code so far is
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand cmd = new SqlCommand("Select likeCount from tbl_Post where tbl_Post.Id="+Convert.ToInt16(content) , conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
int oldVal = Convert.ToInt16(dr["likeCount"]);
int newVal = oldVal + 1;
SqlCommand insert1 = new SqlCommand("update tbl_Post set
likeCount="+newVal+ "where tbl_Post.Id=" + content);
insert1.ExecuteNonQuery();
conn.Close();
}
I am getting an error on the line insert1.ExecuteNonQuery
ExecuteNonQuery: Connection property has not been initialized.
The reason of your error is the missing connection in the second command. You can add it to the SqlCommand constructor as you do in the first command, also you have a missing space in the query text for the second command.
These errors and a more serious error called Sql Injection could be avoided if you use parameters like explained in the code below
Least but probably most important is the fact that you don't need two commands to increment the likeCount field. You can write a single command
protected void Button1_Click(object sender, EventArgs e)
{
string content = Request.QueryString["ContentID"];
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["dbmb17adtConnectionString"].ConnectionString;
string updateText = #"update tbl_Post
set likeCount=likeCount + 1
where tbl_Post.Id=#id";
using(SqlConnection conn = new SqlConnection(connStr))
using(SqlCommand cmd = new SqlCommand(updateText, conn);
{
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt16(content);
cmd.ExecuteNonQuery();
}
}
Notice also the presence of the using statement around the disposable objects like connection and commands. This allows you to close and dispose these objects also in case of exceptions.

Insert a column value to database using session

I want to insert a value into a table which comes from a session variable.The code that i have written is:
protected void Button1_Click(object sender, EventArgs e)
{
double balance;
double reward;
if((double.TryParse(lblBalance.Text, out balance) && (double.TryParse(lblReward.Text, out reward))))
{
Session["FinalBalance"] = balance + reward;
}
else
{
// some kind of error handling
}
string CS = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister('Balance') values('#FinalBalance')", con);
cmd.Parameters.AddWithValue("#FinalBalance", Session["FinalBalance"].ToString());
}
}
But when i click the submit button,the code doesnt throw any exception and doesnt insert the needful.What is the problem here?
You are making the command object but not executing the query. You have to call ExecuteNonQuery method on Command object to insert record.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into tblRegister(Balance) values(#FinalBalance)", con);
cmd.Parameters.AddWithValue("#FinalBalance", Session["FinalBalance"].ToString());
cmd.ExecuteNonQuery ();
}

Move pdf file from SQL database to local ASP.net

I am trying to move the saved pdf file in my database to my local drive. I cannot find a way to do it. When I click on button1 , the dialog save or open shows up. I want to save the file directly on my local drive. Any help ?
please note that reader["FileData"] contains my file.
protected void Button1_Click(object sender, EventArgs e)
{
string id = TextBox1.Text.TrimEnd();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * From FileInformation where Id=3";// +id + " ";
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Response.Clear();
//Response.Buffer = true;
Response.ContentType = reader["FileType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + reader["FileName"] + "\"");
Response.BinaryWrite((byte[])reader["FileData"]);
Response.Flush();
Response.End();
con.Close();
}
Any help on this ?

link data from Textbox to SQL Database in ASP.net (C#)

I am attempting to create a web form where data from several text box's will enter data into a n SQL database I have created. My code is listed below, and the problem is that when it compiles, it acts as if it hasn't. The messagedisplay.text does not change, and the SQL database does not update. Does anyone know a solution?
protected void createButton_Click(object sender, EventArgs e)
{
string state = stateTextBox.Text;
string country = countryTextBox.Text;
string lake = lakeTextBox.Text;
SqlConnection connection = new SqlConnection("Data Source=.MetricSample;Initial Catalog=ElementID;"+ "Integrated Security=true;");
connection.Open();
try
{
using (SqlCommand command = new SqlCommand(
"INSERT INTO ResearcherID VALUES(#ResearcherFname, #ResearcherLName)", connection))
{
command.Parameters.Add(new SqlParameter("ResearcherFName", country));
command.Parameters.Add(new SqlParameter("ResearcherLName", state));
command.ExecuteNonQuery();
}
messageDisplay.Text = "DB Connection Successfull";
}
catch
{
messageDisplay.Text = "DB Connection Failed";
}
}
try this
using (SqlCommand sqlCmd = new SqlCommand("INSERT INTO ResearcherID (FieldNameForFirstName, FieldNameForLastName) VALUES (#ResearcherFname, #ResearcherLName)", sqlConn)) {
sqlCmd.Parameters.AddWithValue("#ResearcherFname", country);
sqlCmd.Parameters.AddWithValue("#ResearcherLName", state);
}
Also use connection.Open(); inside try

Invalid attempt to call Read when reader is closed

I'm kind of struggling trying to get this datagrid to bind. Everytime I run my code, I get an error message stating, "Invalid attempt to call Read when reader is closed". I don't see where I am closing my reader. Can you please help me? My code for loading the datagrid is below:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
gridROI.DataSource = sqlReader;
gridROI.DataBind();
sqlReader.Dispose();
cmd.Dispose();
}
}
}
}
You can't use a SqlDataReader as a DataSource for a DataGrid.
From MSDN:
A data source must be a collection that implements either the
System.Collections.IEnumerable interface (such as
System.Data.DataView, System.Collections.ArrayList, or
System.Collections.Generic.List(Of T)) or the IListSource interface to
bind to a control derived from the BaseDataList class.
Datasource property:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedatalist.datasource.aspx
SqlDataReader:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
A common methodology to bind the query results to your datagrid would be to use a SqlDataAdapter to fill a DataTable or DataSet and then bind that to your DataGrid.DataSource:
protected void LoadGrid()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["VTC"].ConnectionString;
conn.Open();
string sql = "select * from roi_tracking";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill((DataTable)results);
gridROI.DataSource = results;
}
}
}
In addition to what pseudocoder said, you wouldn't want to bind to a SqlDataReader anyway: the connection to the database will remain open so long as the reader instance exists.
You definitely want to deserialize the data into some other disconnected data structure so that you release the connection back into the pool as quickly as possible.

Resources