Is there any replacement of Top in Sql dependency in signalr? - sql

Can you please let me know how can i use Top or other sql statement in sql dependency to get Top 5 records, whenever i use this Top its always shows Sql NotificationType Subscribe.
Please help me out to get top records using query in SignalR
When i tried this its is working fine
public void SendStocksNotifications(string symbol="")
{
string conStr = ConfigurationManager.AppSettings["myConnectionString"].ToString();
using (var connection = new System.Data.SqlClient.SqlConnection(conStr))//"data source="";initial catalog="";persist security info=True;user id="";password="";multipleactiveresultsets=True;application name=EntityFramework""))
{
string newdate = DateTime.Now.ToString( "MM/dd/yyyy" );
string query = "SELECT TOP 1 [Close],Pre_Close, Volume, Pre_Volume, PercentageChange, Pre_PercentageChange, NetChange, Pre_NetChange, High, Low, Pre_High, Pre_Low,Previous, Pre_Previous, [52WH], [52WL] FROM [dbo].[History] WHERE Symbol='" + symbol + "' ORDER BY UpdatyedDate DESC";
connection.Open();
using ( SqlCommand command = new SqlCommand( query, connection ) )
{
}
}
}
But this code
private void dependency_OnChange1(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
string symbol = Vsymbol;
NotificationStocks nHub = new NotificationStocks();
nHub.SendStocksNotifications( symbol );
}
}
shows e.Type=SqlNotificationType.Subscribe.

Related

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()

Filter out duplicate Users Asp.Net

So I made a Registration page and a SQL table(Students Table) in the back end. In the code behind of my registration page.aspx I've got a sql query to count the number of StudentName in the db and if the count is equal to 1 then inform the user attempting to register that the student already exist in the database. However every time I test it the count is always 0, even when I register using a student name that is already in the db.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkUser = "select count(*) from Students where StudentName='" + txtStudentName.Text + "'";
SqlCommand com = new SqlCommand(checkUser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("Student already exist");
}
conn.Close();
}
}

must declare variable scalar

i have this code:
private void btGuardar_Click(object sender, EventArgs e)
{
if (txDescrip.Text.Trim().Equals("") == false && txPath.Text.Trim().Equals("") == false)
{
try
{
byte[] imgData = getMyFileBytes(txPath.Text);
//Server connection
OleDbConnection connection = new OleDbConnection(strcx);
String q = "INSERT INTO MisImagenes (Id,CustomImage) values(#MyPath, #ImageData)";
//Initialize sql command object for insert
OleDbCommand command = new OleDbCommand(q, connection);
//We are passing original image path and image byte data as sql parameters
OleDbParameter pMyPath = new OleDbParameter("#MyPath", (object)txPath.Text);
OleDbParameter pImgData = new OleDbParameter("#ImageData", (object)imgData);
command.Parameters.Add(pMyPath);
command.Parameters.Add(pImgData);
//Open connection and execute insert query
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Mensaje.aviso("Imagen Guardada :)");
//Limpiamos
clearAlta();
}
catch (Exception exc)
{
Mensaje.aviso("Something went wrong! :( " + exc.Message);
}
}
}
when i execute this says "Must declare the scalar variable "#MyPath"." ... any help? please, thank you.
I'm just trying to save an image to my sqlserver db by selecting the path and id description for the image. and i just get this frustrating error
you should use '?' instead of parameter names in oledb queries
INSERT INTO MisImagenes (Id,CustomImage) values(?, ?)
similar question and answer: OleDbCommand parameters order and priority

to solve sql exception Cannot find either column "partinfo" or the user-defined function or aggregate "partinfo.query", or the name is ambiguous

