How to establish a connection through microsoft sql server using code behind? - asp.net

I am having a problem with my asp.net project setting up a connection to the ms sql server.
Here's my aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OnlineAppSyss.aspx.cs" Inherits="SoftwareAnalysisAndDesign.SAD.OnlineAppSyss" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Online AppSyss System</title>
<meta charset="utf-8"/>
<link rel="stylesheet" href="css/style.css" />
<script src="js/index.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body bgcolor="#339966">
<div class="wrapper">
<div class="container">
<h1>Welcome to Online AppSess System</h1>
<form id="form1" runat="server">
<input type="text" id="Username" runat="server" placeholder="Username" />
<input type="text" id="Password" runat="server" placeholder="Password" />
<button type="submit" id="login-button" onserverclick="Button1_Click">Login</button>
</form>
</div>
</div>
<ul class="bg-bubbles">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
And my aspx code behind:
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 System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareAnalysisAndDesign.SAD
{
public partial class OnlineAppSyss : System.Web.UI.Page
{
public class MSConnector
{
public String ConnectionString { get; set; }
public DataSet ExecuteQuery(String sqlStatement)
{
try
{
DataSet results = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(sqlStatement, conn))
{
da.Fill(results);
}
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
return results;
}
catch (Exception ex)
{
throw ex;
}
}
}
public static string query = null;
private DataSet selectedData;
private DataTable dt;
private MSConnector connector = new MSConnector();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Login();
}
public void Login()
{
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=KEITH;UID=KEITH/LaurenceKeith;Password=;DATABASE=Student;";
string username = (this.Username.Value);
string password = (this.Password.Value);
if (username == "" && password == "")
{
query = "select * from Student where StudentID = 2011017997'";
query = "select * from Student where Password = 'lalbano' '";
}
}
}
}
this is my code for setting up a connection using this class MSConnector
public class MSConnector
{
public String ConnectionString { get; set; }
public DataSet ExecuteQuery(String sqlStatement)
{
try
{
DataSet results = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
using (SqlDataAdapter da = new SqlDataAdapter(sqlStatement, conn))
{
da.Fill(results);
}
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
return results;
}
catch (Exception ex)
{
throw ex;
}
}
}
I can't retrieve my data in my database even though I have no error in my code behind.
Is there a problem with my connection string? I don't have a password in my ms sql server though. Is this the correct code of connection string? Please Help.
//ConnectionString for accessing into MSSql
connector.ConnectionString = "SERVER=KEITH;UID=KEITH/LaurenceKeith;Password=;DATABASE=Student;";

Try this as connection string, will use Windows Authentication for login.
connector.ConnectionString = "data source=KEITH;initial catalog=Student;Integrated Security=SSPI;providerName=System.Data.SqlClient";
This is assuming Keith is your SQL server and the database is Student

Related

How to save and retrieve image from database in ASP.NET

I want to show image in image control on page load. I'm using the following code. My problem is that the image is saved in the database as binary data, but I can't retrieve the image in the image control
public partial class TeacherProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
profilepic();
}
protected void upload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
Byte[] imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
SqlCommand cmd = new SqlCommand("Update Registration set Photo = '" + imgbyte + "' where id ='" + idd.Text + "' ", con);
//cmd.Parameters.AddWithValue("#userid", 222); //image id
//cmd.Parameters.AddWithValue("#pic", imgbyte);
//try
//{
con.Close();
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image Uploaded";
con.Close();
//}
//catch
//{
// Label1.Text = "Try Again";
//}
}
}
public void profilepic()
{
SqlCommand cmd2 = new SqlCommand("select Photo from Registration where Username = '" + username1.Text + "'", con);
//cmd2.Parameters.AddWithValue("#userid", username1.Text);
con.Open();
SqlDataReader dr = cmd2.ExecuteReader();
if (dr.Read())
{
byte[] bytes = (byte[])dr["Photo"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image1.ImageUrl = "data:image/png;base64," + base64String;
cmd2.ExecuteNonQuery();
con.Close();
}
else
{
}
}
}
Can anybody help me please?
Thanks in advance...
my code for file upload
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="fileUpload.aspx.cs" Inherits="fetchImage.fileUpload" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
margin-left: 0px;
}
.auto-style2 {
margin-left: 6px;
margin-top: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<div>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto- style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style2" OnClick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
file upload cs:
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 System.Data.SqlClient;
namespace fetchImage
{
public partial class fileUpload : System.Web.UI.Page
{
string path;
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Request.PhysicalApplicationPath + "/Images/"+ FileUpload1.FileName.ToString());
path = "Images/"+FileUpload1.FileName.ToString();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Images values('"+path.ToString()+"','"+TextBox1.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
}
}
}
for showing the file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ShowImage.aspx.cs" Inherits="fetchImage.ShowImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<img src="<%#Eval("image_path") %>" height="100" width="100" />
<td><%#Eval("title") %></td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>
file show cs :
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 System.Data.SqlClient;
namespace fetchImage
{
public partial class ShowImage : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP- U0NOKBP\\SQLEXPRESS;Initial Catalog=Lnmi;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Images";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataList1.DataSource = dt;
DataList1.DataBind();
con.Close();
}
}
}
please create a table before proceeding
create table Images(image_path varchar(MAX), title varchar(50));
and lastly add a folder Images in your project by right clicking at your project name

