How to add connection string dynamically in web.config - asp.net

I have to create one application which will add connection string in web.config when user clicks on some control.
actually it runs fine,
But now together with it i have to run one SQL script which will create new database.
for that i have write following code..
now it gives me error as
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Collections.Generic;
public partial class connectionString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnadd_Click(object sender, EventArgs e)
{
try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
// System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var section = config.GetSection("connectionStrings") as ConnectionStringsSection;
section.ConnectionStrings.Add(new ConnectionStringSettings(txtNAme.Text, txtNAme.Text, "System.Data.SqlClient"));
config.Save();
string sqlConnectionString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
FileInfo file = new FileInfo(#"G:\AAA\SCRIPT.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
}
catch (Exception ex)
{
}
}
}

Define the connection string in web.config
<ConnectionStrings>
<add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
</Connectionstrings>
Configuration is read only so you can not do it in obvious way like
ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";

Related

Retrieve name and image from database where image is stored as upload folder and reference is stored in database?

Trying the following code but could't get the desired result.
I have stored the image in the upload folder and its reference is saved in database while storing the data in the database from the admin side.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace Admin
{
public partial class fetch : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs =
ConfigurationManager.ConnectionStrings["DBSC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spUploadImage", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter ParamId = new SqlParameter()
{
ParameterName = "#Id",
Value = Request.QueryString["Id"]
};
cmd.Parameters.Add(ParamId);
con.Open();
byte[] Bytes = (byte[])cmd.ExecuteScalar();
string strBase64 = Convert.ToBase64String(bytes);
FileUpload1.ImageUrl = "data:image/png;base64, +strBase64";
}
}
}
}

System.Data.SqlClient.SqlException error at asp.net

I am new at asp.net. I was trying database connection. But I am getting this error. Please advice me.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = "Data Source=.;Initial Catalog=test;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(cs);
SqlCommand comma = new SqlCommand("select * from try", con);
con.Open();
GridView1.DataSource = comma.ExecuteReader();
GridView1.DataBind();
con.Close();
}
}
}
The issue is with the connection string you are using.
Data Source=.;Initial Catalog=test;Integrated Security=SSPI
Check the SQL Server instance name running on your local.
Data Source=**.\YourInstanceName**;Initial Catalog=test;Integrated Security=SSPI
You can test your connection string validity by trying to add a connection in Server Explorer (Tools -> Connect to Server - VS2015).
Good luck

Label not displaying the dropdownlist selected value

VS is giving error at this line:
Label1.Text = DropDownList1.SelectedItem.Text;
Error message says that object reference not set to an instance of the object. what could be the solution?
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace Login
{
public partial class ViewCourses : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string loginID = Convert.ToString(Session[0]);
DropDownList1.SelectedValue = loginID;
Label1.Text = DropDownList1.SelectedItem.Text;
}
}
}
I am guessing that DropDownList1.SelectedItem is null.
Put a breakpoint on that line and see what DropDownList1.SelectedItem's value is.
Are you familiar with the VS debugger and breakpoints?

PetaPoco orm tool with Asp.Net GridView

I am trying PetaPoco with my Asp.Net Project. How can I use PetaPoco with Asp.Net GridView. I am new at web programming.
I tried all code samples in the blog. They all are working with console app. But in Asp.Net I could not bind the datasource to GridView.
Thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using PetaPoco;
using northwind;
using System.Dynamic;
namespace Mng
{
public partial class Default : System.Web.UI.Page
{
public northwindDB db;
protected void Page_Load(object sender, EventArgs e)
{
db = new northwindDB();
if (!Page.IsPostBack)
{
var q = db.Query<Product>("SELECT top 10 * FROM Products");
grdMng.DataSource = q;
}
else
{
Response.Write("Postback occurs");
}
}
}
}
Call DataBind method to build the grid
grdMng.DataSource = q;
grdMng.DataBind();

Asp.net how to solve the error

Im designing my web page, in that i have typed in the book id and typed Nameofthebook. and then click the button the stack of book are available is go to another page and then not available is display the error message is book is not available My project (Library management system)
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class Bookcheck : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string constr = null;
constr = ConfigurationManager.ConnectionStrings["librarymanagementconnetionstring"].ConnectionString;
SqlConnection cnn = new SqlConnection(constr);
cnn.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT*FROM BOOKREGISTRATIONDETAILS WHERE bookId='" + txtid.Text.Trim() + "'AND Nameofbook='" + txtnb.Text.Trim() + "'", constr);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("Issueofbook.aspx");
}
else
{
Msg.Text = "NO book available";
Msg.Visible = true;
}
}
}
Error:
Object reference not set to an instance of an object.
I noticed that in librarymanagementconnetionstring, connection is spelled incorrectly. Is this the correct entry in your web.config for the connection string?
I'd say that it's the line
if (ds.Tables[0].Rows.Count > 0)
that giving the error.
If your DataSet has no tables then ds.Tables could be null.
If that's a possibility then you need to code for that.
If there are no rows ds.Tables[0].Rows won't be null and your test should work.
Change
if (ds.Tables[0].Rows.Count > 0)
to
if(ds.HasRows)

Resources