MySQL & UWP - Unable to perform a query
I'm working on UWP (Fall Creators Update) and I'm getting two exceptions upon trying ExecuteReader()
.
This is my code:
MySqlConnection conn = Util.GetConnection("Server=localhost;Port=3306;Database=sample;Uid=root;Pwd=;CharSet=utf8;SslMode=None;");
conn.Open();
string Command = "SELECT id, role FROM tblUsers WHERE username = @user AND password = @pass";
MySqlCommand cmd = new MySqlCommand(Command, conn);
cmd.CommandType = CommandType.Text;
// handle username and password
cmd.Parameters.AddWithValue("@user", UserName);
cmd.Parameters.AddWithValue("@pass", Password);
cmd.Prepare();
MySqlDataReader reader = cmd.ExecuteReader(); // <-- throws an exception.
reader.Read();
...
Checked the query itself and the connection string, they're all fine. The exceptions I'm getting are:
Exception thrown: 'System.ArgumentException' in System.Private.CoreLib.ni.dll
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Private.CoreLib.ni.dll
See also questions close to this topic
-
WinForm: Find if network connection is metered (network cost)
In a Universal Windows Platform application, there are APIs such as
GetInternetConnectionProfile()
to find out whether a network connection has a cost associated to it, i.e. metered connection.Is there a way a WinForm desktop application can find out if the network connection with active internet is metered connection?
-
I can´t retrieve content-disposition and fileName from headers doing a httprequest.
My final goal is to download the file from server, but I think I´m halfway to the goal. I assume that I nee to change the last lines from the front end for saving the downloaded file. However, the following error is appearing when I check whats on the headers.
From the server side I´m doing the following to send fulfill what I expect from the headers and output the file stream.
[HttpGet, Route("DownloadAttachment")] public async Task<HttpResponseMessage> DownloadAttachment(string fileName) { //Here I previously got the idFromtheFile. FileDTO fileTaskContent = this.taskService.GetFileByIdTaskContent(idFromFile); //fileAWS represents the stream var fileAWS = await _awsService.GetFile(fileTaskContent.PathAWS); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(fileAWS.ResponseStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileTaskContent.Name }; return response; }
Then on my angularjs controller I´m getting the response that called the service that made the request.
function downloadAttachment(fileName) { taskService.downloadAttachment(fileName) // Add p .then(function (response) { if (response.data) { var headers = response.headers(); //Here the heders get an arbitrary value than the one from server without showing content disposition nor filename var contentType = headers['content-type']; var data = new Blob([response.data], {type: contentType}); var url = URL.createObjectURL(data); window.open(url, '_blank'); } }); }
Unfortunately I´m getting the error TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.remoteFunction (:2:14).
Any help or ideas are really appreciated!
-
C# Dynamically set sound output of application
A while back I was working on an application that controls the sound output of programs based on which screen the program is. For example I have a browser on my TV and by that I want to set the sound output of the program to the TV's speakers. I've already done the detection part (find on which screen the program is) and I'm ready to implement any solutions you give me here. My program works by always following the application that is focused, so if it changes screens it should change sound output
As I told you above, I already have the screen detection done but when it comes to changing the sound output for only that application that is focused I had no luck so far. How do I accomplish this? Is it possible? I've already searched on this topic and found libraries that should do this like NAudio but none of them seemed to work for me, that's why I stopped developing this program, until now :)
Any help would be appreciated and please don't down vote without telling me what the mistake or problem is so I can fix it.
-
php $sql INSERT INTO not posting new MySQL row with struct Encodable String VALUES
Objective is to
INSERT INTO FUBARtable
theLoginName
andLoginEmail
variables from ios app LoginPage -> into new row of mysql database. Question is how to modify code, which now can insert new row withVALUES ("statictext", ...)
, so that it will insert new row with the variable USERvaluesVALUES (LoginName, ...)
:// This $sql WILL insert new row with static text USERvalues $sql = "INSERT INTO `FUBARtable`(`userName`, `userEmail`) VALUES ('statictext', 'statictext')"; // This $sql will NOT insert new row with variable USERvalues $sql = "INSERT INTO `FUBARtable`(`userName`, `userEmail`) VALUES (LoginName, LoginEmail)"; // per GIJOW comment String? changed to String struct USERvalues: Encodable { let LoginName: String let LoginEmail: String } // userInfo[username, email] passed from LoginPage var userInfo = ["Anonymous", "unknown"] let url = URL(string: "http://mysqlDatabase.com/insert.php")! var request = URLRequest(url: url) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") let Post = USERvalues(LoginName: self.userInfo[0], LoginEmail: self.userInfo[1]) do { let encodedPost = try JSONEncoder().encode(Post) request.httpBody = encodedPost } catch {} let session = URLSession.shared let task = session.dataTask(with: request) { (data, _, _) in guard let data = data else { return } do { print(Post) let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) } catch {} } task.resume()
(applying GIJOW comment to remove ?) print(Post) prints out the correct userInfo values from the LoginPage:
USERvalues(LoginName: "Arthur Dent", LoginEmail: "improbabilitydrive@gmail.com")
-
What is the best option for implementing sharding in mysql
I need to shard mysql database based on tenant-id. When i searched i got some solutions like fabric, NDB cluster, vitess etc. But there is so much confusion on which one is production ready??, which one has much support??, and which is the better option??. Also Does mysql 8.0 will support sharding and is it production ready?? and any shard management and monitoring tools for the above mentioned packages?? Please help me here. I am currently using mysql 5.7
-
Group by & Order by in the same statement (per month)
Is is possible to group by and order by in the same statement? The below statement outputs the months in a random order. It produces the correct figures etc, however i would like to show the months as Jan,Feb,March, April etc. in order
SELECT coalesce(date_format(TRANSACTION_DATE, '%M'), 'Grand Total') AS MONTH, ROUND(SUM(SALES_AMOUNT),2) TOTAL, SUM(QUANTITY) AS TOTAL_QUANTITY FROM SALES WHERE YEAR(TRANSACTION_DATE) = 2018 GROUP BY month WITH ROLLUP; April 30826.68 476 August 39703.85 619 December 36986.16 515 February 34531.15 463 January 45163.22 596 July 37640.08 506 June 37284.25 496 March 44194.98 621 May 39016.04 576 November 39161.90 521 October 34447.61 485 September 34958.94 498 453914.86 6372
-
Unwanted space is found in Xamarin UWP app's ContentView
I've been having a trouble with unwanted extra space in Xamarin UWP app's ContentView
<ScrollView Orientation="Vertical"> <Grid RowSpacing="0"> <Grid.RowDefinitions> <!--Header - Logo & Caption--> <RowDefinition Height="Auto"></RowDefinition> <!--ListView menu with boxes--> <RowDefinition Height="Auto"></RowDefinition> <!--Footer--> <RowDefinition Height="Auto"></RowDefinition> </Grid.RowDefinitions> ...
Below my ListView, I get to see a lot of unwanted space. I tried Auto and * options but I'm still getting space.
-
the program does not respond when loading data via StreamSocket
I create a UWP App which can show worldwide cameras. My use this method for load data:
public Task StartLoad(string url) { private const int ChunkSize = 512; private bool streamStopped; private StreamSocket tcpClient; return Task.Run(async () => { this.streamStopped = false; #region Sockets var uri = new Uri(url); var requestHeadersBuilder = new StringBuilder(); requestHeadersBuilder.Append(@"GET "); requestHeadersBuilder.Append(uri); requestHeadersBuilder.AppendLine(" HTTP/1.1"); requestHeadersBuilder.AppendLine(@"Connection: Keep-Alive"); requestHeadersBuilder.AppendLine(String.Format(@"Host: {0}", uri.Host)); requestHeadersBuilder.AppendLine(); try { using (this.tcpClient = new StreamSocket()) { this.tcpClient.Control.NoDelay = false; this.tcpClient.Control.QualityOfService = SocketQualityOfService.Normal; var socketProtection = SocketProtectionLevel.PlainSocket; if (uri.Scheme == "https") { socketProtection = SocketProtectionLevel.Tls12; } await tcpClient.ConnectAsync(new HostName(uri.Host), uri.Port.ToString(), socketProtection); try { using (var outputStream = tcpClient.OutputStream.AsStreamForWrite()) { var requestHeaders = requestHeadersBuilder.ToString(); var headersBytes = Encoding.UTF8.GetBytes(requestHeaders.ToCharArray()); await outputStream.WriteAsync(headersBytes, 0, headersBytes.Count()); await outputStream.FlushAsync(); } } catch (Exception ex) { var error = ex.Message; } using (var inputStream = tcpClient.InputStream.AsStreamForRead()) { using (var br = new BinaryReader(inputStream)) { while (!this.streamStopped) { var buff = br.ReadBytes(ChunkSize); var stringStartBytes = Encoding.UTF8.GetBytes("Content-Length: "); var stringStartIndex = buff.Find(stringStartBytes); if (stringStartIndex > 0) { var stringEndBytes = Encoding.UTF8.GetBytes("\r\n"); var stringEndIndex = buff.Find(stringEndBytes, stringStartIndex); var contentLengthHeader = Encoding.UTF8.GetString(buff, stringStartIndex, stringEndIndex - stringStartIndex); var lengthString = contentLengthHeader.Substring("Content-Length: ".Length); var imageSize = Int32.Parse(lengthString); var imageBuffer = new byte[imageSize]; var jpegImageStartIndex = buff.Find(JpegHeader); if (jpegImageStartIndex > 0) { var readedImageSize = buff.Length - jpegImageStartIndex; Array.Copy(buff, jpegImageStartIndex, imageBuffer, 0, readedImageSize); while (readedImageSize < imageSize) { if (this.streamStopped) { break; } var remainingSize = imageSize - readedImageSize; var chunkSize = Math.Min(remainingSize, ChunkSize); buff = br.ReadBytes(chunkSize); Array.Copy(buff, 0, imageBuffer, readedImageSize, buff.Length); readedImageSize += buff.Length; } if (!this.streamStopped) { this.ImageReceived.SafeInvoke(this, new ImageDataEventArgs() { ImageBytes = imageBuffer }); } } else { this.streamStopped = true; this.StopLoad(); SynchronizationContextProvider.UIThreadSyncContext.Post((d) => { this.ErrorOccurred.SafeInvoke(this, new ErrorEventArgs() { ErrorException = new ArgumentException("Image not found") }); }, null); } } else { this.streamStopped = true; this.StopLoad(); SynchronizationContextProvider.UIThreadSyncContext.Post((d) => { this.ErrorOccurred.SafeInvoke(this, new ErrorEventArgs() { ErrorException = new ArgumentException("Image not found") }); }, null); } } } } this.StopLoad(); } } catch (Exception ex) { this.streamStopped = true; this.StopLoad(); SynchronizationContextProvider.UIThreadSyncContext.Post((d) => { this.ErrorOccurred.SafeInvoke(this, new ErrorEventArgs() { ErrorException = ex }); }, null); } #endregion }); }
But when the picture freezes, the program does not respond on user action. I don't click on a button. I don't know what happens. I call this method asynchronously, but the app behaves as like I call it synchronously.
-
C# UWP: Cannot TryParse a byte[] datatype
I want to convert a 'string' to a 'byte[]' and I wish to do so with the TryParse function. I have used the TryParse function to successfully convert bool and DateTime data types however I am struggling to do so with byte[].
The code I have written is:
byte[] password;
byte[].TryParse(PasswordBox.Text, out password);
The error message that appears is "TryParse does not exist in the current context". When I rename byte[] to Byte it works, however the byte I have used requires '[]' and the error message that then comes up is "cannot convert 'byte' to 'byte[]'.