Database notification using signalr and asp.net not displaying the data in UI

i followed the tutorial to from one of the online blog and am able get the application out with out error, but main issue is its not giving error as well as output.
My hub class looks like this
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
My ASPX.CS page looks like this
protected void Page_Load(object sender, EventArgs e)
{
SendNotifications();
}
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[MessageBuffer]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
and My aspx page is --
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
$('#newData').append('<li><strong>' + msg + '</li>');
};
$.connection.hub.start();
});
</script>
<div style="padding:10px 0px 10px 10px">
New Messages:
<ul id="newData"></ul>
</div>
</body>
</html>
i have done different samples, i have used same format to display, i am able to get those out in a hand, but here i am stuck with this. i am getting value in aspx.cs page, it calling the DB, which i have given in global.asax. and i have added sqldependency as well, enbabled broker in DB. but issue is still there. i cant see anything in UI.
Thanks in advance
I had a similar problem a while back. I just used the hub method name attribute and it worked for me. So you want something like
[HubMethodName("SendNotifications")]
public string SendNotifications()
And then at the front end just do
$.connection.hub.start(function () {
notify.server.SendNotifications();
});
Update
You could have a span the way I have in my code. so something like
<div>
<ul>
<li>New Messages:<span id="newData">0</span></a></li>
</ul>
</div>
Then do
$('#newData').text(msg);

Format of the initialization string does not conform to specification starting at index 0 during debug

On page load I am extracting the parameter from the query string and inserting into the database.
here is the web.config file
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="MyConsString" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=MCAS_TEST;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
Here is my aspx page coding
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample Configuration Page</title>
<style type="text/css">
.style1
{
width: 100%;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td>IP_Address:</td>
<td>
<asp:TextBox ID="x" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>MAC_Address:</td>
<td>
<asp:TextBox ID="y" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" Text="Save"/>
</form>
</body>
</html>
The C# Code behind the aspx page is
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["x"] != null)
{
insertData();
}
}
public void insertData()
{
using (SqlConnection con = new SqlConnection("MyConsString"))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(#x, #y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
// Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
Response.Write("Unable To Save Data. Error - " + Ex.Message);
}
}
}
}
Now while executing it I am having error that Format of the initialization string does not conform to specification starting at index 0.
I am not getting why...
I modified my own code after some research which is as follows and it worked..
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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["x"] != null)
{
if (Request.QueryString["y"] != null)
{
insertData();
}
}
// else
// {
// Response.Redirect("http://localhost:53627/Default.aspx");
// }
}
public void insertData()
{
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
con.Open();
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Test(x, y) VALUES(#x, #y)", con))
{
cmd.Parameters.Add(new SqlParameter("x", Request.QueryString["x"]));
cmd.Parameters.Add(new SqlParameter("y", Request.QueryString["y"]));
cmd.ExecuteNonQuery();
}
}
catch (Exception Ex)
{
// Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
Response.Write("Unable To Save Data. Error - " + Ex.Message);
}
}
}
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
}
}

