Stored Procedure working correctly in DB MySql but get error in ASP NET C#
I have the Stored Procedure
in database MySql version 8.0.17 that working correctly on the DB
CALL SP_PIVOT('Q100', 'sourcetable', 'contents', 'sun', 'contents');
Now I am trying to get Stored Procedure
to work in code-behind ASP NET C#
All tests get an error
First test
string sql = "CALL SP_PIVOT('Q100', 'sourcetable', 'contents', 'sun', 'contents');";
MySqlCommand cmd =
new MySqlCommand(sql);
Error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Q100', 'sourcetable', 'contents', 'sun', 'contents')'' at line 1
Second test
MySqlCommand cmd =
new MySqlCommand("SP_PIVOT");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.AddWithValue("tun", Mp2smal.Base64ForUrlDecode(Request.QueryString["un"]));
cmd.Parameters.AddWithValue("sourcetable", "sourcetable");
cmd.Parameters.AddWithValue("contents", "contents");
cmd.Parameters.AddWithValue("sun", "sun");
cmd.Parameters.AddWithValue("contents", "contents");
Error
"contents" Parameter is already declared
See also questions close to this topic
-
Filter items in a listbox that have been added with json
Well I'm trying to list items that are from listbox created with UserControl and the text properties are defined with a json file.
This is my .json file:
{ "Games": { "Quantity": 2, "Title0": "SomeGame1", "Description0": "Fps game", "Image0": "Some image link", "Link0": "GameStore.com/Somegame1", "Title1": "SomeGame2", "Description1": "RPG game", "Image1": "Some image link", "Link1": "GameStore.com/Somegame2", } }
This is the code to load the games as items in the listbox:
string JsonFile = Environment.CurrentDirectory @"\Test.json"; dynamic jasonfile = JsonConvert.DeserializeObject(JsonFile); GameUserControl[] Games = new GameUserControl[jasonfile["Games"]["Quantidade"]]; for (int quantity= 0; quantity < Games.Length; quantity++) { Games[quantity] = new GameUserControl(); Games[quantity].Descrição.Content = (jasonfile["Games"]["Title" + quantity]); Games[quantity].jog = (jasonfile["Games"]["Titulo" + quantity]); Games[quantity].lin = (jasonfile["Games"]["Link" + quantity]); string image = jasonfile["Games"]["Image" + quantity]; Games[quantity].imag = new ImageBrush(new BitmapImage(new Uri(image, UriKind.Absolute))); GamesListBox.Items.Add(Games[quantity]); }
This is the code I used in a textbox to try to filter:
if (CollectionViewSource.GetDefaultView(GamesListBox.Items) != null) CollectionViewSource.GetDefaultView(GamesListBox.Items).Filter = (o) => { return o.ToString().ToLower().Contains(Search.Text.ToLower()); };
But it didn't work, the item names are always GameUserContro.Can someone help me?
-
Advantage of .Net Core over WCF for RESTful APIs
We are currently using WCF to create RESTful APIs, it is working fine and has an added advantage that it can be consumed via SOAP too if we ever need to. We have all our systems using Microsoft technologies.
There is no active development on WCF but the current functionality is working fine for us. However, I believe the recommended approach is to start using .Net core for RESTful services. What are the additional advantages .Net core offers over WCF (apart from being platform independent)?
-
Generic class type constraint with a generic class having another constraint
Let's say I have a generic class
public class G<T> { }
and I want to declare final class as
public class F<T> where T : G<T> { }
that seems to be possible, but what if I want to complicate the task and add a constraint to the class G like that
public class A { } public class DA : A { } public class DB : A { } public class G<T> where T : A { }
and finally I want to do this
public class F<T> where T : G<T> { }
that does not work, it says T has to be of type A which is understandable and it looks like I can rewrite it like this
public class F<T, U> where T : G<U> where U : A { }
but in this case the usage has a redundant declaration
public class DF : F<G<DA>, DA> { }
I have to repeat DA twice when using class F even though it is quite clear if I use G as a generic type the generic type of G is DA. Is there a way to avoid this redundancy?
-
mysql select query does not fetch columns
I am trying to log in with php and mysql using the post method, only that when I go to press submit the sql query cannot find the records that exist, and therefore cannot log in this is my code:
<?php session_start(); $hostname=""; $username=""; $password=""; $dbname=""; $conn = new mysqli($hostname,$username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); ?> <script> console.log("Connection to db failed");</script><? } $username = $_POST["username"]; $password = $_POST["password"]; $sql = "SELECT username, password FROM admin WHERE utente = '$username' AND password = '$password'"; if($result = $conn->query($sql)){ if($result->num_rows > 0) echo 'sei loggato!!!'; else echo 'non sei loggato!!!'; } ?>
Could someone tell me what I'm doing wrong? (I did not use prepared statements because it is only a test)
-
Socket.io connection to different mySQL tables, Angular front end
I have an angular app that displays a table of data (mySQL database) and updates whenever anything is added to the database. I feel that I should add I'm very inexperienced, i know angular but trying to learn more about backened operations.
I'm using a websocket (socket.io) on a node.js server to achieve this. It works fine but I'd like to add a second unrelated table of data that will appear in a different part of my app. . Should I set up another websocket to achieve this? Or can one websocket interact with 2 different table in the one database.
All of the SQL queries are handled in the backend and look like this.
// Create MySQLEvents const instance = new MySQLEvents(connection, { startAtEnd: true // to record only new binary logs }); await instance.start(); instance.addTrigger({ name: 'Monitor all SQL Statements', expression: 'mydb.*', // listen to database statement: MySQLEvents.STATEMENTS.ALL, onEvent: e => { currentData = e.affectedRows; let newData; switch (e.type) { case "INSERT": database.table('products') .withFields(['id', 'title', 'quantity', 'price']) .sort({id: -1}) .getAll() .then(prods => { data = prods; io.sockets.emit('update', {prods: [...data]}); }) .catch(err => console.log(err)); .....
My front end just accepts and displays the incoming data. I'd be unsure of how to add a second socket to it.
Here is my socket.service.ts in angular.
export class SocketService { constructor(private socket: Socket) { } getInitialData() { return this.createObserver('initial'); } getUpdatedData() { return this.createObserver('update'); } private createObserver(event: string) { return this.socket.fromEvent(event); }
and here is the component.ts
export class DashboardComponent implements OnInit, OnDestroy { private subs: Subscription[] = []; localData: any[] = []; constructor(private socketService: SocketService) { } ngOnInit() { this.subs.push( this.socketService.getInitialData().subscribe((data: ServerResponse) => { this.localData = data.prods; }) ); this.subs.push( this.socketService.getUpdatedData().subscribe((data: ServerResponse) => { this.localData = data.prods; }) ); } ngOnDestroy() { this.subs.forEach(s => s.unsubscribe()); } } interface ServerResponse { prods: any[]; type?: string; }
I just iterate over localData to display the table.
My ideal outcome would be to have the one websocket with multiple endpoints. I just don't know how to handle this with mySQL events.
Similarly if I had 2 completely separate websockets I'm unsure how to handle that on the angular side.
-
JDBC remote acces to mysql db
I've been using a local database for my java projet using wamp and MYSQL, everything worked fine. Recently i set up an AWS EC2 vm on windows server. Wamp and Mysql are installed on it.
i managed to give remote access to apache and mysql so i'm able to acces phpmyadmin, the db and interactif with it from an external computer through a brower using its address : http://15.188.65.36/phpmyadmin/
but when i change what i had before (for my local wamp) which worked fine
public static ResultSet execute(String requete) { Connection connexion; Statement stmt = null; ResultSet res = null; try { connexion = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dbname","user","*********"); stmt = connexion.createStatement(); if(stmt.execute(requete)) { res = stmt.getResultSet(); } } catch (SQLException e) { System.out.println(e.getMessage()); } return res; }
for
public static ResultSet execute(String requete) { Connection connexion; Statement stmt = null; ResultSet res = null; try { connexion = DriverManager.getConnection ("jdbc:mysql://15.188.65.36:3306/dbname","user","*********"); stmt = connexion.createStatement(); if(stmt.execute(requete)) { res = stmt.getResultSet(); } } catch (SQLException e) { System.out.println(e.getMessage()); } return res; }
It's not working anymore, it seems that it can't connect, i receive this error :
Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Thanks for helping
-
Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net
I have an
asp.net
search form that includes anajaxToolkit Combobox
and a standardasp DropDownList
. Both controls are bound to two separatedSqlDatasource
components.Something like this:
<ajaxToolkit:ComboBox ID="cbConvenzionato" runat="server" AutoCompleteMode="SuggestAppend" DropDownStyle="DropDownList" DataSourceID="sdsConvenzionati" DataTextField="nome" DataValueField="id" AutoPostBack="true" OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" /> <asp:DropDownList ID="ddlVeicoli" DataSourceID="sdsVeicoli" DataTextField="targa" DataValueField="id" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged" AppendDataBoundItems="true"> <asp:ListItem Text="TUTTI" Value="" Selected="True" /> </asp:DropDownList> <asp:SqlDataSource ID="sdsConvenzionati" runat="server" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, nome FROM anag_convenzionati ORDER BY nome;" /> <asp:SqlDataSource ID="sdsVeicoli" runat="server" EnableCaching="false" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, targa FROM veicoli_contratti WHERE ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato)) ORDER BY targa;"> <SelectParameters> <asp:ControlParameter Name="id_convenzionato" ControlID="cbConvenzionato" PropertyName="SelectedValue" Direction="Input" ConvertEmptyStringToNull="true" DbType="Int32" DefaultValue="" /> </SelectParameters> </asp:SqlDataSource>
There's also a third
sqldatasource
(sdsNoleggi
) that feeds agridview
but this's not a problem right now.In code behind I have two event handlers:
protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e) { sdsVeicoli.Select(DataSourceSelectArguments.Empty); Search(); } protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e) { Search(); } private void Search() { sdsNoleggi.Select(DataSourceSelectArguments.Empty); }
I tought in this way I should filter
ddlVeicoli
items after selecting an item incbConvenzionato
... but it's not working... why?If I look into
sdsVeicoli
SelectParameters
in debug I can seeid_convenzionato
being correctly set to selected value (id coming fromcbConvenzionato
) I bet also thatsdsNoleggi
dataset wiil be correctly updated with new values since I did this many times before. So why bound control it's not? I tried also to force addlVeicoli.DataBind()
aftersdsVeicoli.Select()
call ... but this had no effect. -
Swagger UI not working for REST API (asp.net web api2) application
I have asp.net mvc project with .NET Framework 4.7.2 and the same project contains asp.net web api2 controller in a separate folder : Controllers. The solution is legacy. The API are already in use in the PRODUCTION environment. Now I added the Swagger nuget package (Install-Package Swashbuckle -Version 5.6.0) to this existing project. Post that I see a SwaggerConfig.cs added to the App_Start folder of the Solution Explorer.
Here the asp.net mvc controllers are used by App1 pointing to the server: www.app1.com and asp.net web api2 controllers are used by another frontend angular app: App2 pointing to the server : www.app2.com
The complete deployment package for both App1 and App2 are hosted in IIS
Any request related to App1 is handled by www.app1.com and any api request related to App2 (Angular frontend) is handled by App1 only using IIS Rewrite rules at App2 level which redirect any api request to App1 only.
Now in this case when I tried to navigate to www.app1.com/swagger , I see it is loading the SwaggerUI for me, but when I tried to navigate to www.app2.com/swagger it is not working and instead of that it is loading the Angular frontend application
Here goes the App1 and App2 at IIS level:
Can anyone help me here by providing their guidance to fix this issue?
-
Cors error missing allow origin header. MailKit
I have
cors error missing allow origin header
error only on ONE post request. My CORS Policypublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
Every request work fine, but one POST request fails, it's really weird. Code in controller action which failed use MailKit and SMTP to send email, maybe that's cause
-
Snowflake error in JavaScript procedure column index/name does not exists in resultSet getColumnValue
I am having a procedure on snowflake which executing the following query:
select array_size(split($1, ',')) as NO_OF_COL, split($1, ',') as COLUMNS_ARRAY from @mystage/myfile.csv(file_format => 'ONE_COLUMN_FILE_FORMAT') limit 1;
And the result would be like:
Why I run this query in a procedure:
CREATE OR REPLACE PROCEDURE ADD_TEMPORARY_TABLE(TEMP_TABLE_NAME STRING, FILE_FULL_PATH STRING, ONE_COLUMN_FORMAT_FILE STRING, FILE_FORMAT_NAME STRING) RETURNS variant LANGUAGE JAVASCRIPT EXECUTE AS CALLER AS $$ try{ var final_result = []; var nested_obj = {}; var nbr_rows = 0; var NO_OF_COL = 0; var COLUMNS_ARRAY = []; var get_length_and_columns_array = "select array_size(split($1,',')) as NO_OF_COL, "+ "split($1,',') as COLUMNS_ARRAY from "+FILE_FULL_PATH+" "+ "(file_format=>"+ONE_COLUMN_FORMAT_FILE+") limit 1"; var stmt = snowflake.createStatement({sqlText: get_length_and_columns_array}); var array_result = stmt.execute(); array_result.next(); //return array_result.getColumnValue('COLUMNS_ARRAY'); NO_OF_COL = array_result.getColumnValue('NO_OF_COL'); COLUMNS_ARRAY = array_result.getColumnValue('COLUMNS_ARRAY'); return COLUMNS_ARRAY; } ... $$;
It will return an error as the following:
{
"code": 100183,
"message": "Given column name/index does not exist: NO_OF_COL",
"stackTraceTxt": "At ResultSet.getColumnValue, line 16 position 29",
"state": "P0000",
"toString": {}
}
The other issue is if I keep trying, it will return the desired array, but most of the times is returning this error.
-
Check which SP is usege in via a database
I want to check which SP is in a database active in usege.
Example: Which SP was usege in the last three months. Has anyone an idea for this issue?
Thanks in advance.
-
NHibernate mapping of a Stored Procedure
I need to implement stored procedures in my project while using NHibernate as an ORM. The problem is that these SPs retrieve from a lot of tables. Do I have to do the mapping of each table? Or only the fields that the stored procedure works on?