I use this pgm to get value from a column in xmlstring format named partinfo.which is one of the columns in table test.the partinfo column can be treated as another table containing many columns.and i want to read data from one of this column which is installed date in this case.but while executing i am getting a
sql exception: Cannot find either column "partinfo" or the user-defined
function or aggregate "partinfo.query", or the name is ambiguous.how
can i solve this.
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
try {
SqlConnection con = new
SqlConnection("Data Source=NIP007\\SQLEXPRESS;
Initial Catalog=test;User ID=sa;Password=nest123#!");
con.Open();
string query = "SELECT [partinfo].query('.//InstalledDate').value('.','VARCHAR(MAX)')FROM [test]";
SqlCommand cmd = new SqlCommand(query, con);
// StringBuilder builder=new StringBuilder();
// string PartInfo=string.Empty;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string str5 =dr.ToString();
if (!string.IsNullOrEmpty(str5))
{
textBox1.Text=str5;
}
}
}
catch(Exception ex)
{
}
}
}
}
It is not clear what exactly where your error lies because, your SQL should work ok (Demo Here) and not return an error, although I am not sure the output is what you would want as it just concatenates all the installed dates in the XML as one long string:
As said in my previous answer if you have multiple Installed Dates per row, you will want to use CROSS APPLY TO get the installed dates as separate rows.
Demo SQL using CROSS APPLY
If you really want the dates concatenated to one string then I'd suggest using a string builder to do this:
try
{
string query = #"SELECT InstalledDate = x.value('InstalledDate[1]', 'DATETIME')
FROM dbo.Test
CROSS APPLY PartInfo.nodes('/DocumentElement/PartInfo') p (x);";
using (var con = new SqlConnection("Data Source=NIP007\\SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=nest123#!"))
using (var cmd = new SqlCommand(query, con))
{
con.Open();
using (var dr = cmd.ExecuteReader())
{
var builder = new StringBuilder();
while (dr.Read())
{
string str5 = dr.GetString(0);
if (!string.IsNullOrEmpty(str5))
{
builder.Append(str5 + ",");
}
}
textBox1.Text = builder.ToString();
}
}
}
catch (Exception ex)
{
}
If this doesn't help can you post the DDL of your table Test and some sample data.
Thanks

sqlcommand for updation

I have a table which I want to update using a simple update command.
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET KPI1_Status =
#KPI1_Status, KPI2_Status = #KPI2_Status, KPI3_Status = #KPI3_Status,
KPI4_Status = #KPI4_Status, KPI5_Status = #KPI5_Status, KPI6_Status =
#KPI6_Status, Overall_Status= #Overall_Status WHERE TokenID = '" +
DropDownList1.SelectedItem.Text + "' AND TimeSet = '"
+ currentdate + "'", connection);
cmd.Parameters.AddWithValue("#KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Overall_Status", FinalStatus.SelectedItem.Text);
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
However it's throwing the following exception error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The only column of datatype datetime in the database is TimeSet. But currentdate is also of data type datetime.
DateTime currentdate = DateTime.Now.ToLocalTime();
Then why is this error popping up? Please help.
a) Use parameters for the values in your WHERE clause, as well as for the SET part, and
b) Then use cmd.Parameters.AddWithValue("#TimeSet", DateTime.Now.ToLocalTime());
This will also protect you from SQL injection.
I.e. if you've got a datetime value, try to keep it as a datetime value, and don't muck about with trying to treat it as a string at any point. Let ADO.Net and SQL Server deal with any necessary conversions.
Your code should look like this:
protected void UpdateButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("UPDATE KPI_DETAILS_TABLE SET"+
"KPI1_Status = #KPI1_Status, KPI2_Status = #KPI2_Status,"+
"KPI3_Status = #KPI3_Status, KPI4_Status = #KPI4_Status,"+
"KPI5_Status = #KPI5_Status, KPI6_Status = #KPI6_Status,"+
"Overall_Status= #Overall_Status"+
"WHERE TokenID = #ID AND TimeSet = #Time", connection);
cmd.Parameters.AddWithValue("#KPI1_Status", DropboxKPI1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI2_Status", DropboxKPI2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI3_Status", DropboxKPI3.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI4_Status", DropboxKPI4.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI5_Status", DropboxKPI5.SelectedItem.Text);
cmd.Parameters.AddWithValue("#KPI6_Status", DropboxKPI6.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Overall_Status", FinalStatus.SelectedItem.Text);
cmd.Parameters.AddWithValue("#ID", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Time", DateTime.Now.ToLocalTime());
try
{
cmd.ExecuteNonQuery();
Error1.Text = "KPI Status Successfully Updated !!";
}
catch { Error1.Text = "Error during Updating status of KPIs"; }
finally { connection.Close(); }
}
Repaired the mess in the string of your SqlCommand object.
Instead of adding local variables to your SqlCommand I added new SqlParameters and defined where they'd get their values from (#ID, #Time).
Instead you use DateTime.Now.ToString(); for giving the Currentdate and try again.