|
Hi there,
how can I change the text of my textbox, while the code is running?
I will change it when I click on the button "search", and while the programm is searching the text in my textbox should be "searching ..."
Can anyone help me please?
|
|
|
|
|
Um...
myTextBox.Text = "Searching...";
I'm sure that isn't the problem you are having, but I can't work out from that little what problem you want us to solve.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I think you are asking how you can use the TextBox as both the source of what to search for and, then, while searching, a kind of progress indicator.
If this is what you want, I'd argue against that because:
1. if the computer this runs on is not very powerful, you may delay the search.
2. if the computer this runs on is super-powerful, all you may see is a meaningless blur.
3. there is a traditional way of doing this: use either a progress-bar or a status-bar control.
There are good resources here on CP for using both progress-bar and/or status-bar with a process (like search) running in its own thread, which is desirable so that the main UI does not become frozen, and the user may have the opportunity to cancel the search, etc.
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Okay but how can I show that it is searching?
|
|
|
|
|
Is there a way to change the speech recognition language, without installing language packs in windows or by installing them, but not changing the default language pack?
|
|
|
|
|
|
Upvoted; might not have been what he wants to hear, but it is correct.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Have areal 5 back, for telling the truth.
|
|
|
|
|
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 ')' at line 1;
What's wrong with this bracket
private void BindGrid()
{
MySqlConnection con = new MySqlConnection(constr);
MySqlCommand cmd = new MySqlCommand("SELECT Rasm FROM rasmlar where Rasm_ID IN (" + String.Join(",", getRasm_ID1()) + ")", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
}
|
|
|
|
|
That depends entirely on what's returned by getRasm_ID1() and what the column type of Rasm_ID .
If you're going to build a string to hold the SQL statement, put the statement into a string variable so you can examine the contents of the string in the debugger before you create a MySqlCommand object with it.
|
|
|
|
|
After creating the command, examine what the statement in cmd.CommandText looks like to see the problem. Few possibilities that come in mind:
|
|
|
|
|
Your code is vulnerable to SQL Injection[^].
NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
private void BindGrid()
{
using (MySqlConnection con = new MySqlConnection(constr))
using (MySqlCommand cmd = new MySqlCommand(string.Empty, con))
{
var sb = new System.Text.StringBuilder("SELECT Rasm FROM rasmlar where Rasm_ID IN (");
foreach (var id in getRasm_ID1())
{
if (cmd.Parameters.Count != 0)
{
sb.Append(',');
}
string name = "@p" + index;
cmd.Parameters.AddWithValue(name, id);
sb.Append(name);
}
sb.Append(')');
cmd.CommandText = sb.ToString();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I am trying to solve the following problem but my code is not so good. Could anybody help me a little bit.
Write a function that provides change directory (cd) function for an abstract file system.
Notes:
Root path is '/'.
Path separator is '/'.
Parent directory is addressable as "..".
Directory names consist only of English alphabet letters (A-Z and a-z).
For example, new Path("/a/b/c/d").Cd("../x").CurrentPath should return "/a/b/c/x".
Heres my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public class Path
{
public string CurrentPath { get; private set; }
public Path(string path)
{
this.CurrentPath = path;
}
public Path Cd(string newPath)
{
Path pathStr = new Path(this.CurrentPath);
if (newPath == null | newPath == string.Empty)
{
throw new System.NotSupportedException("Waiting to be implemented.");
}
string patternUp = "([\\.]{2}/)+[a-zA-z]+";
string patternDown = @"/([a-zA-z]*)";
var matchesUp = Regex.Matches(newPath, patternUp);
var matchesDown = Regex.Matches(newPath, patternDown);
if (matchesUp.Count > 0)
{
var countUp = newPath.Count(c => c == '.');
pathStr.CurrentPath = pathStr.CurrentPath.Substring(0, pathStr.CurrentPath.Length - countUp);
pathStr.CurrentPath = pathStr.CurrentPath + "/" + newPath.Replace("../", "");
}
else
{
pathStr.CurrentPath = pathStr.CurrentPath + newPath.Replace("../", "");
}
return new Path(pathStr.CurrentPath);
}
public static void Main(string[] args)
{
Path path = new Path("/a/b/c/d");
Console.WriteLine(path.Cd("../x").CurrentPath);
}
}
|
|
|
|
|
Sure. You don't need the RegEx's at all. All you need is to split the passed in string on the "/" characters and process the items found from left to right.
This sniffs of a homework assignment.
|
|
|
|
|
What happens using the code example you give now ? Errors ? If so, what ?
«I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.
|
|
|
|
|
Hello there,
Please have a look in this code:
ERROR LINE IS JUST BELOW #REGION YEARLYTAX... (COMMENTED)
private void ImportData_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
#region Delete Previous Data...
if (MessageBox.Show("Delete all previous records?", "DELETE ALL", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
if (MessageBox.Show("ALL RECORDS WILL BE DELETED PERMANENTLY... ARE YOU SURE?", "DELETE ALL", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
lblMessage.Content = "Please wait...";
Cursor = Cursors.Wait;
Engine E = new Engine();
SQLiteCommand CMD = new SQLiteCommand("DELETE FROM YEARS", E.Conn);
CMD.ExecuteNonQuery();
CMD = new SQLiteCommand("DELETE FROM WARDS", E.Conn);
CMD.ExecuteNonQuery();
CMD = new SQLiteCommand("DELETE FROM USERS", E.Conn);
CMD.ExecuteNonQuery();
CMD = new SQLiteCommand("DELETE FROM SETTINGS", E.Conn);
CMD.ExecuteNonQuery();
E.Dispose();
CMD.Dispose();
Cursor = null;
}
else goto Import;
}
#endregion
Import:
ButtonsPanel.IsEnabled = false;
FrmClose.IsEnabled = false;
BW.WorkerSupportsCancellation = false;
BW.WorkerReportsProgress = true;
BW.WorkerSupportsCancellation = false;
BW.DoWork += BW_DoWork;
BW.ProgressChanged += BW_ProgressChanged;
BW.RunWorkerCompleted += BW_RunWorkerCompleted;
BW.RunWorkerAsync();
lblMessage.Content = "Done...";
ButtonsPanel.IsEnabled = true;
FrmClose.IsEnabled = true;
}
void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblMessage.Content = "Done...";
Progress.Value = 0;
}
void BW_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress.Value = e.ProgressPercentage;
}
void BW_DoWork(object sender, DoWorkEventArgs e)
{
Progress.Value = 0;
#region YearlyTax...
var INF = new IniFile(Path.Combine(Directories.OLD_DATAFOLDER, @"yt.txn"));
string[] T = INF.GetSectionNames();
Progress.Maximum = T.Length;
foreach (string M in T)
{
SQLiteCommand CMD = new SQLiteCommand(E.InsertSQL("YEARS"), E.Conn);
CMD.Parameters.AddWithValue("ID", Guid.NewGuid().ToString());
CMD.Parameters.AddWithValue("YEAR", M);
CMD.Parameters.AddWithValue("B6000", INF.GetDouble(M, "txt6000"));
CMD.Parameters.AddWithValue("I12000", INF.GetDouble(M, "txt12000"));
CMD.Parameters.AddWithValue("I100000", INF.GetDouble(M, "txt100000"));
CMD.Parameters.AddWithValue("I150000", INF.GetDouble(M, "txt150000"));
CMD.Parameters.AddWithValue("I200000", INF.GetDouble(M, "txt200000"));
CMD.Parameters.AddWithValue("I250000", INF.GetDouble(M, "txt250000"));
CMD.Parameters.AddWithValue("A250000", INF.GetDouble(M, "txtabove250000"));
CMD.Parameters.AddWithValue("SAMEKIT", INF.GetDouble(M, "samekit"));
CMD.Parameters.AddWithValue("VIVRANI", INF.GetDouble(M, "vivraniprapatrashulk"));
CMD.Parameters.AddWithValue("LATEFEESPERCENT", INF.GetDouble(M, "latefees"));
CMD.Parameters.AddWithValue("HOUSINGDISCOUNTPERCENT", INF.GetDouble(M, "housingdiscount"));
CMD.Parameters.AddWithValue("OWNERDISCOUNTPERCENT", INF.GetDouble(M, "completeownerdiscountpercent"));
CMD.Parameters.AddWithValue("WIDOWDISCOUNT", INF.GetDouble(M, "concessiontypediscount"));
CMD.ExecuteNonQuery();
lblMessage.Content = "Importing: " + M;
BW.ReportProgress(P++);
Thread.Sleep(30);
}
#endregion
BW.ReportProgress(0);
#region Wards...
T = Directory.GetFiles(Path.Combine(Directories.OLD_DATAFOLDER, "Wards"), "*.wrd", SearchOption.AllDirectories);
foreach (string M in T)
{
INF = new IniFile(M);
string[] Q = INF.GetSectionNames();
foreach (string L in Q)
{
SQLiteCommand CMD = new SQLiteCommand(E.InsertSQL("WARDS"), E.Conn);
CMD.Parameters.AddWithValue("ID", Guid.NewGuid().ToString());
CMD.Parameters.AddWithValue("WARDNUMBER", Convert.ToInt32(L));
CMD.Parameters.AddWithValue("ZONE", INF.GetInt32(L, "zone"));
CMD.Parameters.AddWithValue("NAME", INF.GetString(L, "name"));
CMD.Parameters.AddWithValue("MANAGER", string.Empty);
CMD.Parameters.AddWithValue("N1", INF.GetDouble(L, "m1"));
CMD.Parameters.AddWithValue("N2", INF.GetDouble(L, "m2"));
CMD.Parameters.AddWithValue("N3", INF.GetDouble(L, "m3"));
CMD.Parameters.AddWithValue("ON1", INF.GetDouble(L, "mn1"));
CMD.Parameters.AddWithValue("ON2", INF.GetDouble(L, "mn2"));
CMD.Parameters.AddWithValue("ON3", INF.GetDouble(L, "mn3"));
CMD.Parameters.AddWithValue("IN1", INF.GetDouble(L, "vm1"));
CMD.Parameters.AddWithValue("IN2", INF.GetDouble(L, "vm2"));
CMD.Parameters.AddWithValue("IN3", INF.GetDouble(L, "vm3"));
CMD.Parameters.AddWithValue("OIN1", INF.GetDouble(L, "vmn1"));
CMD.Parameters.AddWithValue("OIN2", INF.GetDouble(L, "vmn2"));
CMD.Parameters.AddWithValue("OIN3", INF.GetDouble(L, "vmn3"));
CMD.ExecuteNonQuery();
lblMessage.Content = "Importing: " + M;
BW.ReportProgress(P++);
Thread.Sleep(30);
}
}
#endregion
BW.ReportProgress(0);
#region Customers...
T = Directory.GetFiles(Path.Combine(Directories.OLD_DATAFOLDER, "Customer"), "custdata.cst", SearchOption.AllDirectories);
P = 0;
foreach (string M in T)
{
INF = new IniFile(M);
SQLiteCommand CMD = new SQLiteCommand(E.InsertSQL("Customers"), E.Conn);
CMD.Parameters.AddWithValue("ID", Guid.NewGuid().ToString());
CMD.Parameters.AddWithValue("DEMAND", CheckDemand(INF.GetString("data", "voterid")));
CMD.Parameters.AddWithValue("AADHAR", INF.GetString("data", "aadhar").Trim());
CMD.Parameters.AddWithValue("WARDNUMBER", INF.GetInt32("data", "wno"));
CMD.Parameters.AddWithValue("NAME", INF.GetString("data", "name").Trim());
CMD.Parameters.AddWithValue("CASTE", INF.GetString("data", "caste").Trim());
CMD.Parameters.AddWithValue("ADDRESS1", INF.GetString("data", "address1").Trim());
CMD.Parameters.AddWithValue("ADDRESS2", INF.GetString("data", "address2").Trim());
CMD.Parameters.AddWithValue("PLOTNUMBER", INF.GetString("data", "plotno").Trim());
CMD.Parameters.AddWithValue("MOBILENUMBER", INF.GetString("data", "mobile").Trim());
CMD.Parameters.AddWithValue("LEDGERBALANCE", 0);
CMD.ExecuteNonQuery();
lblMessage.Content = "Importing: " + Path.GetFileName(M);
BW.ReportProgress(P++);
Thread.Sleep(30);
}
#endregion
}
Any help is appreciated.
Thanks in advance.
|
|
|
|
|
That doesn't make a lot of sense:
var INF = new IniFile(Path.Combine(Directories.OLD_DATAFOLDER, @"yt.txn"));
If it's a static class, you can't create a variable or an instance of it!
So either you will get a couple of error messages telling you that, and your app won;t compile; or it isn't a static class at all, and the problem is in the class constructor.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Hello Friend,
sorry for my long code and IniFile is not static. moreover, IniFile is not static.
Here is the exception report:
System.InvalidOperationException was unhandled by user code.
Additional information: The calling thread cannot access this object because a different thread owns it.
And the line where I am getting the code:
var INF = new IniFile(Path.Combine(Directories.OLD_DATAFOLDER, @"yt.txn"));
|
|
|
|
|
So look at the line, and there are two possible parts:
Directories.OLD_DATAFOLDER Which looks like an enum , but we can't see it. If it's an enum then its won't be that.
new IniFile(...); Which means it's in the constructor, which we can't see.
You've got a cross threading error in code we can't see which probably shouldn't be using threads and the fragment you show use doesn't use threading anyway.
That doesn't exactly make it easy for us to work out what your problem might be...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
It would be much more helpful if you put only the relevant parts of the code, and showed the exact text of the error message.
|
|
|
|
|
And what error do you get? I have the suspicion that you're trying to access UI controls from this thread, but as you haven't told us what the exception is, we cannot say for certain.
|
|
|
|
|
Hello,
I would like to ask for a 'code review' of the project below, as I have never designed such a thing before and I wonder if there are any serious problems with the code/approach below.
Here's a little background - I create a bunch of small and mostly internal WPF applications for my company - usually for some file manipulation etc. For these programs, I would like to start collecting user info - who uses them, how often, most importantly - which version is used.
It's partly for my personal skill development, but I also want to introduce auto-updating for my apps - some of them have this feature already, but they rely on text files located on shared drive so obviously not a good solution.
The intended audience is not a large crowd, probably fewer than 50 users. The calls to the database will most likely happen only on the application launch.
The idea is that I have a generic 'helper' dll, which I reference in my projects so that in each of the programs I call a simple method and have the repetitive registration handling out of my mind. All the data is stored in a single Azure database called MyDB, and all the programs should connect through the same API (also hosted in Azure), called e.g. MyApi (myapi.azuresites.net).
So, looking from the point of view of a single client app:
public MainWindow()
{
InitializeComponent();
Register = new RegistrationHelper();
var progressInfo = new Progress<string>(p => StatusInfo = p);
Register.HandleRegistration(progressInfo);
}
Now, the helper library contains a smart constructor that will deduct all the info I need for my database (email is optional only for some programs with explicit registration):
private const string DefaultApiAddress = "<a href="https:
public RegistrationHelper(string email = null)
{
ApiUri = new Uri(DefaultApiAddress);
UserName = Environment.UserName;
MachineName = Environment.MachineName;
UserProvidedEmail = email;
CurrentAssembly = Assembly.GetEntryAssembly();
ProgramName = CurrentAssembly.GetName().Name;
ProgramVersion = FileVersionInfo.GetVersionInfo(CurrentAssembly.Location).FileVersion;
}
Then it has a public method for running handling the registration (which obviously should not block program execution):
public void HandleRegistration(IProgress<string> progressInfo)
{
Task.Run((() => HandleRegistrationAsync(progressInfo)));
}
Which calls a private handler:
private async Task HandleRegistrationAsync(IProgress<string> progressInfo)
{
try
{
progressInfo.Report("Connecting...");
RegisteredUserId = await GetUserIdAsync();
if (RegisteredUserId == 0)
{
RegisteredUserId = await RegisterUserByNameAsync();
if (RegisteredUserId > 0)
{
progressInfo.Report(string.Format("Newly registered. Id: {0}", RegisteredUserId));
}
else
{
progressInfo.Report("Registration failed");
}
}
else if (RegisteredUserId < 0)
{
progressInfo.Report(string.Format("Not registered. {0}", RegisteredUserId));
}
else
{
progressInfo.Report(string.Format("Updating user {0} info...", RegisteredUserId));
progressInfo.Report("Registered. Id: " + RegisteredUserId);
}
}
catch (Exception ex)
{
progressInfo.Report("Connection error");
if (ThrowExceptions)
throw ex;
}
}
And the methods that call the API are all pretty similar, structured as follows:
public async Task<int> UpdateProgramUsageAsync()
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = ApiUri;
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response = await client.GetAsync(string.Format("api/update/{0}/{1}/{2}/", RegisteredUserId, ProgramName, ProgramVersion));
return response.IsSuccessStatusCode
? Convert.ToInt32(response.Content.ReadAsStringAsync().Result)
: -1;
}
}
catch (Exception)
{
if (ThrowExceptions)
throw;
else
return -666;
}
}
Now, what's in the web API:
There is a single UserController (apart from the stuff that comes out of the box from the WebApi template). It contains the connection string to the database (hardcoded), plus a bunch of constants for StoredProcedures names and stuff like that.
Then, my controller methods are structured as follows:
private const string ConnectionString = "allthestuffsensitivetoconnecttodatabase";
[Route("api/getid/{username}")]
public async Task<int> GetIdAsync(string username)
{
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
var result = await ExecuteScalarCommandAsync(GetRegisteredUserByName, conn,
new[]
{
new SqlParameter(UserNameCol, username),
});
if (result != null && !(result is DBNull))
{
return Convert.ToInt32(result);
}
return 0;
}
}
return -1;
}
private async Task<object> ExecuteScalarCommandAsync(string commandName, SqlConnection conn, SqlParameter[] parameters)
{
using (var command = new SqlCommand(commandName, conn)
{
CommandType = CommandType.StoredProcedure,
})
{
command.Parameters.AddRange(parameters);
return await command.ExecuteScalarAsync();
}
}
Also, as for the methods that not only 'get' values, but also update database, I am using the GET as well.
The one below is a match of UpdateProgramUsageAsync() pasted above:
[Route("api/update/{userid}/{programname}/{version}")]
[AcceptVerbs("GET")]
public async Task<int> UpdateProgramUsageAsync(string userid, string programname, string version)
{
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
var result = await ExecuteScalarCommandAsync(UpdateProgramUsage, conn,
new[]
{
new SqlParameter(UserIdCol, userid),
new SqlParameter(ProgramNameCol, programname),
new SqlParameter(VersionCol, version)
}
);
if (result != null && !(result is DBNull))
{
return Convert.ToInt32(result);
}
}
}
return 0;
}
As you can see, it relies on stored procedures updating the database and returning some response codes. The procedures are pretty simple (get value, put value into a table, nothing fancy).
modified 12-Sep-15 10:21am.
|
|
|
|
|
And your question is?
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
Sorry - I was actually asking if it makes sense or are there any serious problems with the code.
|
|
|
|
|
... and?
Is there a question in that presentation you posted?
|
|
|
|
|