I'm trying to print a server report without preview using C#. The report is printing fine in WidowsXP but it's printing in zoomed view in Windows 7 and Windows 10. Below is my code.
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
namespace Dahlawi.ManPower.Recruiting.Forms
{
public partial class FrmReportViewer1 : Form
{
List<Metafile> m_ReportPages = new List<Metafile>();
int m_ReportPageIndex = 0;
public FrmReportViewer1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PrintDocument objPrintDoc = new PrintDocument();
objPrintDoc.PrintPage += PrintPageHandler;
PrintDialog objPrintDiag = new PrintDialog();
objPrintDiag.Document = objPrintDoc;
DialogResult objDiagResult = default(DialogResult);
objDiagResult = objPrintDiag.ShowDialog();
if (objDiagResult == DialogResult.OK)
{
objPrintDoc.PrinterSettings = objPrintDiag.PrinterSettings;
this.m_ReportPages = new List<Metafile>();
this.m_ReportPageIndex = 0;
this.reportViewer.ShowCredentialPrompts = false;
this.reportViewer.ServerReport.ReportServerCredentials.NetworkCredentials = new System.Net.NetworkCredential("USER", "PASSWORD", "DOMAIN");
this.reportViewer.ServerReport.ReportServerUrl = new Uri("http://SERVER/ReportServer");
this.reportViewer.ServerReport.ReportPath = "/DMR/Candidate_Information";
ReportParameter[] reportParameters = new ReportParameter[] { new ReportParameter("CandidateId", "16744") };
reportParameters[0].Visible = false;
this.reportViewer.ServerReport.SetParameters(reportParameters);
this.reportViewer.RefreshReport();
string deviceInfo = "<DeviceInfo>" + "<OutputFormat>emf</OutputFormat>" + " <PageWidth>8.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.2in</MarginTop>" + " <MarginLeft>0.5in</MarginLeft>" + " <MarginRight>0.5in</MarginRight>" + " <MarginBottom>0.2in</MarginBottom>" + "</DeviceInfo>";
Warning[] objWarnings = null;
string[] sStreamIDs = null;
string sMimeType = "";
string sEncoding = "";
string sFilenameExtension = "";
byte[] renderedPage = null;
renderedPage = this.reportViewer.ServerReport.Render("Image", deviceInfo, out sMimeType, out sEncoding, out sFilenameExtension, out sStreamIDs, out objWarnings);
this.m_ReportPages.Add(new Metafile(new MemoryStream(renderedPage)));
foreach (string sStreamId in sStreamIDs)
{
renderedPage = this.reportViewer.ServerReport.RenderStream("Image", sStreamId, deviceInfo, out sMimeType, out sEncoding);
this.m_ReportPages.Add(new Metafile(new MemoryStream(renderedPage)));
}
objPrintDoc.Print();
objPrintDoc = null;
}
}
private void PrintPageHandler(object sender, PrintPageEventArgs e)
{
if (this.m_ReportPageIndex < this.m_ReportPages.Count)
{
Metafile imgPage = this.m_ReportPages[this.m_ReportPageIndex];
this.m_ReportPageIndex += 1;
e.Graphics.DrawImage(imgPage, 0, 0, imgPage.Width, imgPage.Height);
e.HasMorePages = this.m_ReportPageIndex < this.m_ReportPages.Count;
}
}
}
}
When I print the report using above code in WindowsXP it prints like this Proper Print
But when I run the same code in Windows 7 or Windows 10 it prints like this Zoomed Print
Please help me run this code on Windows 7 / Windows 10. I can provide more details if required.
I found out the issue and it's the "emf" output format which is causing the problem on Windows 7 and Windows 10 but working fine on Windows XP / Windows 2003. I changed the output format in "deviceInfo" string from "emf" to "jpg" (other formats e.g. "png", "jpeg", "bmp" also work fine) and then I changed the type of "m_ReportPages" list object from "Metafile" to "Image" and got the issue resolved.
Related
I've finished a Unity game which i want to publish in Google Play, Windows Phone Store and Windows 8 Store. I'm using the very last version of Parse for Unity SDK (1.4.1) and also the last version of Unity Editor (4.6.4p4), including last patches.
The Parse implementation i made in my game works perfectly on:
- Unity Editor (all platforms)
- Android (deploying apk on two devices)
- Android (Publishing the game as alpha, installing it in +8 devices)
- Windows Phone 8 (All Windows Phone Emulators - 8.0 and 8.1 - x86)
- Windows Phone 8 (debugging on device with both Visual Studio 2012 for Windows Phone and Visual Studio 2013 Community - ARM)
It does'nt work on:
- Windows Phone 8 (deploying as a Beta)
- Windows Phone 8 (deploying as Hidden release)
The game crashes every time i try to use any function of the Parse SDK, throws no exception, the Windows Phone 8 Store gives me no info about any crashes... seems like an assembly load issue...
I've no idea what is happening, this issue is stoping me to publishing my game, think i'm going crazy...
So, i've made a simple dummy app to test my parse implementation, and... it has the same issue... it's very simple: Only a gameobject which has the "Parse Initialize Behaviour" attached (with both AppId and .NET keys setted) and a very simple script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System;
using System.Linq;
using Parse;
using System.Threading.Tasks;
// Demo application script
public class AppScript : MonoBehaviour
{
public static string userName = "Caldofran";
public static string userPass = "Password5";
public static string userEmail = "caldofran#email.com";
public static string errAsincrono = "";
public static string log = "";
public static bool bLogin = false;
public static bool bSignUp = false;
// Use this for initialization
void Start () {
//Application.runInBackground = true;
}
GUIStyle ts = new GUIStyle();
void OnGUI()
{
if (GUI.Button(new Rect(10, 100, 100, 30), "Sign Up"))
SignUp(userName,userPass, userEmail);
if (GUI.Button(new Rect(10, 150, 100, 30), "Login"))
Login(userName, userPass);
if (GUI.Button(new Rect(10, 200, 100, 30), "Logout"))
Logout();
if (GUI.Button(new Rect(10, 300, 100, 30), "Clear Texts"))
{
errAsincrono = "";
log = "";
}
int left = Screen.width - 110;
string usrParse = "";
if (AppScript.IsLoggedInParse())
usrParse = ParseUser.CurrentUser.Username;
ts.normal.textColor = Color.red;
GUI.BeginGroup(new Rect(300, 5, 600, 500));
GUI.Box(new Rect(0, 0, 400, 300), "");
//GUILayout.Label("P: " + mensajeGUI);
GUILayout.Label("User Config: " + userName, ts);
GUILayout.Label("Pass config: " + userPass, ts);
GUILayout.Label("email config: " + userEmail, ts);
GUILayout.Label("Logged in parse: " + AppScript.IsLoggedInParse().ToString(), ts);
GUILayout.Label("Parse logged user: " + usrParse, ts);
GUILayout.Label("Last msg: " + errAsincrono, ts);
GUILayout.Label("Last Log: " + log, ts);
GUI.EndGroup();
}
// Update is called once per frame
void Update () {
if (bLogin)
{
bLogin = false;
log += " Login Update text";
}
if (bSignUp)
{
bSignUp = false;
log += " SignUp Update text";
}
}
#region Parse
public static bool IsLoggedInParse()
{
bool retorno = false;
if ((ParseUser.CurrentUser != null) && (ParseUser.CurrentUser.IsAuthenticated))
retorno = true;
return retorno;
}
public static void SignUp(string userName, string passWord, string email)
{
var user = new ParseUser()
{
Username = userName,
Password = passWord
};
if (string.IsNullOrEmpty(email))
user.Email = "";
else
user.Email = email;
try
{
Task signUpTask = user.SignUpAsync().ContinueWith(t=>
{
if (t.IsFaulted || t.IsCanceled)
{
// The login failed. Check the error to see why.
foreach(var e in t.Exception.InnerExceptions) {
ParseException parseException = (ParseException) e;
log += parseException.Message + ": CODE: " + parseException.Code.ToString();
}
errAsincrono = t.Exception.Message;
}
else
{
// Signup was successful.
log = "Welcome " + userName;
bSignUp = true;
}
});
}
catch (Exception ex)
{
errAsincrono = "Error: " + ex.Message;
}
}
public static void Login(string user, string pass)
{
try
{
ParseUser.LogInAsync(user, pass).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
// The login failed. Check the error to see why.
foreach(var e in t.Exception.InnerExceptions) {
ParseException parseException = (ParseException) e;
log += parseException.Message + ": CODE: " + parseException.Code.ToString();
}
errAsincrono = t.Exception.Message;
}
else
{
// Login was successful.
log = "Welcome back " + userName;
AppScript.bLogin = true;
}
});
}
catch (Exception ex)
{
errAsincrono = "Error: " + ex.Message;
}
}
public static void ResetPassword(string email)
{
if (IsLoggedInParse())
{
Task requestPasswordTask = ParseUser.RequestPasswordResetAsync(email);
log = "Pass reset ok";
}
}
public static void Logout()
{
if (IsLoggedInParse())
{
ParseUser.LogOutAsync();
log = "Logged out ";
}
}
#endregion
}
Can anybody try it? What i'm doing wrong? Why this code works nearly always but not in Windows Phone (published on the store)?
I've read about Unity bug, which affects only to iOS: http://forum.unity3d.com/threads/unity-5-parse-ios-nsurlerrordomain-error-1012.308569/
This bug (consuming WWW trough SSL) affects Windows Phone apps?
In my case, using Parse SDK 1.6.1 for Windows.
To set Password property throws ArgumentException.
The cause was in Master build configuration and .NET Native tool chain.
Solution 1:
Uncheck "Compile with .NET Native tool chain" in Project's Build settings.
Solution 2:
Create subclass of ParseUser and define "new" properties Username and Password.
Im developing a small Tcp Client Socket application in windows phone. Actually i have a text box, in that whatever the data received from a TCP server, should update continuously in UI text box control.
while (val)
{
result = Receive();
Dispatcher.BeginInvoke((Action)(() =>
{
txtOutput.Text += result;
}));
}
Here in above code, method receive() will receive string data and should update in textbox control but it is not happening,no data is updating to it.
Can any one suggest, how can i resolve this.
Just telling you what i have been advised, "avoid Dispatcher, CoreDispatcher, etc. There are always better solutions."
Below is the piece of code worked for me for both wp8 and wp8.1 WinRT app,
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
where UpdateTicker() method contains your instructions, in this case...
public void UpdateTicker()
{
result = Receive();
txtOutput.Text += result;
}
Hope this helps...
Thanks for everyone, who given a valuable response for my post.
Hi Nishchith,
I tried your code, but it dint works for me
Here is my logic used to update textbox continuously with data received from TCP server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using Windows.Phone.Networking;
using System.Threading.Tasks;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 1000;
const int MAX_BUFFER_SIZE = 2048;
const int ECHO_PORT = 9055; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 49152; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
string result = string.Empty;
public MainPage()
{
InitializeComponent();
}
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
SocketClient client = new SocketClient();
Connect(txtRemoteHost.Text, ECHO_PORT);
//close();
}
public void Connect(string hostName, int portNumber)
{
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(2000);
_socket.ConnectAsync(socketEventArg);
Thread.Sleep(5000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
bool val;
if (result == "Success")
{
val = true;
}
else
{
val = false;
}
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
}
public void UpdateTicker()
{
result = Receive();
string[] strsplit = result.Split(' ');
txtOutput.Text = strsplit[1];
}
public string Receive()
{
string response = "Operation Timeout";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(1000);
_socket.ReceiveAsync(socketEventArg);
Thread.Sleep(1000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}
I've a requirement where I should display the list of all files from google drive (of course using oAuth for authorization and authentication)... displaying the list of files which has the extension (.mp3) along with the full path where the user can either copy the path of the file and paste it in a seperate url or can click on the file name to download the file. I'm not getting proper inputs of getting the full path of the file from google drive. I'm using asp.net application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Client;
using Google.GData.Documents;
using System.IO;
using Google.Apis.Drive.v2;
using Google.Apis.Drive;
using Google.Apis;
namespace AccessGoogleDriveData
{
public partial class GoogleOAuthCallback : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string state = Request.QueryString["state"];
// creating oauthparameter with client id and secret key
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = "myclientid.apps.googleusercontent.com",
ClientSecret = "clientsecretid",
RedirectUri = "http://localhost:16615/GoogleOAuthCallback.aspx">,
Scope = "https://docs.google.com/feeds/ ",
State = "documents",
AccessType = "offline"
};
lstDocuments.Visible = false;
if (state != null)
{
parameters.AccessCode = Request.QueryString["code"];
// it gets accesstoken from google
Google.GData.Client.OAuthUtil.GetAccessToken(parameters);
GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MyDocumentsListIntegration-v1", parameters);
DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
service.RequestFactory = requestFactory;
DocumentsListQuery query = new DocumentsListQuery();
// Make a request to the API and get all documents.
DocumentsFeed feed = service.Query(query);
lstDocuments.Visible = true;
if (feed.Entries.Count > 0)
{
// var documentsList = from entry in feed.Entries select entry.Title.Text;
var documentsList = from entry in feed.Entries where GetFileExtension(entry.Title.Text.ToString()) == "mp3" select entry.Title.Text;
lstDocuments.DataSource = documentsList;
lstDocuments.DataBind();
}
}
}
protected void btnGetDocuments_Click(object sender, EventArgs e)
{
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = "myclientid.apps.googleusercontent.com",
ClientSecret = "clientsecretid",
RedirectUri = "http://localhost:16615/GoogleOAuthCallback.aspx",
Scope = "https://docs.google.com/feeds/ ">,
State = "documents",
AccessType = "offline" // offline means it creats a refreshtoken
};
string url = Google.GData.Client.OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
Session["oauthDocumentsParameters"] = parameters;
// it redirct to google login page
Response.Redirect(url);
}
private string GetFileExtension(string sFileName)
{
sFileName = sFileName.Trim();
if (String.IsNullOrEmpty(sFileName))
{
return String.Empty;
}
string sExtension = String.Empty;
char[] cArr = sFileName.ToCharArray();
int iIndex = 0;
for (int i = cArr.Length - 1; i > -1; i--)
{
if (cArr[i].Equals('.'))
{
iIndex = i;
break;
}
}
if (iIndex > 0)
{
for (int i = iIndex + 1; i < cArr.Length; i++)
{
sExtension += cArr[i];
}
}
return sExtension.ToLower();
}
}
}
I have created a Windows phone app based on a quiz game. I want that when the user give the correct answer for some question then a small tick mark will be permanently on in the tab of the question.
I want to store score for every question so that i can display that in a place name as 'your score'. And that score will not be reset even if the app is closed.I have used IsolatedStorageFile to store the data for each page separately. In each page i have provided a back button which will navigate to category page using "NavigationService.GoBack()".
//mainpage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using logic.Resources;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/logo.xaml", UriKind.Relative));
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
int y = 0;
if (!fileStorage.FileExists("amazon.txt"))
{
//Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("amazon.txt", FileMode.OpenOrCreate, fileStorage));
//Write the contents of our TextBox to the file.
fileWriter.WriteLine(y);
//Close the StreamWriter.
fileWriter.Close();
}
}
}
}
//category page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class logo : PhoneApplicationPage
{
public logo()
{
InitializeComponent();
int x = 0;
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new StreamReader
StreamReader fileReader = null;
if (fileStorage.FileExists("amazon.txt"))
{
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("amazon.txt", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
x = Convert.ToInt32(textFile);
//Write the contents of the file to the TextBlock on the page.
fileReader.Close();
if (x == 1)
{
ama.Visibility = System.Windows.Visibility.Visible;
}
}
}
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.Navigate(new Uri("/amazon.xaml", UriKind.Relative));
}
}}
//question page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using System.IO.IsolatedStorage;
namespace logic
{
public partial class amazon : PhoneApplicationPage
{
public amazon()
{
InitializeComponent();
}
//check the answer is correct or not
int count = 0;
int x;
private void b1_Click(object sender, RoutedEventArgs e)
{
if (tb1.Text.Length == 0 || tb2.Text.Length == 0 || tb3.Text.Length == 0 || tb4.Text.Length == 0 || tb5.Text.Length == 0 || tb6.Text.Length == 0)
{
}
else
{
Char s1, s2, s3, s4, s5, s6;
s1 = Char.ToUpper(tb1.Text[0]);
s2 = Char.ToUpper(tb2.Text[0]);
s3 = Char.ToUpper(tb3.Text[0]);
s4 = Char.ToUpper(tb4.Text[0]);
s5 = Char.ToUpper(tb5.Text[0]);
s6 = Char.ToUpper(tb6.Text[0]);
if (s1 == 'A' && s2 == 'M' && s3 == 'A' && s4 == 'Z' && s5 == 'O' && s6 == 'N')
{
//Obtain a virtual store for application
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Create a new StreamReader
StreamReader fileReader = null;
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("amazon.txt", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
x = Convert.ToInt32(textFile);
//Write the contents of the file to the TextBlock on the page.
fileReader.Close();
if (x == 0)
{
fileStorage.DeleteFile("amazon.txt");
//Create a new StreamWriter, to write the file to the specified location.
StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("amazon.txt", FileMode.OpenOrCreate, fileStorage));
fileWriter.WriteLine("1");
//Close the StreamWriter.
fileWriter.Close();
}
ans.Text = "Correct!!!";
}
else
{
ans.Text = "\n\nINCORRECT";
}
}
}
//reset the value
private void reset_Click(object sender, RoutedEventArgs e)
{
tb1.Text = "";
tb2.Text = ""; tb3.Text = ""; tb4.Text = ""; tb5.Text = ""; tb6.Text = "";
}
private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
NavigationService.GoBack();
}
}
}
The problem is that when ever i gave the correct answer and press the back button which navigate to logo page the trick(named as "ama" in category code) do not show. But when again i navigate to mainpage then come back to category page the trick is shown. I want that when ever i give the correct answer and navigate back to category page using the back button provided in the app or back button of mobile the trick should be shown at that time only.
According to your code.
Your logic is in constructor of that class. Which is called once you navigate to it from main page and is not called again when you navigate back from question page.
So, you are logically not executing any code when it navigates back, hence displaying the same view as it was.
To make it update, write your logic code in Page_Loaded event.
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using MySql.Data.MySqlClient;
namespace Student_Portal_Password
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string GetMd5Hash(string input)
{
MD5 md5Hash = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public void check()
{
if (txtid.Text == "")
{
MessageBox.Show("Please enter Student ID ", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
else if (txtpassword.Text == "")
{
MessageBox.Show("Please enter new password", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//check();
txtpassword.Text.Trim();
string hash = GetMd5Hash(txtpassword.Text);
string db = "server=localhost;uid=root;password=usbw;database=dum;";
MySqlConnection dbcon = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand(db);
dbcon.Open();
cmd.CommandText = "SELECT * FROM members;";
cmd.ExecuteNonQuery();
MessageBox.Show("Success!");
dbcon.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtid_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
}
}
A couple of things;
You're using ExecuteNonQuery for a Query. Try for example ExecuteReader instead.
You're not setting a connection for your DbCommand, so executing it won't find the database.
Try this instead;
MySqlConnection dbcon = new MySqlConnection(db);
string sql = "SELECT * FROM members";
MySqlCommand cmd = new MySqlCommand(sql, dbcon); //<-- pass connection to command
Your current code;
MySqlCommand cmd = new MySqlCommand(db);
...passes in the connection string as the SQL to execute, and does not associate the command with any database connection. That will give the error you're asking about.