pass value from ashx to aspx page

I have written the fallowing ashx code. for autocomplete textbox.
i want to transfer the values ContactId, ContactName from ashx to code behind in aspx file.
how can i do that
code for ashx file
<%# WebHandler Language="C#" Class="Search_CS" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
public class Search_CS : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactId, ContactName from Customers where " +
"ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
StringBuilder sb = new StringBuilder();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
sb.Append(sdr["ContactName"])
.Append(Environment.NewLine);
}
}
conn.Close();
context.Response.Write(sb.ToString());
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
code for aspx file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtSearch.ClientID%>").autocomplete('Search_CS.ashx');
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
try this
in aspx page
<div>
<script type="text/javascript">
function get_look_suggs(key, cont) {
var script_name = 'Search_CS.ashx';
var params = { 'q': $("#<%=txtSearch.ClientID%>").val() }
$.get(script_name, params,
function (obj) {
// obj is just array of strings
var res = [];
for (var i = 0; i < obj.length; i++) {
res.push({ id: i, value: obj[i].Name });
}
// will build suggestions list
cont(res);
},
'json');
}
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete({ ajax_get: get_look_suggs });
});
</script>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</div>
in handler
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System;
using System.Data;
public class Search_CS : IHttpHandler
{
private readonly JavaScriptSerializer js = new JavaScriptSerializer();
public class names
{
public names(string p)
{
// TODO: Complete member initialization
this.Name = p;
}
public string Name { get; set; }
}
// Handle request based on method
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["q"];
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ContactId, ContactName from Customers where " +
"ContactName like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<names> lstnew = new List<names>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
lstnew.Add(new names(sdr["ContactName"].ToString()));
}
}
conn.Close();
string jsonObj = js.Serialize(lstnew);
context.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
context.Response.Write(jsonObj);
context.Response.ContentType = "application/json";
}
}
}
}

Binding command-based SQLite to a data source?

I'm trying to use SQLite in my application, and it's been bumpy. A few things, first off.
Due to having VS 2008 Express, SQLite design-time support is nonexistent. I've done some reading and i'm rather confused about how to use command-based sql connections with standard data controls, ie gridview. If the views ask for data sources, what data source do I choose to use my custom SQL statements with? And how do I choose it, given that I can't use the design time support?
Thank you,
Cameron
I've never used design support in Visual Studio and with SQLite I wonder if it is possible at all so I would suggest you to get into coding :-) Here's a sample illustrating the basic ideas. You start off by creating your database:
Global.asax:
public class Global : System.Web.HttpApplication
{
public string GetDbFile()
{
return Path.Combine(Server.MapPath("~/App_Data"), "data.db3");
}
public string GetConnectionString()
{
return "Data Source=" + GetDbFile() + ";Version=3;";
}
protected void Application_Start(object sender, EventArgs e)
{
var dbFile = GetDbFile();
if (File.Exists(dbFile))
{
File.Delete(dbFile);
}
ExecuteCommand("create table users (usr_id integer primary key, usr_name string)");
ExecuteCommand("insert into users (usr_id, usr_name) values (1, 'user 1')");
ExecuteCommand("insert into users (usr_id, usr_name) values (2, 'user 2')");
}
public void ExecuteCommand(string sql)
{
using (var connection = new SQLiteConnection(GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
Of course you could skip this step if you already have an SQLite database file. You won't need to recreate it every time your application starts :-)
Once you have the database filled with data you could show it in a grid.
default.aspx:
<%# Page Language="C#" %>
<%# Import Namespace="System.Linq" %>
<%# Import Namespace="System.Collections.Generic" %>
<%# Import Namespace="System.Data.SQLite" %>
<script type="text/C#" runat="server">
private class User
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
usersGrid.DataSource = GetUsers();
usersGrid.DataBind();
}
}
private IEnumerable<User> GetUsers()
{
using (var connection = new SQLiteConnection(ApplicationInstance.GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select usr_id, usr_name from users";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new User { Id = reader.GetInt32(0), Name = reader.GetString(1) };
}
}
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="usersGrid" runat="server" />
</div>
</form>
</body>
</html>

Resources