pass value from ashx to aspx page - asp.net

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";
}
}
}
}

Related

Signalr and Devexpress

I want to create a grid and automatic update it, when data changes in the database. It works with a simple table control.
public partial class index : System.Web.UI.Page
{
static string connectionString = #"Data Source=*******;initial catalog=Test;persist security info=True; Integrated Security=SSPI;";
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static IEnumerable<Person> GetData()
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
command.Notification = null;
SqlDependency.Start(connectionString);
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(Dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new Person(x.GetInt32(0), x.GetString(1))).ToList();
}
}
}
private static void Dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
MyHub.Show();
}
public void FillGrid()
{
List<Person> persons = new List<Person>();
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [Id],[Name] FROM [dbo].[Persons]", connection))
{
if (connection.State == ConnectionState.Closed)
connection.Open();
using (SqlDataReader rdr = command.ExecuteReader())
{
while (rdr.Read())
{
var id = rdr.GetInt32(0);
var name = rdr.GetString(1);
persons.Add(new Person(id, name));
}
}
}
}
grid.DataSource = persons;
grid.DataBind();
}
}
public class MyHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.displayStatus();
}
}
And the apsx Page :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.myHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData()
{
var $tbl = $('#tbl');
$.ajax({
url: '/index.aspx/GetData',
contentType: 'application/json;charset=utf-8',
datatype: 'json',
type: 'POST',
success: function (data) {
if (data.d.length > 0) {
var newdata = data.d;
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th></tr>');
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Name + '</td><td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table id="tbl"></table>
<dx:ASPxGridView ID="grid" runat="server"></dx:ASPxGridView>
</div>
</form>
</body>
</html>
However I want to use a Devepress Aspxgridview. The Devexpress Site states they don't support SignalR. However since the Javascript function is triggered when data changes in the database, is it possible somehow to force the client to get the data from the server? Force a postback and/or call the FillGrid method? ( To create the grid from js is not possible since the AspxgridView Control is much more complicated).
SOURCE: https://www.youtube.com/watch?v=30m-7wpmbrc
Although SignalR is not supported out of the box, it should be possible to manually notify the server side about the update using the existing API. You can send a callback to the server using the ASPxClientGridView.PerformCallback method, and handle the server side ASPxGridView.CustomCallback event to reload data from the SQL server.

How to establish a connection through microsoft sql server using code behind?

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

How to show Arabic style in Google charts

<%# Page Language="C#" AutoEventWireup="true" CodeFile="Ar_PieChart.aspx.cs" Inherits="Ar_PieChart" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv='content-type' content='text/html; charset=UTF-16' />
<meta name="viewport" content="width=device-height,minimum-scale=0.5,maximum-scale=3.0,user-scalable=yes" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Ar_PieChart.aspx/GetData',
data: '{}',
success:
function (response) {
drawVisualization(response.d);
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Column Value');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
}
new google.visualization.PieChart(document.getElementById('visualization')).draw(data, { is3D: true });
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="visualization" style="width: 600px; height: 350px">
</div>
</form>
</body>
</html>
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.Web.Services;
using MySql.Data.MySqlClient;
public partial class Ar_PieChart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Data> GetData()
{
MySqlConnection conn = new MySqlConnection("server=****;user id=****;Password=****;database=****");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "SELECT Class,COUNT(Class) FROM sh_report GROUP BY Class";
MySqlCommand cmd = new MySqlCommand(cmdstr, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data> dataList = new List<Data>();
string cat = "";
int val = 0;
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
dataList.Add(new Data(cat, val));
}
return dataList;
}
}
public class Data
{
public string ColumnName = "";
public int Value = 0;
public Data(string columnName, int value)
{
ColumnName = columnName;
Value = value;
}
}
I am getting chart perfectly but i am in need of Arabic style like reverse.
i mean while seeing the chart view in mirror.
If any one know the answer please help me.
Thanks in advance.

Need to change the format of data return from JSON

I'm creating a webservice which should get data from database(sql server) and return it.
Every thing working fine. But what I need is I need to display the data with the format which I needed.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
// public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT * FROM Contact e WHERE FirstName LIKE '%" + SearchTerm + "%'";
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(ds);
con.Close();
// Create a multidimensional array
string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in ds.Tables[0].Rows)
{
//EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Contactno"].ToString() };
EmpArray[i] = new string[] { "FNAME: " + rs["FirstName"].ToString(), "LName: " + rs["LastName"].ToString(), "Contactno: " + rs["Contactno"].ToString()};
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(EmpArray);
return strJSON;
}
catch (Exception ex) { return errmsg(ex); }
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Here is my output:
[["FNAME: devi","LName: priya ","Contactno: 965577796 "],
["FNAME: arun","LName: kumar ","Contactno: 9944142109"],
["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]
But I need the result in the following format:(which should contain curly braces and the word cargo at starting each name and value should start and end with double codes..
{ "Cargo": [ { "FNAME": "devi", "LName": "priya " },
{"FNAME": "arun", "LName": "kumar" }, { "FNAME": "karu ", "LName": "ronald" }] }
The followiing code solves my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[ToolboxItem(false)]
public class CService : System.Web.Services.WebService
{
public CService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void CargoNet()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT TOP 1 * FROM cargo_tracking ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}

Autocomplete in Ajax not working?

In Ajax, i am using autocompleteExender in my asp.net application, i write the service for that, when i run that service it is working fine, when i place autocompleteextender in asp.net page and assign properity for ajax autocompleteextender it is not working. this is my code service:
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
SqlConnection con=new SqlConnection
("server=******;database=Mydb;user id=***;password=****;");
string sql = "Select productname from F_Product
Where productname like '" + prefixText + "%'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
try
{
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr[0].ToString(), i);
i++;
}
return items;
}
catch
{
return null;
}
finally
{
con.Close();
}
and this is my ajax autocompleteextender code.
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="2"
TargetControlID ="TextBox1" ServiceMethod="GetCompletionList"
ServicePath="~/Autocomplete.asmx"
runat="server">
</asp:AutoCompleteExtender>
<asp:TextBox ID="TextBox1" runat="server"
Width="213px"></asp:TextBox>
Try this out.
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
If you find it useful, please mark it as your answer else let me know...
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Script.Services;
namespace YourProject
{
/// <summary>
/// Summary description for WebService
/// </summary>
// [ScriptService]
//[System.Web.Script.Services.ScriptService()]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
}
}
If you find it useful, please mark it your answer else let me know...

Resources