16,004,507 members
Sign in
Sign in
Email
Password
Forgot your password?
Sign in with
home
articles
Browse Topics
>
Latest Articles
Top Articles
Posting/Update Guidelines
Article Help Forum
Submit an article or tip
Import GitHub Project
Import your Blog
quick answers
Q&A
Ask a Question
View Unanswered Questions
View All Questions
View C# questions
View C++ questions
View Javascript questions
View Visual Basic questions
View .NET questions
discussions
forums
CodeProject.AI Server
All Message Boards...
Application Lifecycle
>
Running a Business
Sales / Marketing
Collaboration / Beta Testing
Work Issues
Design and Architecture
Artificial Intelligence
ASP.NET
JavaScript
Internet of Things
C / C++ / MFC
>
ATL / WTL / STL
Managed C++/CLI
C#
Free Tools
Objective-C and Swift
Database
Hardware & Devices
>
System Admin
Hosting and Servers
Java
Linux Programming
Python
.NET (Core and Framework)
Android
iOS
Mobile
WPF
Visual Basic
Web Development
Site Bugs / Suggestions
Spam and Abuse Watch
features
features
Competitions
News
The Insider Newsletter
The Daily Build Newsletter
Newsletter archive
Surveys
CodeProject Stuff
community
lounge
Who's Who
Most Valuable Professionals
The Lounge
The CodeProject Blog
Where I Am: Member Photos
The Insider News
The Weird & The Wonderful
help
?
What is 'CodeProject'?
General FAQ
Ask a Question
Bugs and Suggestions
Article Help Forum
About Us
Search within:
Articles
Quick Answers
Messages
Comments by Eric Lynch (Top 150 by date)
Eric Lynch
3-Jan-19 16:56pm
View
Sorry, I am a bit confused about your goals. I think you may be misunderstanding a few different concepts.
In your reply, you indicate an expectation for your method to return "a false result". Currently, your method cannot return any result, it is of type "void". If you want it to return a true/false result, you need to change its datatype to "bool". Though, based on the remainder of your sentence and your code, it seems unlikely that this is actually your intent.
Next, you indicate that you want to "return to the catch". Perhaps, you're using imprecise terminology, but this is not exactly how a "catch" works.
In the "have tried" section of your question, if any error (exception) were to occur in the "try" block, you would stop executing the code in that "try" block.
Instead, at that point, you would begin executing the first line of code contained in the "catch" block. Since, you currently have no code in that "catch" block, you would do nothing. Effectively, you would discard (ignore) the exception. You would then continue to the next line of code after the "catch" block.
Since you have no code after the "catch" block, you would then return nothing (void) from the "Adding" method.
While I am fairly certain this is not what you intend, I am less clear on what you do intend.
Rather than replying to my comment, I again you suggest you click "Improve Question" and edit your question to add more detail.
You need to be specific about at least two things:
1) What EXACTLY do you expect/want to happen if the code in the "try" block succeeds?
2) What EXACTLY do you expect/want to happen if the code in the "try" block fails? This is the code you want to put in the "catch" block.
Currently, in failure, you do nothing. Also, in either success or failure, you return nothing (void) from the "Adding" method.
Keep in mind that your code may fail at almost any line within the "try" block. For example, it might fail during your SQL query, or during your call to FonkA, or during your call to DeleteNonCorrectAdd. Any of these failures, would result in the code "skipping" to the first line of code in your "catch" block.
Eric Lynch
3-Jan-19 15:17pm
View
Typically, if you have a catch block, you should DO something with the exception. There are many possible actions you can take. Some common options include logging the text of the exception, re-trying the operation (for more specific exceptions like timeout), and returning an indication that the operation failed. It is seldom a good idea to simply discard the exception (as your "have tried" code would do).
It might help if you improve your question to describe your problem a little bit better. What were your expectations from the code you tried? How did the results you observed fail to meet those expectations? Its unclear from your current question if you are simply struggling to understand try/catch or you have some specific, desired outcome that you are having trouble implementing.
Eric Lynch
21-Nov-18 6:51am
View
You may want to consider clicking "Improve question" and sharing the actual text of the exception. Beyond simply letting you know that "something" has gone wrong, the text of the exception describes that "something" and can provide clues for fixing it.
Eric Lynch
20-Nov-18 8:52am
View
FWIW, here is the similar code I experimented with (which works fine). I also tried almost everything I could think of to make it fail in a similar fashion (without success).
using System;
using System.Data;
using System.Windows.Forms;
namespace CodeProjectQAForms
{
public partial class MainForm : Form
{
public MainForm() =>
InitializeComponent();
private int id;
private void addButton_Click(object sender, EventArgs e)
{
var table = listBox1.DataSource as DataTable;
if (table == null)
return;
table.Rows.Add((++id).ToString());
// table.Rows.Add(); // Also tried this
editButton.Enabled = removeButton.Enabled = table.Rows.Count > 0;
}
private void MainForm_Load(object sender, EventArgs e)
{
var table = new DataTable();
table.Columns.Add("name", typeof(string));
listBox1.DataSource = table;
listBox1.DisplayMember = "name";
}
}
}
Eric Lynch
20-Nov-18 8:12am
View
As to "I worrying about this being a bug"...don't worry its definitely a bug...unless you intended the exception :)
Seriously though, a lot of the suggestions were to help you fight assumptions. When you're trying to debug a confusing problem like this, assumptions are your biggest enemy.
Let me give you an example: "other parts of my code is not getting involved logically". If your code were working the way you intended, this would be a safe assumption. Regrettably, the code is not working. Something is happening that neither of us understand. Given this, you can no longer safely make that assumption.
Here's something I do know for certain...through experimentation...not assumption. I've written code, from scratch, that was as close as I could make it to yours. It did NOT have the same problem. So, what you're trying to do is absolutely possible. Something that is non-obvious in your code is causing a different behavior (the exception).
You may want to revisit my earlier suggestions without dismissing them so easily this time. If you want to solve this problem, the only assumption you can make is that you "know" nothing :) You'll need to confirm everything through observation or experimentation.
As to the meaning of a "mis-wired events"...each of the components on your forms (Button, ComboBox, ListBox, etc.) has a whole bunch of possible events (e.g. Click) that are associated (wired) to a given method (e.g. btnAdd_Click). Ideally, each event is wired to the method you intended.
Unfortunately, this is a case where the behavior is not evident in the code you have shared. I have seen cases where an event, either through human error, or project corruption becomes wired to an unintended method. This can cause some very strange behavior. You can check how events are wired by clicking on each of the components and looking at the event tab in properties.
I suggest improving your question to share all of these associations (between event and method).
This is an example of where assumptions can hurt you. You "assume" that all of your events are properly wired, but until you double-check you can't be certain.
If even one event is mis-wired, commenting out code or setting breakpoints, in all of the methods, are techniques that might have helped you to discover the problem. These same techniques can help uncover other incorrect assumptions.
There are similar reasons, gained through about three decades of experience, behind the other suggestions. I'd explain each, but feel this answer is already approaching novel length :)
Though, I will reiterate one suggestion. Please double check that code you have shared, for the form, is complete and identical to what you are actually running. I know it sounds silly, but in the past, I've tried to help someone only to MUCH later discover that we weren't debugging the same code.
One footnote...it is actually expected behavior that SelectedIndexChanged is NOT called. System.Windows.Forms.ListBox.set_SelectedIndex, which changes the index, fails. SelectedIndexChanged (past tense) is called AFTER the index changes, which never happens, because of the failure.
Eric Lynch
19-Nov-18 10:03am
View
I took a look at your stack trace and I have to admit that I am a bit mystified. From the stack trace, as you mention, the exception appears to occur during the call to dt.Rows.Add. This call, for some reason, internally results in a change in the selected index for some ListBox (possibly listBox1). However, by the time that call occurs something has changed such that the proposed index value is no longer valid.
I tried to re-produce the circumstances with my own code, but was unable. There seems to be something that is not evident in the code that you have shared.
So, regrettably, I'm left guessing a little bit. I think this one may be difficult to debug.
My first guess is that, like you, I'm missing something obvious. If that's the case, I may be the wrong one to help you :)
Another possibility is that you have a mis-wired event. I'd check all of the events, for the components on your form, to be certain that they are ALL wired to the method you expect. Also, it might be worth improving your question to share this wiring. Its not evident in your code.
Another guess, perhaps you are not sharing all of the current or relevant code for your form? I'd check that and improve your question, if necessary.
Next, I'd take care of the low-hanging fruit. Clean up what you can. For example, Dispose where you should dispose. Also, consider the line dt.Rows.Add(). Is this truly what you mean to do? Add a row where all of the column values are null? This seems odd.
Also, the relationship between your combo-box and list-box seems unusual. When the combo-box changes, you are changing the data source for the list box. It seems you are refreshing the list box entirely independent of the new index value for the combo-box. This is unusual.
Also, in the debugger, I'd set breaks in every single method in your form. Is one getting called at a time that you are not expecting?
I'd use the debugger to take a hard look at your DataTable. Does it have the expected columns, with the expected values, and with the expected constraints?
Admittedly, the suggested code clean up is not very likely to fix your issue. However, the more variables you can eliminate the easier it is to track an issue.
Finally, if you reach the point of desperation, as a last resort, there is another trick I've found helpful in these situations. Start commenting out code until your issue disappears. Then back track, uncommenting, until you figure out the minimum code required to reproduce it. This can at least narrow what you need to consider to fix it.
Hope some of this helps or someone else sees the obvious and points it out.
Eric Lynch
18-Nov-18 23:49pm
View
The debugger will usually point you at the exact line a bit easier...hence the suggestion. Getting a bit sleepy, so I'll have to take a look at the stack trace tomorrow.
Regarding GC, its great at reclaiming allocated memory...at some point after instances pass out of scope.
IDisposable solves a different problem. With IDisposable, there is often an unmanaged resource (network connection, file handle, etc.) associated with the instance. GC seldom does anything to reclaim these resources. So, if a class implements IDisposable, you really should call the Dispose method (usually implicitly via a using statement) to avoid leaking these resources.
Honestly, this cleanup is often (not always) a bit of legacy baggage at the boundary of where .NET began and traditional windows APIs continued.
C# is really helpful in this respect. The using statement guarantees that disposal occurs even in the presence of exceptions. Of course, your always free to use try/finally blocks, and call Dispose yourself, to accomplish a similar, but less concise, outcome :)
Eric Lynch
18-Nov-18 16:20pm
View
If you run this in the debugger, that should help you to isolate the exact line at which the exception occurs. Sharing this information may help us to help you.
While not the cause of your problem, I do note one thing you should fix. Many classes are IDisposable (e.g. SQLiteCommand and SQLiteDataAdapter). In general, if a class is IDisposable, you should either wrap it in a "using" statement or eventually call the Dispose method. Otherwise, you will leak resources.
Another thing...it is unlikely that, in List_Load, when you set the value of comboBox.SelectedIndex to 1, that this is a valid value. At the time the form is loading, unless you pre-populated the combo-box, this would not be valid, since the combo-box would be empty. A value of 1 implies there are at least two elements. A value of 0 implies there is at least one element. When no elements are present, SelectedIndex is traditionally -1, though you should not set it to this value either.
Eric Lynch
16-Nov-18 16:45pm
View
Hopefully, this isn't a double post. My prior comment seems to be missing.
As 0x01AA notes, the correct (mathematical) maximum for these three numbers (0, 28.444, and 28.444) is 28.444. What did you expect?
In an earlier comment, you assert that the debugger does "not show a value" for d3. This is perplexing in two ways. First, this should be impossible for a value type (which defaults to zero). Second, it is inconsistent with the assertion above...that the value of d3 is "0".
Did you perhaps forget to share that an exception occurred (and share the exception text)?
I'll again re-iterate that IsNullOrEmpty is not the only invalid input text. For example, "Mickey Mouse" is not a valid decimal number. This is why I strongly suggest you either add a try/catch block or use decimal.TryParse instead of decimal.Parse.
Eric Lynch
16-Nov-18 14:11pm
View
Here, the debugger is your friend. Things I would examine in the debugger...
1) What are the values of your input columns: rows.Cells[41].Value, rows.Cells[46].Value, and rows.Cells[37].Value?
2) What are the results of your conversions: d1, d2, and d3?
3) What is the result of your intermediate Max operation: AL?
4) What is the result of your final Max operation: AL?
5) What is your expected result and how is it different than your actual result?
I guarantee one of these things (probably items 1 or 2) are not what you think.
Folks here can't see your screen, or run the debugger for you, so we're at a disadvantage.
At a minimum, you should improve your question to provide your actual input values (columns 37, 41, and 46), your actual output value (AL), and your expected output value. If any errors occur, you should also include that information.
BTW, instead of decimal.Parse, you may want to consider decimal.TryParse. The latter allows you to catch and handle invalid input more efficiently.
Eric Lynch
16-Nov-18 12:48pm
View
Cool, thank you for the confirmation. I swear I Googled my brains out, but still didn't find that link :)
If you'd been a bit quicker you could have saved me writing a program, out of desperation, to find what other folks were doing.
FWIW, adherence to this convention is spotty at best. Almost all of my installed UWP apps are from Microsoft, but I still found three vendors who ignored it.
The most notable exception was Twitter...which reminds me, I need to do a better audit for bloatware :)
Eric Lynch
5-Nov-18 8:49am
View
Depends on the exact requirements, but it sounds like you may be able to get away with a simple pixel-by-pixel comparison. After you screen capture, that would basically be a comparison and accumulation inside a couple of nested loops, with the outer loop by row and the inner loop by column. Its comparatively resource-intensive...not sure you'll get the performance you need for anything near real-time.
Eric Lynch
5-Nov-18 8:49am
View
Deleted
Depends on the exact requirements, but it sounds like you may be able to get away with a simple pixel-by-pixel comparison. After you screen capture, that would basically be a comparison and accumulation inside a couple of nested loops, with the outer loop by row and the inner loop by column. Its comparatively resource-intensive...not sure you'll get the performance you need for anything near real-time.
Eric Lynch
5-Nov-18 0:09am
View
Dang...I was hoping someone else would say it. First, I admire your ambition.
That said, I recommend starting with the basics. Select a stack...C#/.Net, Java, or something else?
Personally, I like WinForm C#. Progress to "Hello World!"...search for it...it's a meme for every technology.
Then, progress to basic image processing. What is a pixel? How is it represented in a complex image? How do I compress/de-compress a complex image format, like JPG/PNG?
Then, if you're still in the game, consider image recognition. Have I seen this picture before? This is (perhaps) the single biggest challenge in our industry...so, don't expect it to be easy :)
In short, I encourage you to answer and pursue your original question...with gradual progress...perhaps with a bit more humility :). It's a difficult question and worth anyone's effort.
If this is NOT your goal...and I truly hope I'm wrong...there are many folks who've already struggled with this same question and found a (very) limited solution. Check out / purchase one of these efforts (Google is your friend).
In either case, best of luck. You picked a very challenging goal to start. Stick with the problem and you might become a world-class engineer. Again...best of luck!
I personally hope you ignore the naysayers. If so, please realize you chose an awesome profession (IMO). There are countless talented folks out there. I hope you join their ranks. In my experience, it's about 50% talent and 50% effort.
Eric Lynch
4-Nov-18 0:40am
View
It sounds like you've made an honest effort to solve the problem. So, why not click "Improve question" and share the actual code you've tried?
That way, folks here can help point out where you've gone wrong, instead of writing it for you.
Eric Lynch
3-Nov-18 22:53pm
View
I suppose it is possible...I don't know the OP. Also, as I mentioned in the solution, I'm not familiar with DevExpress.
That said, it doesn't seem like I'm exactly sharing state secrets here :)
I'm not providing anything more than is available either with the free MS documentation (for the standard control) or the free DevExpress documentation (I found with Google).
Eric Lynch
2-Nov-18 20:29pm
View
For a response to a solution, you should really click "Have a Question or Comment?" on that solution...not "Add a Solution" on the question.
Eric Lynch
28-Oct-18 16:35pm
View
I do not intend to be unkind with this information. I realize language skills vary. I've worked in other countries where I did not speak the language. People were very kind to me there.
I hope to return the favor by offering the following glossary and suggestions.
In SQL, a "table" is composed of "columns". A "table" is uniquely identified by a "table name". For example, a table containing information about people might be named "People".
Each column has a "column name". For example, a column named "Country" might contain a value "India". It is unlikely you would have a column named "India".
A "row" is a set of values for the "columns" within a "table".
A "file" is typically something maintained by the operating system. While related, it is different/distinct from a SQL "table". A "path" is typically a unique identifier for a "file". A "file name" is typically a non-unique portion of a "path".
Different "files" contain different types of data. Excel would be one type of data.
Given this information, it would be helpful if you could do the following.
1) Provide the name of the SQL table that is causing you problems.
2) Provide the names (and data types) of the columns contained in this table.
3) Provide the names of the columns you want to (I think?) extract from this table and write to an Excel file.
4) If you are limiting the rows you want from this table, provide more specific information about this limit. For example, "WHERE Country = 'India'".
5) Be more specific about the format for your output file. For example, a CSV file (column-separated-value) is easily written and can be read by Excel. Is this sufficient? If not, writing a "true" Excel file is more difficult.
6) As OriginalGriff suggests, be more specific about the sort of help you need. For example, if you actually wrote some code that failed, share the code, share the error. We can all read code. There, language difficulties are less important.
Hope this helps you word the question. As written, its very difficult to help you.
Eric Lynch
23-Oct-18 13:05pm
View
Dang it, you beat me to it, so I upvoted your answer.
I was busy over-engineering, for stuff the OP probably doesn't care about...but I was having fun.
With your solution, the ascending numeric order would not be preserved. Also, there's the matter of the bad input data. I'm guessing the trailing comma (on S2) was unintentional, but you never know.
So, just in case, I posted the long-winded version. I might have tied you, but then I went back and added comments :)
Eric Lynch
23-Oct-18 9:16am
View
No problem, happy to help.
I suggest spending some time familiarizing yourself with XPATH syntax. Its fairly powerful (and not terribly difficult to learn).
If you'll be playing with XML longer term, I'd suggest checking out the newer LINQ to XML APIs (XDocument). I find them easier to use than the original API's (XmlDocument).
I've updated the solution to include links for both.
This site (CodeProject) provides many introductory articles on LINQ itself. Even if you're not planning on playing much with XML, LINQ is well worth your time. Its useful almost any time you're manipulating collections of items.
Eric Lynch
18-Oct-18 10:06am
View
Nah, I was only joking, truth is credit goes to MS on this one. They made it easy. I often vent about them, but I think they did a nice job with the XML APIs in C#.
Eric Lynch
18-Oct-18 9:48am
View
You're code is reversing the order. You march through the children in the order they appear, but then you pre-pend (add to the beginning). I think the AppendChild method would have resulted in the correct order.
Though, pretending humility here, I think my code is prettier :)
Eric Lynch
18-Oct-18 9:46am
View
No problem, happy to help. Also, congrats on getting closer to a solution on your own.
If you're going to continue playing with C# and XML, I highly recommend learning LINQ to XML. To answer this question, its only slightly more concise. However, for other problems, it saves a lot of code and time. Happy coding!
Eric Lynch
18-Oct-18 9:30am
View
Please see solution 2, which presents in the correct order.
Eric Lynch
17-Oct-18 18:29pm
View
First, the XML file in your question is not valid. It has a closing tag, for the Steps element, but no opening tag.
Next, its not entirely clear to me what problem you have encountered. Perhaps, after fixing the XML file in your question, you could (at a minimum) add your expected output. And, if you experienced a problem, your actual output. This would more clearly illustrate the difference between the two (expected and actual).
Finally, you may want to consider using LINQ to XML instead. Personally, I find this interface a little friendlier to use. Here is a link:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml-programming-overview
Eric Lynch
11-Oct-18 11:38am
View
If you want an answer, other than a link to one of those tutorials, you'll need to provide more detail.
Click "Improve Question". Show what you've actually tried (code-wise) in "What I have tried". Don't simply repeat your description.
Clearly, you didn't get the expected result. So, something must have gone wrong. Improve your description to clue us into what happened. Did you get a compile error? If so, what was it? Did you get a runtime error? If so, what was it? Did you observe a behavior you didn't expect? If so, what was it?
We can't see your screen. So, without this information, all we can do is take guesses or post a link.
Eric Lynch
6-Oct-18 10:13am
View
Simply add a "last chance" try/catch block. Where exactly, depends on the type of application. For most types, you can place it around the logic in the Main method. For web apps, its a bit different, but same concept.
Or, you could simply run it in the debugger, which will normally break at the offending line, when an exception occurs.
Eric Lynch
6-Oct-18 8:26am
View
Simply checking, you do understand that your stored procedure ends at the first GO, correct?
The rest is simply scripted SQL that is NOT part of your stored procedure. It might get executed in SSMS, but will never get executed when you call your SP.
To be clear, this is the entirety of your stored procedure:
ALTER PROCEDURE [dbo].[SPNULL]
(
@errorstat AS INT = 0
)
AS
WHILE @errorstat = 0
BEGIN
BEGIN TRY
UPDATE suppDB
SET ldgrid = 0
WHERE ldgrid IS NULL
ALTER TABLE suppDB
ALTER COLUMN [ldgrid] INTEGER NOT NULL
ALTER TABLE suppDB
ADD CONSTRAINT sldgrid
DEFAULT 0 FOR ldgridif @@ERROR <> 0 OR @@ERROR = 0
BEGIN
PRINT '0'
END
END TRY
BEGIN CATCH
PRINT '1'
END CATCH
END
If you want the rest of this to be part of your SP, you'll need to enclose the entirety of the SP (after AS) in a BEGIN/END block and re-factor to eliminate the "GO" statements (inside the SP).
Also, as others have mentioned, the approach you've selected doesn't make much sense.
Eric Lynch
5-Oct-18 15:25pm
View
You might consider adding some indentation to help both yourself and us match the begin and end tags visually. I simply don't have the time to wade through your code without indentation.
At a quick glance, trying to match your begin/ends, it seems like you may have posted both your stored procedure and a bunch of extraneous scripted code outside your stored procedure. Near as I can tell, your stored procedure seems to end at the first "GO" statement.
Perhaps this is the cause of your problem?
If not, I'd recommend adding some indentation and using the "improve question" button to post only what you beleive to be your stored procedure.
Additionally, the logic in your stored procedure seems very suspect. In general, repeatedly altering tables is not a particularly good idea.
I'm guessing maybe you had some problems with your update and, instead of diagnosing those problems, tried slapping on this ill-advised band-aid?
I'd recommend maybe starting over and asking for help with the original problem...assuming you aren't able to resolve it yourself.
Eric Lynch
3-Oct-18 21:56pm
View
To use any of the Java methods, you need to have a basic understanding of how they work. Since there are already a lot of good explanations elsewhere, it doesn't make much sense to repeat those explanations here. For example, a quick Google provides the following link which has a number of different examples of reverse sorting...
See: https://www.geeksforgeeks.org/collections-reverseorder-java-examples/
I recommend you read the explanations, copy the code that's closest to what you want, run it in the debugger (so you can see it work), and then make the small number of changes necessary to solve your exact problem.
Eric Lynch
2-Oct-18 10:17am
View
The specified link provides an example where XML in multiple table rows is updated. Depending on your exact requirement, you need to either change, or omit, the WHERE clause in the SQL UPDATE. To change exactly what is updated in each XML document, you would need to adjust the XPATH selector.
As mentioned, in the response, its to "get you started"...not to write it for you.
Its unclear, from your response, if you're having trouble updating multiple SQL rows, trouble updating multiple XML elements (presumably within a column for each of those rows), or if you're conflating the two very different concepts.
If you're having trouble updating multiple SQL rows, you should become more familiar with the SQL UPDATE command, which makes this quite easy. See: https://www.w3schools.com/sql/sql_update.asp.
If you're having trouble understanding the XML data type methods, which allow you to play with XML text, see: https://docs.microsoft.com/en-us/sql/t-sql/xml/xml-data-type-methods?view=sql-server-2017.
If you're having trouble selecting multiple XML elements, to update, you should become more familiar with XPATH. See: https://www.w3schools.com/xml/xpath_syntax.asp.
All the parts you need are demonstrated in the original link (provided in the solution).
If you need someone to put all the parts together, and write it for you, its not really what Q&A is for, but you might still have some luck here. However, you'll need to provide a lot more detail in your question, for someone to do that.
You're more likely to get assistance, if you have some specific question about an element of the larger problem.
In any case, hope this helps you to either get started on a solution or clarify your question. Best of luck.
Eric Lynch
28-Sep-18 8:00am
View
If you've tried the above, something must have gone wrong. Otherwise, you wouldn't be here asking questions :)
Generally, in C#, if "something goes wrong" an exception is thrown and (unless you handle the exception) it is displayed somewhere. If you really want help, you'll need to share the details of that exception.
There are a bunch of different things that can "go wrong". Some examples include: you (as a user) are not authorized to access the database, you've provided an incorrect database name, SQL server is not running, the connection is blocked by a firewall or other network setting, some problem has caused a timeout before the connection is completed, or many, many other possible issues.
To help you, we need to know which of these many possible issues is the cause. The exception usually provides enough detail to (at a minimum) restrict the number of possibilities. Once we know what issues might be possible, we might be able to provide some advice about how to fix that specific issue (or issues).
Without that information, all we can do is guess, which is both a waste of our time and unlikely to help you.
Of course, this all assumes your code actually compiles. As others note, the variable "connetionString" is undefined, so either the compilation should fail or your question does not include the code you actually tried (perhaps a typo?).
As a secondary issue, OriginalGriff is correct, you shouldn't hard-code connection strings in the source code. Generally, I usually save these in either the application or web configuration file. If you also add the type of application you are writing (Web or WinForm/WPF/Console) into your question, you might get more specific information about how this is done.
Hopefully, you'll add enough information, to your question. help us to help you. Good luck.
Eric Lynch
4-Sep-18 20:59pm
View
How about this one?
https://www.learn-c.org/
Eric Lynch
4-Sep-18 15:55pm
View
no problem
Eric Lynch
4-Sep-18 15:47pm
View
It looks like you may have replied about the same time I updated. I'd take a look at the update and consider, if possible, consolidating databases. This is the better solution. That way you don't have to maintain multiple databases, connection strings, etc. An approach is suggested in the update.
If you decide to limit to two databases as above, in response to "where to put this?" The correct question is not "where" but "when". The answer is in the original response: "after your login is complete". You must have some code/event that validates your login. You would put it immediately after validation is completed.
Eric Lynch
4-Sep-18 13:20pm
View
No problem...glad I could help. Sorry, if I got a bit curt, you were confusing me a little :)
Eric Lynch
4-Sep-18 13:07pm
View
Updated the solution with my best guess of what you want...more details would have helped.
Eric Lynch
4-Sep-18 12:40pm
View
I really have no idea what you are trying to accomplish here. Please click Improve Question, to add a lot more clarification to your original question. That question implied that you had already saved your image to a file named testImage.jpg and were expecting to use the default image viewer. I have no idea what this reply suggestions.
So, if you want help, please Improve your original question to include the following information:
1) Do you want to use the default image viewer to view your image? If not, list the name of the application you expect to use.
2) Have you saved the image to the file testImage.jpg (as your question implies)?
3) If you have not saved the image to file yet (and this will be necessary), do you hope to save the image from the picturebox?
Eric Lynch
4-Sep-18 12:33pm
View
I replied to your file path issue, you were mistakenly specifying two backslashes (see earlier reply).
In this update, are you saying that you have not successfully saved the image to disk...to the file C:\testImage.jpg you mention in your original code?
If not, why would you expect the file testImage.jpg to exist? If this is the case, you really need to clarify your question (a lot).
Eric Lynch
4-Sep-18 12:26pm
View
Amending my previous reply, I can help. Your path is definitely wrong. Either get rid of the "@" or use a single "\". With both there, the path is wrong.
To clarify, if you use an "@", it means that "\" is interpreted literally, so "\\" is two backslashes. Without the "@", it means that the "\" is interpreted as an escape sequence, so "\\" is one backslash.
In Windows file paths, one backslash is all you need.
Eric Lynch
4-Sep-18 12:24pm
View
That I cannot help you with. The error is very specific. You need to double check the file path. Either you have it wrong, or you don't have read access to the root directory.
Eric Lynch
4-Sep-18 12:23pm
View
Deleted
That I cannot help you with. The error is very specific. You need to double check the file path. Either you have it wrong, or you don't have read access to the root directory.
Eric Lynch
4-Sep-18 12:19pm
View
I'm having a bad day today...fixed for real and tested this time.
Eric Lynch
4-Sep-18 12:17pm
View
sorry...typo on my part...fixed.
Eric Lynch
3-Sep-18 14:26pm
View
The problem is that you're not providing enough information for people to understand your question and help. Try improving your question to include information like:
1) your input XML
2) your expected output
3) your actual output
4) a brief description of how your expected output differs from your actual output
As your question currently stands, we understand that its "not working", but we have no idea about what (exactly) fails to meet your expectations.
Eric Lynch
31-Aug-18 15:48pm
View
Great catch and almost certainly the correct solution!
Though, proper exception handling and checking of return values, neither of which occur in the OP's code, is still good practice.
On the plus side, kudos to the OP for correctly using SQL parameters. Its nice to see that for a change :)
Eric Lynch
31-Aug-18 14:10pm
View
You're hiding any exceptions by catching them without doing anything. Show a message box or log it. And, if there is an exception, share that exception, it might help to diagnose the problem. Also, ExecuteNonQuery returns the number of rows actually affected (in this case updated), you should share that as well to help diagnose the problem.
Eric Lynch
29-Aug-18 17:35pm
View
it takes a while, because there's a lot to learn, but its worth the effort. the good news, once you've learned C# syntax, you've pretty much also learned Java syntax...they are very similar :) good luck!
Eric Lynch
27-Aug-18 12:54pm
View
Great news, happy it helped.
Eric Lynch
25-Aug-18 8:46am
View
I applaud the OPs ambition. Sometimes, it takes someone who "doesn't know any better" to accomplish the impossible. That said, I'd be comfortable betting against it, the impossible usually wins :)
Eric Lynch
25-Aug-18 8:26am
View
And once again, I find myself wishing I could upvote a comment :)
Eric Lynch
25-Aug-18 8:22am
View
Is it wrong that I wish the hurdle to starting Facebook was much higher? :)
Eric Lynch
23-Aug-18 16:38pm
View
You seem to want a short cut to learning C#. None exist. You have to read a lot more and learn to understand. At a minimum, you need to understand the large building blocks. Things like: What are classes? What are methods? How are methods used?
In this case, you have a class Replace and a method DoSomeStuff that are simply never used. The syntax is fine, so they'll compile fine and you'll get no errors.
So, ask yourself some questions. Why does my program output "Hello World!"? Who creates an instance of the class Program? Who invokes the Main method in the Program class? The answers are simple. When you create a console application, by default, the operating system will create an instance of the Program class and invoke the method named Main. This is all explained in the "Hello World" link I shared.
Now ask yourself the same questions about the Replace class and the DoSomeStuff method. Who creates an instance of the class Replace? Who invokes the DoSomeStuff method in the Replace class? The answer are as follows. Nothing creates the Replace class...you include no code to do that. Nothing invokes the DoSomeStuff method...you include no code to do that.
As discussed, console applications have some default behaviors for the Program class and its Main method. That's it...nothing else. They don't have default behaviors for other classes or other methods. Those classes and methods sit there and do nothing unless you provide code to actually use them.
This all goes back to basics. A class is basically a description of something: a car, a building, a piece of belly lint, or something else. By itself, its only that: a description. Until you actually create a car, or a building, or (yuck) belly lint, you have a description that sits there and does nothing. When you create a class, its called instantation. In C#, you create a class instance with the "new" keyword.
For example, within a method (like Main), you could add the following:
Replace replacer = new Replace();
A shorter syntax is as follows:
var replacer = new Replace();
Once you've created a instance of the Replace class, you are free to refer to any of its accessible constants, fields, properties, or methods. For example, if you wanted to invoke its DoSomeStuff method, the syntax would be:
replacer.DoSomeStuff();
Please go back and read a lot more about C# syntax. There are many excellent books on the topic. Also, the following can provide a good starting point, with links to many relevant topics.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
We all start out somewhere and a lot of people on this site, myself included, are willing to give you some help, when you get stuck. It seems like you have some good intuition for syntax. My recommendation would be to read a bit more and then play with a some of the code samples that are available online, until you REALLY understand how they're put together and work. There are a bunch of them out there.
Trying to learn the basics from Q&A isn't very effective.
Hope this helps. Best of luck.
Eric Lynch
22-Aug-18 16:24pm
View
You might want to start over. When you first create a console application project, it contains a Program.cs file, which contains a Program class and a static Main method. The Main method is automatically called, by the operating system, when you execute the program. By the error you mention, it sounds like you have somehow deleted (or illegally altered) the Program.cs file.
Traditionally, when folks start programming, they start by writing a "Hello World" application. I'd make sure you fully understand that before moving on.
See: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/hello-world-your-first-program
Eric Lynch
22-Aug-18 10:23am
View
A quick Google provides a link to the manual...
http://www.gpstracker.in/pdf/L100%20Manual.pdf
Eric Lynch
21-Aug-18 12:57pm
View
Since you're starting from C#, you may want to check out the following:
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/bulk-copy-operations-in-sql-server
Eric Lynch
20-Aug-18 8:00am
View
I agree with ppolymorphe, you need to add your XSLT file to the question. Because its missing, I'm guessing (maybe) you didn't try anything yet. Give it a try!
Update your original question to add the XSLT and ask for more specific help. Then, I think you'd find a lot more people willing to help you. Few people, myself included, are likely to write the entire thing for you. We usually get paid for that sort of "help" :)
Here are a couple of links to get you started. Good luck.
https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor/Basic_Example
https://www.w3schools.com/xml/xsl_intro.asp
Also, you might want to mention how you plan to execute the XSLT transform. For example, are you planning to use a command line tool? If so, which one? Or, are you planning to invoke it from some programming language? If so, which one?
Eric Lynch
20-Aug-18 7:19am
View
You're welcome...happy I was able to help :)
Eric Lynch
17-Aug-18 16:32pm
View
Honestly, for line 3, I'm am surprised you do not see the same problem. If it is truly instantiated, and utilized, I can not see why "check" would not also cause an issue. To answer questions, about the difference, I would need to see both the instantiation and utilization of both classes.
Since I cannot, I suspect maybe you are assuming a similarity in instantiation or utlization that does not exist. If you are describing everything accurately, and completely, the difference in behavior between two nearly identical classes makes zero sense. The only difference in declaration is a difference in class protection ("public" vs default). This would not make sense as an explanation for the difference in behavior...absent an accompanying difference in instantiation / utilization.
Eric Lynch
10-Aug-18 9:17am
View
I wish I could upvote a comment :)
Eric Lynch
10-Aug-18 8:35am
View
Correct on both counts...and worth pointing out to other readers.
Regarding my solution, I am aware of the newer operators. I considered using them in my solution, but decided against it. I wanted to teach him how to convert his loop, without troubling him with having to also learn the newer language features. The code provided was as much like his original as I could make it, to illustrate the differences between using foreach and LINQ.
I am also aware of the perils of premature materialization. However, in his example, selectedList was specifically declared as a list, which is why I included ToList. For other readers, for more information on the perils of premature materialization, please check out my earlier article:
https://www.codeproject.com/Articles/1236958/LINQ-Part-A-Deep-Dive-into-IEnumerable
The reason I wrote the article was to better explain IEnumerable and hopefully help people avoid the mistake of always tacking on ToList...or anything else that would trigger premature materialization.
On an unrelated note, I was surprised to see a two star rating on the solution. Not sure what I did to deserve that :)
Eric Lynch
9-Aug-18 7:46am
View
In your question, you didn't mention that you wanted to change the "transport" node. To change the "transport" node, you want the following:
XmlNode node = doc.SelectSingleNode("//security/transport");
You should really take the time to learn XPATH. This is the syntax for the parameter to SelectSingleNode. Then, you can answer this question for yourself. I'll leave changing the message node as a learning exercise :)
For information on XPATH syntax, see the following:
https://www.w3schools.com/xml/xpath_syntax.asp
For information on SelectSingleNode, see the following:
https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlnode.selectsinglenode
Also, if you'll be dealing with XML longer term, you may want to check out LINQ to XML. While the XmlDocument API continues to work fine, LINQ to XML offers many advantages. For more information on LINQ to XML, check out:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-queries-linq-to-xml
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/getting-started-linq-to-xml
With LINQ, if you're unfamiliar, you can choose between query syntax and method syntax. Query syntax is shown in many of the examples. Method syntax is more like traditional C# syntax. Any query syntax can also be expressed as method syntax. The reverse is not true.
Personally, I prefer method syntax. Either is fine, its up to you which works better for you. Basically, method syntax is a series of extensions to the IEnumerable interface. The following article summarizes the available methods:
https://www.codeproject.com/Articles/1240219/LINQ-Part-Standard-Methods-Tools-in-the-Toolbox
Eric Lynch
6-Aug-18 12:59pm
View
If everything is truly as stated, I don't see how this is possible. I think maybe you have missed some small difference between the two input files you are using in your test.
I would try the following experiment. Temporarily rename the input file that doesn't work. Copy the input file that does work to that same location. Re-try your test.
At this point, I would be shocked if you don't get the correct result in both cases. Then, if you need to debug the difference, get a hex dump and compare the working and non-working files byte for byte.
Eric Lynch
5-Aug-18 14:11pm
View
You are still not checking the return status from cmd2.ExecuteNonQuery(), as recommended. This would actually tell you if the update succeeded or not.
You are not displaying either success of failure, based on that return status. This would allow you to share that information with anyone who tries to help you. You also are still not reporting the value of the id variable, so you can check that it has the value that you think it does.
I can't tell if you've also removed the exception handling. If you have, this is also not good.
Finally, you do not want the quotes around the @name parameter. This will change the value of StudentName to the actual text '@name' instead of the parameter value.
I also suggested updating your question, not adding another comment. This might allow others to help you as well. When you do so, you should include relevant information, for the question, which is currently missing. Things like:
"no exception occurred" or "the exception text was ???" -AND-
"the return status from ExecuteNonQuery was ???"
Eric Lynch
5-Aug-18 14:11pm
View
Deleted
You are still not checking the return status from cmd2.ExecuteNonQuery(), as recommended. This would actually tell you if the update succeeded or not.
You are not displaying either success of failure, based on that return status. This would allow you to share that information with anyone who tries to help you. You also are still not reporting the value of the id variable, so you can check that it has the value that you think it does.
I can't tell if you've also removed the exception handling. If you have, this is also not good.
Finally, you do not want the quotes around the @name parameter. This will change the value of StudentName to the actual text '@name' instead of the parameter value.
I also suggested updating your question, not adding another comment. This might allow others to help you as well. When you do so, you should include relevant information, for the question, which is currently missing. Things like:
"no exception occurred" or "the exception text was ???" -AND-
"the return status from ExecuteNonQuery was ???"
Eric Lynch
5-Aug-18 9:55am
View
Great list! Although, I think I'll continue to cheat on the following assumption :) 11. People’s names are all mapped in Unicode code points.
Eric Lynch
5-Aug-18 9:44am
View
Procedural vs event driven programming is essentially acting vs reacting. You can find a bit more about it, plus other paradigms here: https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms
Eric Lynch
5-Aug-18 9:31am
View
I'd add some exception handling, to find out which cases cause the error, and then step through the debugger, for one of those cases, to find out which line causes the error.
Eric Lynch
5-Aug-18 1:50am
View
Come on! You've got the name "ppolymorphe" and didn't catch the "new" keyword on the InsuredPatient.AmountDue property and suggest changing it to a "virtual/override"? Such a missed opportunity :)
Eric Lynch
5-Aug-18 1:43am
View
Nice catch! I was busy asking for more info, trying to dissuade the OP from using the "new" keyword on an inherited property, and suggesting some ways to reduce clutter :)
Eric Lynch
5-Aug-18 1:36am
View
I second ppolymorphe's point. While it seems you have some problem related to PctPaid, it is unclear exactly wheat that problem might be. For example, does it affect all patients or only one? What were your expected values? What were your actual values? If you want to receive help in a timely fashion, the more information you include the better your results will be. Unlike you, we cannot see your screen or step through the debugger to look at things. We can only work with the information you provide us.
That said, though it won't help you fix your problem, I would like to suggest a couple of improvements to your code.
You repeat the following a couple of times in your code:
goodNum = true;
for (y = 0; y < x; ++y)
if (patient[x].Equals(patient[y]))
goodNum = false;
You might consider moving this into a "IsPatientValid" method, which you can call in both places. Also, you ask for a patient and then loop to ask for a valid patient. If you refactor slightly, you can reduce this duplication to a single loop that gets a valid patient.
Also, it looks like you are familiar with auto-implemented properties. You might want to use them more consistently. For example, the following:
double pctPaid;
public double PctPaid
{
get
{
return pctPaid;
}
set
{
pctPaid = value;
}
}
Could be:
public double PctPaid { get; set; }
It really cleans up the code quite a bit. You have a few places that would benefit from it.
Also, about this:
public new double AmountDue
Just don't! There are almost no cases where hiding an inherited member with the "new" keyword is appropriate. This is not one of them.
Add a "virtual" keyword to AmountDue in Patient and an "override" keyword in AmountDue in InsuredPatient. This may seem like a minor difference. Trust me. It is not.
Eventually, in some future program, that "new" keyword will cause you some major headaches. Using the "new" keyword, if you ever assign an InsuredPatient value to a Patient variable, you won't get the AmountDue you expect. You'll get the one from Patient...not from InsuredPatient. The "new" keyword simply hides the value in the parent class, but its still there waiting to cause you problems.
The "virtual/override" keyword pair replaces it. Together they provide one of the many wonders that is polymorphism :)
Eric Lynch
5-Aug-18 0:58am
View
OK. Without the space before the WHERE, which it sounds like you have now added, you would *definitely* get an exception. Hopefully, you've also corrected the many other problems I mentioned as well.
I'll add a new one. Many methods return a value. You should really check it. ExecuteNonQuery is one of those methods. It returns the number of rows that are affected (in this case updated) by the command.
If you have no exception, there are two possibilities. If the return value is non-zero, you are updating a different row than you expected. Otherwise, and more likely, if the return value is zero, then your WHERE clause is incorrect. In either case, most likely the value of "id" is not what you expect it to be.
I've been doing this a very long time. SQL is very accurate in what it reports. Assuming every thing you've mentioned is accurate, SQL will either throw an exception or return a zero value (to indicate no row was updated). The only other possibilities are that the row you expected was updated (but you didn't notice) or a different row than you expected was updated. I'll assume neither of these other possibilities is the case here (but its worth your double checking both).
The good news is that your WHERE clause is very simple. It should be easy to fix. Try either displaying the value of "id" in your "success" message or learning to use the debugger. I suggest the latter. The debugger will allow you to not only examine the "id" variable, but examine other variables and step through to check the flow of your code as well.
Regarding your code, while it is not the cause of your symptom, I'll add another problem to the list. You add the empty string ("") to the start and end of many of your strings. This is not necessary. For example, "" + "A" + "" is still only "A".
If you continue to have a problem, I suggest updating your question with all of the corrections to the code included. Also, I would update the question to include all of the missing information you fail to mention in your question. For example...add that the status field shows "Data updated successfully" and no exception occurs. And, if you check the return value, add that "the return value from ExecuteNonQuery is ?".
All of this missing information, when added, will help both you and anyone who attempts to answer your question to diagnose the problem.
Eric Lynch
5-Aug-18 0:57am
View
Deleted
OK. Without the space before the WHERE, which it sounds like you have now added, you would *definitely* get an exception. Hopefully, you've also corrected the many other problems I mentioned as well.
I'll add a new one. Many methods return a value. You should really check it. ExecuteNonQuery is one of those methods. It returns the number of rows that are affected (in this case updated) by the command.
If you have no exception, there are two possibilities. If the return value is non-zero, you are updating a different row than you expected. Otherwise, and more likely, if the return value is zero, then your WHERE clause is incorrect. In this case, most likely the value of "id" is not what you expect it to be.
I've been doing this a very long time. SQL is very accurate in what it reports. Assuming every thing you've mentioned is accurate, and no row is updated, SQL will either throw an exception or return zero value. There is simply no other possibility.
The good news is that your WHERE clause is very simple. It should be easy to fix. Try either displaying the value of "id" in your "success" message or learning to use the debugger. I suggest the latter. The debugger will allow you to not only examine the "id" variable, but examine other variables and step through to check the flow of your code as well.
Regarding your code, while it is not the cause of your symptom, I'll add another problem to the list. You add the empty string ("") to the start and end of many of your strings. This is not necessary. For example, "" + "A" + "" is still only "A".
If you continue to have a problem, I suggest updating your question with all of the corrections to the code included. Also, I would update the question to include all of the missing information you mention in your comment. For example...the status field shows "Data updated successfully" and no exception occurs. And, if you check the return value, add "the return value from ExecuteNonQuery is ?". All of this missing information, when added, will help both you and anyone who attempts to answer your question to diagnose the problem.
Eric Lynch
4-Aug-18 8:38am
View
Deleted
A few things...on your page load, you have a catch that simply discards any SQL exception. You should almost never do that. In general, you should either (at least) log or mitigate the exception. In your button click, you at least put the exception in some status text. Does an exception occur? Could you please share the text if it does?
Some final observation, you have resource leaks. You don't dispose of cmd at all. You don't dispose of sd. And, you don't dispose of cmd2, if an exception occurs.
I suggest you familiarize yourself with the C# using statement. A typical pattern would be:
using(var con = new SqlConnection(conStr))
{
con.Open();
using(var cmd = new SqlCommand(cmdStr, con))
{
// Do work here
}
}
With the using statements, there is far less chance you'll accidentally introduce a resource leak.
Adding one other point, you should use SQL parameters instead of string concatenation when building your commands. Otherwise, you are a very easy target for hackers via a SQL injection attack.
See: https://docs.microsoft.com/en-us/sql/relational-databases/security/sql-injection
Eric Lynch
1-Aug-18 23:54pm
View
Its a bit difficult to follow your terminology. By syntax (in your example), the following would be methods (NOT classes): MenuTop, MenuDown, Background, Player, Enemy, and Treasure. Though, by name, they do sound more like classes.
As an example, if you intend them to be classes, elsewhere you would typically instantiate them, something like the following:
private MenuTop menuTop = new MenuTop();
And, then perhaps in your ScreenPaint method, you might do something like the following:
menuTop.Screen_Paint(sender, e);
This would assume, that you had declared a method Screen_Paint, in the MenuTop class.
So, assuming you are clear on the terms, can you please improve your question so that it uses proper terms and matching syntax.
Alternatively, if you are unclear on the distinction between class and method, I suggest you might need to read a bit more about C# syntax and object oriented design in general before you try to tackle this problem. In the unlikely event this is the case, I'd be happy to provide some links to decent reading material.
Eric Lynch
1-Aug-18 20:20pm
View
Yeah, I went to school with a kid who's entire legal name was G...and this was way before the other OG was a recognized title :)
Eric Lynch
1-Aug-18 18:42pm
View
Sorry Markus, I had a bit of good natured fun :) The "turn it on/off, unplug it/plug it in, and hit it with a hammer" answers are a bit of a meme.
It's a bit like that old "Doctor, doctor, it hurts when I do this" joke, where the punch line is "then don't do that".
I really wasn't clear on your question. Could you please add some more detail? To obtain effective help, you need to describe what your program does, how you are trying to start it, and what error text (or other symptom) occurs when it does not start.
You need to understand that what is obvious to you as you sit in front of your screen is entirely unavailable to the rest of us. We can't see your screen, or step through a debugger, or do any of the many other things we can do to debug our own code.
Eric Lynch
1-Aug-18 18:36pm
View
Construction involves both hammers and sledgehammers, perhaps a good alternative career? :)
Eric Lynch
1-Aug-18 18:32pm
View
You're very welcome. I have done as you suggested and added a solution. I will shamelessly accept any credit you deem appropriate :)
I highly recommend taking a bit of extra time to explore the difference between value and reference types in the provided link. This is a fairly common problem encountered by people as they become more familiar with C#. Its likely to cause you problems, in other situations, until you become comfortable with it.
Eric Lynch
1-Aug-18 17:08pm
View
Re:Should I try turning it off and on again?
Yes. Also hit it with a hammer :)
Eric Lynch
1-Aug-18 13:28pm
View
Be careful though, any technique will be culture-dependent. Also, even in cultures that have a clear first, middle, last, you need to consider the odd ball cases. People with no middle name and people with multiple middle names. Also, there are the occasional truly exceptional single-name cases (e.g. Cher).
Eric Lynch
1-Aug-18 13:15pm
View
Read the comment a bit more carefully. This has the exact same problem. When you pass "num" to "Attack", you pass a COPY of the value. This is how value types (e.g. int) work. Then you increment the "targetlife" (which is a copy NOT the original). After this, you return. Since "targetlife" passes out of scope, when you return, it ceases to exist.
I recommended some possible solutions in the earlier comment. You may also want to re-think your object model a bit. There is not enough code for me to be certain, but my intuition tells me the model could be improved to make this less difficult.
For example, if Sprite has both life and damage, you could do the following:
public void Attack(Sprite target)
{
target.life -= damage;
}
gigel.Attack(tree);
To better understand the difference between value types (int, struct, etc.) and reference types (class), you may want to read here:
http://www.albahari.com/valuevsreftypes.aspx
Eric Lynch
1-Aug-18 0:18am
View
Having some trouble following your question. My guess is that you are asking why tree.life, which is passed as a parameter, is not updated when you call Attack.
If this is the case, it is because the data type int is a value type. This means that when you pass it as a parameter, you pass a copy of the value (unless you specify the ref or out keyword). When you decrement targetlife, you are decrementing a copy. Since you do nothing with that copy, its value is discarded after it passes out of scope.
Assuming "life" is a property of tree, this poses further difficulties. You cannot simply pass properties by reference (with a ref/out keyword).
So, you have a few possible options. Expose a "Damage" property from the Sprite, and then: tree.life -= gigel.Damage.
Or, change the signature of the Attack method: public int Attack(targetlife) { return targetlife - damage; } and then: tree.life = gigel.Attack(tree.life).
Eric Lynch
30-Jul-18 13:11pm
View
OriginalGriff, as usual, provides sage advice here. I'd add one item, in case you need to generate an identity. In addition to GUIDs, MySQL also supports AUTO_INCREMENT columns, see: https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html
Eric Lynch
30-Jul-18 6:53am
View
Building on this, to make it a bit shorter, I'd also invert the conditional and use an in-line variable (C# 7 or better)…
if (!int.TryParse(msg[1], out int deposited))
throw exception to indicate invalid input;
stats[user].Cash -= deposited;
stats[user].Bank += deposited;
Eric Lynch
27-Jul-18 11:16am
View
Or, make the class IComparable<T>, and call list.Sort() without a parameter, for example:
public class KitModel : IComparable<KitModel>
{
public string KitName { get; set; }
public string KitCode { get; set; }
public decimal KitValue { get; set; }
public string KitCodePrefix { get; set; }
public int KitIndex { get; set; }
public int CompareTo(KitModel other)
{
if (other == null)
return 1;
int comparison = KitCodePrefix.CompareTo(other.KitCodePrefix);
return comparison != 0 ? comparison : KitIndex.CompareTo(other.KitIndex);
}
}
Eric Lynch
26-Jul-18 16:15pm
View
You'd need to clarify your rules for ordering better. As far as a string compare is concerned, CAN10 comes before CAN8 ("1" comes before "8").
Eric Lynch
26-Jul-18 16:10pm
View
In that case, I'd populate a System.Data.DataTable and call the System.Data.SqlClient.SqlBulkCopy.WriteToServer passing that as a parameter. I'd offer more help, but you still haven't shared data type for the grid. Telling me its a web app narrows it (somewhat), but don't have any more time to guess.
Here's an example of how to create and use a DataTable…
https://msdn.microsoft.com/en-us/library/ex21zs8x(v=vs.110).aspx
Eric Lynch
26-Jul-18 8:04am
View
Storing a username/password in clear text is very insecure. You should consider using Integrated Security, which Oracle supports. With Integrated Security connection strings, clients are authenticated via Windows login credentials, so no username/password is required in the connection string.
Failing this, you should at least encrypt the information in the configuration file. Though, this is less secure and less easy to maintain.
See: https://docs.oracle.com/cd/B28359_01/win.111/b32010/external.htm#g1028005
Eric Lynch
25-Jul-18 22:56pm
View
Its more important that I understand the data type used to populate your grid view than it is to know the actual data. Generally, it is uncommon for a grid view to be populated directly, instead it is normally bound to a data source (DataTable, List<t>, etc.). For example, if its bound to a DataTable, this data type can be passed directly (as a parameter) to the WriteToServer method. If it's bound to a List<t>, its comparatively easy to use a LINQ Select/ToArray to create an array of DataRow, which can also be passed directly (as a parameter) to the WriteServer method. If it is neither of these cases, then I would need to understand EXACTLY how you populate the grid view to suggest a best course of action. I would also need the fully qualified name of the data type for the grid view (e.g. System.Windows.Forms.DataGridView) so that we don't waste time. Within the .NET framework, there are a few different ways to represent a grid.
Eric Lynch
25-Jul-18 22:41pm
View
Deleted
Its more important that I understand the data type used to populate your grid view than it is to know the actual data. Generally, it is uncommon for a grid view to be populated directly, instead it is normally bound to a data source (DataTable, List<t>, etc.). For example, if its bound to a DataTable, this data type can be passed directly (as a parameter) to the WriteToServer method. If it's bound to a List<t>, its comparatively easy to use a LINQ Select/ToArray to create an array of DataRow, which can also be passed directly (as a parameter) to the WriteServer method. If it is neither of these cases, then I would need to understand EXACTLY how you populate the grid view to suggest a best course of action. I would also need the fully qualified name of the data type for the grid view (e.g. System.Windows.Forms.DataGridView) so that we don't waste time. Within the .NET framework, there are a few different ways to represent a grid.
Eric Lynch
21-Jul-18 3:38am
View
Too much code to weed through...step through the debugger...find the line where the exception is thrown and excerpt it. Also, if you can, include the stack trace (exception.ToString()) for the exception. Sometimes there are inner exceptions which provide additional detail.
Eric Lynch
20-Jul-18 20:25pm
View
That's funny...the old "missing digit" excuse. That at least puts it in prspective..oops missed an "e"...seriously, thank you for brightening my day!
Eric Lynch
19-Jul-18 20:28pm
View
One thing, I suggest using Directory.EnumerateFiles. With Directory.GetFiles, you can't start doing anything until the information for ALL files has been loaded. With Directory.EnumerateFiles, you can process the file information as its discovered. The signatures are nearly identical, but it can make a big performance difference for directories with large numbers of files. Of course, this assumes that the caller doesn't do something dumb like tack a ToArray/ToList onto the IEnumerable :)
Eric Lynch
19-Jul-18 12:12pm
View
One other thing you may want to consider, a node can have IsVisible = true and still not be visible, because it is scrolled out of range. Regrettably, NextVisibleNode does not consider scrolling. I updated the solution to include methods that consider scrolling, in case this is part of your requirements.
Eric Lynch
19-Jul-18 10:17am
View
No problem. You may want to read through the answer. If you're looking for the first truly visible node (IsVisible=true and not scrolled out of view), then the TreeView.TopNode is the best way to go. Otherwise, don't bother with recursion, just examine the top level nodes, one is guaranteed to be the first visible node, if any nodes in the tree are visible. That's a simple bit of LINQ, presented at the end of my solution. Also, regarding the vote, I think you may be able to edit your choice...I forget. No problem either way.
Eric Lynch
19-Jul-18 9:25am
View
Yep, I understand its stuck now. However, I was hoping maybe somebody wrote documentation before they released it. In which case, they could have fixed it before release. I know, I know...novel concept actually writing documentation for a product BEFORE release...also, never going to happen :)
Eric Lynch
19-Jul-18 8:58am
View
Wow, someone actually documented that without taking the time to say, "hey, let's change that to an exception that describes what went wrong"...sad :)
Eric Lynch
18-Jul-18 16:07pm
View
what step are you doing when "it" says it and what is "it"?
Eric Lynch
18-Jul-18 14:58pm
View
You may want to look at the SqlParameterCollection.AddRange(SqlParameter[]) method, described here: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection
Eric Lynch
18-Jul-18 14:21pm
View
Deleted
The question was how to save an image, which has a pre-requisite that you have acquired the image you want to save. This would generally imply that you have declared a C# variable with the data type "Image" and loaded the data into that variable.
If not, you'll need to update your post to include at least one additional question: How do I load/read an image? When you update the post, you'll need to provide additional information about the source of that image: disk file, download from web, or upload from user to web. If its web-based, you'll need to provide additional information as well for anyone to be able to answer the question.
Eric Lynch
17-Jul-18 17:26pm
View
Also, the suggested code wouldn't even compile in C#. I'm guessing you meant var a = "hihihihihi"? or string a = "hihihihihi"? Also, I'm guessing you meant Console.WriteLine not System.WriteLine?
Assuming the guesses are correct, there are two problems. First, you are using Console.WriteLine improperly.
The overload that takes a string argument and a variable number of additional arguments is for formatting strings. In this case, the first argument provides the format and the remaining arguments provide the parameters to be used with that format.
For example, Console.WriteLine("Number={0}", 123) would write out the text "Number=123" followed by a new line character (WriteLine adds a new line onto whatever it writes out).
The second problem (noted by kmn1235) is that you seem to expect the WriteLine method to (somehow) magically separate your string. It will not do this.
For comparison, the following code would provide the output you hope for:
Console.WriteLine("hi");
Console.WriteLine("hi");
Console.WriteLine("hi");
Console.WriteLine("hi");
Console.WriteLine("hi");
Although, I would probably put that in a loop as follows:
for(int index = 0; index < 5; index++)
Console.WriteLine("hi");
Eric Lynch
17-Jul-18 16:56pm
View
The way your code is structured it is a bit more complex. I missed that you were placing the file name in three different text boxes. I see you added a clarification. Your code is not the cleanest I've seen, but I'll try to guess at your intent. Shortly, I'll do so in an update to the solution...editing in comments is limited.
Eric Lynch
17-Jul-18 12:19pm
View
You're very welcome. I also suggest checking out Richard Deeming's comment to your question. Otherwise, your application is potentially a very easy target for hackers.
Eric Lynch
15-Jul-18 21:16pm
View
As always, there are many ways to get the same solution. If you're limiting yourself to common C# data types, you may want to look at the System.TypeCode enumeration. This might be better for representing the possible types.
One way of accomplishing this task, might be to create a List<Dictionary<TypeCode, int>>, where each item in the list represents a column of data. Each entry in the dictionary then keeps track of the number of times the corresponding data type (TypeCode) occurs.
Sampling basically requires you to add or increment the corresponding dictionary item. When done sampling, you can simply iterate though the dictionary, for each column, and choose the one with the highest count.
Though, you should consider what to do in the case of a tie. For example, in most cases, text for TypeCode.Int32 (int) is also valid for TypeCode.Decimal (decimal).
Again, just one possibility. There are many other approaches that would also work.
Eric Lynch
2-Jul-18 9:27am
View
I agree with all of your points with regard to learning programming. I started programming professionally a bit over 35 years ago. I grew up on Knuth and FORTRAN and BASIC. I've lost count of how many programming languages I've learned and discarded over the decades.
That said, the question was specifically on the syntax of C#. While it won't help you program any better, being familiar with advances in the underlying framework and syntax can make a good programmer more productive. On the flip side, it tends to make poor programmers even more cryptic :)
Eric Lynch
30-Jun-18 21:40pm
View
You may want to check out the link I provided in the third solution. While I agree the C# language added its most useful features by VS 2008, there were some very useful additional features (mostly syntactic sugar) added over the past 10 years.
Eric Lynch
29-Jun-18 9:00am
View
You're really not providing enough information to help effectively. That said, I do notice one discrepancy within your question. In some places, you mention "imglogo" and in the error we see "ImgLogo". C# is a case-sensitive language, so these two are NOT the same thing. Are you maybe mixing up the case someplace in your code?
Eric Lynch
29-Jun-18 8:04am
View
You are not providing enough information for anyone to answer your question. Let's take a look at some of the problems with your question:
"i have below xml in the ip address"
Is this the entire XML document? If yes, the XML is not valid. If no, how are we supposed to guess at the rest of it?
"i am access the ip in postman <colleges>"
If you're trying to access the XML element <colleges>, this is not included in the sample data you provide. No one can tell you how to access an element that they cannot see.
"i have to read below, i am not sure how to get data"
If you're question is how to read a random XML document (that we cannot see), then
Maciej Los provided a solution. If you're question is more specific, then please be more specific.
From a response to the solution...
"thank you @Maciej, but i have already tried this"
That's great news. What went wrong? Did you get an error? If so, what error?
Without knowing the error, the contents of the string "sret", the complete contents of the XML document, the actual source code you tried, or having ANY other detail, it is not possible to guess the cause...possible causes are almost limitless.
In my opinion, the most likely possibilities are: 1) you copied the code incorrectly, 2) the XML document is not valid, or 3) a different character encoding (other than UTF-8) was used.
If you still want help, try providing people more information so that they can actually help you.
Eric Lynch
23-Jun-18 14:50pm
View
For an event driven application, it sounds a bit backwards for a custom class to manipulate a control (unless perhaps the custom class is derived from a control). As many respondents have suggested, I think perhaps its less a misunderstanding of the few details in the question, than a general lack of detail in the question itself.
Eric Lynch
22-Jun-18 9:29am
View
No magic involved. When you are designing your form, simply subscribe to one of the events exposed by the controls. With WinForm designer, this generally involves double-clicking the control...at which point, a stub method is added to your form to handle that event. For example, Button has a click event. Then, within that handler method, put whatever logic you want to call methods in your custom classes.
That said, like the other respondents, I'm somewhat amazed that you haven't already done this in 7 years as a C# developer. Almost all UIs are event driven...the exact interface and designer change between approaches, but conceptually its all about the same.
Eric Lynch
21-Jun-18 17:07pm
View
Don't know if this would work for you...for similar requirements, in the past, I've initially written to a temporary directory or file name. Then, I've renamed/moved the file only AFTER its complete. That way the process that reads the file only ever sees completed files.
Eric Lynch
21-Jun-18 16:50pm
View
Doesn't necessarily require a Marshal. The following is a little bit slow, but works.
int x = 0;
int y = 0;
var bitmap = Image.FromFile(@"pic.jpg") as Bitmap;
Color color = bitmap.GetPixel(x, y);
byte red = color.R;
byte green = color.G;
byte blue = color.B;
A bit faster (which does require a Marshal) is described here:
https://stackoverflow.com/questions/7373703/c-sharp-getting-the-pixel-data-efficiently-from-system-drawing-bitmap
WPF also has some equivalents to System.Drawing that may be better.
Eric Lynch
21-Jun-18 11:06am
View
As a suggestion, are you open to a different approach? It is possible to let .NET do a lot of the heavy lifting for you, decoding the file format, and still have access to RGB values for the pixels that make up the image. Or, are you set on reading the image byte-by-byte from the file?
Eric Lynch
21-Jun-18 9:39am
View
In the case of ".jpg" files: https://en.wikipedia.org/wiki/JPEG
Eric Lynch
21-Jun-18 6:11am
View
Not clear what you are trying to do here. Your code is doing to you have asked it to. Which of the following are you trying to do?
Are you trying to add a new "product" element to "Brand"? -OR-
Are you trying to add new "ip"/"op" attributes to a specific "product" element within "Brand"? If so, which one? Currently, you are adding to the first one. -OR-
Are you trying to add additional values to the existing "ip"/"op" attributes (e.g. before: ip=1,2,3 / after: ip=1,2,3,4,5,6)?
The easiest way to ask is probably to show a small before XML document and after XML document for what you want to do.
Eric Lynch
20-Jun-18 6:34am
View
Sorry Jochen, we posted about the same thing at the same time. Combining our code, we would have a perfect solution. My code initially under-sizes the builder (should be same.Length * 7) and yours will have an extra space at the end of the text :) Though, yours is simpler to understand.
Eric Lynch
20-Jun-18 6:28am
View
Is this what you are looking for?
string same = "Shahbaz";
var builder = new StringBuilder(same.Length * 5);
foreach (char chr in same)
{
if (builder.Length > 0)
builder.Append(' ');
builder.AppendFormat("U+{0:X4}", (ushort)chr);
}
string text = builder.ToString();
Console.WriteLine(text);
To be clear, the following text will be displayed to the console:
U+0053 U+0068 U+0061 U+0068 U+0062 U+0061 U+007A
Eric Lynch
20-Jun-18 6:21am
View
Using your example, the following code would NEVER display the word "No". Things really are always in UTF-16 in C# strings.
ushort[] codepoints = new ushort[] { 0x53, 0x68, 0x61, 0x68, 0x62, 0x61, 0x7A };
string utf16 = "\u0053\u0068\u0061\u0068\u0062\u0061\u007A";
string same = "Shahbaz";
Console.WriteLine(utf16 == same ? "Yes" : "No");
for (int index = 0; index < utf16.Length; index++)
if (utf16[index] != same[index] || utf16[index] != codepoints[index])
Console.WriteLine("No");
So, again, if you have a string, you by definition have something in UTF-16.
With regard to the database, nvarchar stores a Unicode representation in whatever encoding it chooses, you don't get to pick. In the case of SQL Server, this is also UTF-16. See the following, if you are unsure:
https://docs.microsoft.com/en-us/sql/relational-databases/collations/collation-and-unicode-support?view=sql-server-2017
Now, with regard to converting from a C# string (always UTF-16) to a native database encoding (up to the database product), this is handled (automatically) by software that is not under your control. Usually, with C#, some technology sits on top of the provider, and calls it on your behalf. This might be ADO.NET, LINQ to SQL, Entity Framework, or Entity Framework Core.
Hopefully, this helps you understand why your question as stated is not meaningful. I understand this can be confusing, but both Jochen and myself are providing you with accurate information. In this case, there is simply no work for you to do...so we can't provide you with code to do it :)
Eric Lynch
19-Jun-18 19:07pm
View
Serialization with something like JSON.NET can also allow you to omit null/default values. So, if you use nullables or have a good default value you can use for absent items, you can greatly reduce the size of the serialized data during transport. This might allow you to use a single class.
Eric Lynch
19-Jun-18 18:15pm
View
If you're wondering why you have received so little response, its because you haven't even provided any detail for people who want to help. There is so little detail that people don't even know what questions to ask to get the missing detail.
The terms "grid" and "webpage" are ridiculously generic. There are hugely different approaches to presentation. Most modern web applications fetch data via a RESTful service and deal with the presentation work (creating the HTML for the grid) on the client-side. Older web applications (and some modern ones) create the HTML on the server-side. Any clue about the basic architecture of your application might help people to ask intelligent questions.
With either architecture, there is ultimately some data source for the grid. This could come in the form of a DataTable class or a collection of strongly-typed objects. Any clue about the data source, and more importantly the nature of the data, might help people to ask intelligent questions.
Assuming we knew anything about the application or the data, the next question would be exactly what you are trying to do. It seems, if I read correctly, you want to generate a database schema, create a database table from this schema, and populate it with the data from your application.
If correct, this is a very unusual requirement. We'd need to understand more about why? For example, are users able to add and remove columns from your grid? Are they able to change column names? Are they able to change the data types for those columns? If the answer to all of these questions is "no", then there is no need to dynamically generate anything. There are much better approaches that people might suggest.
If you are truly giving the user the ability to directly influence the creation of database tables, via your webpage, then this is a design that carries a fair amount of risk, both to application stability and potentially security as well.
If this is correct, I would recommend against this approach. There are almost always better approaches, if the requirements are truly understood.
Assuming all of this is true, and you're willing to assume the risk, we'd have to better clarify "store exactly". There are data types in C# that simply don't exist in some databases. Which, I guess brings up yet another question, what database are you using (SQL Server, MySQL, Oracle, etc.)? There are differences in syntax and data types between databases.
The final question is what you plan to do with the data once you store it? Will the webpage try to query it later? If the user can change the schema, via the webpage, and you query the table later, how do you plan become aware of a change in the schema? Do you need to also know how to query table metadata from a database?
In short, I think you need to more carefully consider your requirements and articulate them, before anyone even knows what questions to ask you, so that they can help.
Eric Lynch
19-Jun-18 13:11pm
View
To (hopefully) add a bit to Jochen's response, a C# string is always stored as UTF-16 within memory. There two common cases where you need to worry about the encoding: 1) you are reading or writing a file or 2) you are dealing with some non-.NET entity (via interop). For those cases, check out the suggested links.
Another concern can be with a user interface. There, you need to make certain you select a font that contains glyphs for the characters you expect to display. Though, this is a presentation issue, not an encoding issue. Usually, the default MS fonts are fairly decent for letters in most languages...less so for symbols.
Eric Lynch
19-Jun-18 12:57pm
View
Deleted
I'm certain I replied to the correct portion of the thread this time but CP seems not to agree. Anyhow, too lazy to copy it down this time, please check earlier in the thread for my reply to this post :)
Eric Lynch
19-Jun-18 12:52pm
View
First, I really think specifying the type in your query is the best option. That said, assuming a grid view item was selected, I would expect the other suggestion to work.
When you say "it's returned a null", what is "it"?
Is "MyDevicesDataGrid.SelectedItem" null? If so, that means the user hasn't selected a data grid row in the UI?
Is "(MyDevicesDataGrid.SelectItem as dynamic)" null? If so, I'd use the debugger to examine "MyDevicesDataGrid.SelectedItem" to determine its underlying type.
Is "(MyDevicesDataGrid.SelectedItem as dynamic).SN" null? If this is the case, either the database column may be null or the compiler may be having some trouble resolving the dynamic property.
Both specificity, and the debugger, help when trying to diagnose these issues. That said, where possible, I prefer to simply work with a specific type for the end result of a LINQ query, to avoid all of the above complexities. I often use dynamic types, for inner portions of a LINQ query, but almost always select to a specific type for the outermost result.
Eric Lynch
19-Jun-18 11:03am
View
Sorry, accidentally replied to your question instead of your comment...
I'd recommend changing your LINQ query to yield a specific type as suggested in the original response.
While I would not recommend it, I think the following should also work, if you insist on doing it later.
string id = (MyDevicesDataGrid.SelectedItem as dynamic).SN;
Eric Lynch
19-Jun-18 11:01am
View
Deleted
I'd recommend changing your LINQ query to yield a specific type as suggested in the original response.
While I would not recommend it, I think the following should also work, if you insist on doing it later.
string id = (MyDevicesDataGrid.SelectedItem as dynamic).SN;
Eric Lynch
19-Jun-18 10:44am
View
Your LINQ query appears to return a dynamic type; whereas, your assignment appears to expect a specific type (DevicesDetail). When you use the "as" clause, it will cast to the specified type (if the object is of that type); otherwise, it will yield null. You can't simply cast from a dynamic type to a specific type. Its not valid. You'll need to either alter your LINQ query to select your desired type or write a method to do the conversion yourself later.
ADDENDUM: To be a bit clearer, you can change "select new { … }" to "select new DevicesDetail { … }" and then change to assignments like "SN = DT.SN" within the brackets (where the "..." bits are).
Eric Lynch
17-Jun-18 14:32pm
View
Nice, I like the analogy. Though, for static classes, what about those funky three wheeled cars :)
Eric Lynch
15-Jun-18 23:07pm
View
In fairness, I tried to find a nice article on ADO to recommend. Most had some problems. That said, I think you need to work at the basics (walk before you run) a little bit more.
I really want to keep helping, but I think I may be doing more harm than good.
Knowing that "Postalcode" is a datatype of float, you would need to adjust the following line...
command.Parameters.AddWithValue("postalcode", 1010F);
To be clear, it is important that your understand that the first parameter is the name of a SQL parameter (which must match the SQL query). It is also important that you understand that the value is a floating point value (by data type) that matches what the user entered for the postal code.
I still think you need to learn more (SQL, ADO, C#, et al) before you continue. This is the best (ill-advised) that I can continue to help you. After this, I'm done. Programming is difficult when you first start. You truly won't learn anything (or achieve your goal) unless you work through some of the basics yourself.
Apologies if I was at all condescending. Your guesses indicate you may have a talent for this. But, you won't learn unless you try to work some of this out for yourself.
Eric Lynch
15-Jun-18 10:30am
View
I suggest stepping through it in the debugger, "nothing" is a bit too broad of a category to help with. You'd need to isolate which line failed to give you the expected result. At a minimum, your SQL query (which includes "* City") does not appear to be valid. The "*" is generally used to select all columns. In which case, the first column (reader[0]) may not be the city column. The original query I suggested, only includes the city column.
Additionally, the first parameter of AddWithValue omits the parameter name, so that won't work correctly.
Finally, I don't see where in your code you assign a value to the text box. You only assign it to the local variable txt_st_city, which is then discarded (when it passes out of scope).
I'd suggest maybe finding a brief tutorial out there that covers the basics and working your way through that first. Sorry, but Q&A really isn't a place to cover the basics. Its more to answer specific questions.
Eric Lynch
15-Jun-18 9:53am
View
This question needs more information, starting with: database table name, column name, column type (is it nullable?), database technology (ADO.NET, LINQ to SQL, LINQ to Entities), etc. Depending on the approach you choose, you should at least try first. Then, you can ask a more specific question. There is simply not enough information in your question for anyone to provide you with meaningful assistance.
Eric Lynch
15-Jun-18 7:08am
View
Previous response (with possibly corrected table / column names) should do what you want. Instead of assigning to city string, assign to text box.
Eric Lynch
15-Jun-18 6:27am
View
You're reply is a bit terse (and unclear)...not exactly a schema. So, I'm forced to make some assumptions. I'll assume the following: you know your connection string, your table name is "Postalcode", your column names are "postalcode" and "city", both columns are compatible with string (e.g. varchar, nvarchar, etc.), the table is (minimally) indexed by postal code (for performance), you want to use ADO.NET (instead of LINQ to SQL or LINQ to Entities), and your question is how to get the name of a city given a postal code.
If this is all true (a huge IF), the first thing you should know is that most SQL classes in C# are IDisposable, so you should make use of the "using" statement.
Your solution should be approximately as follows. Note, I'm typing it by hand here, so there may be some slight syntax errors.
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand("SELECT city FROM Postalcodes WHERE postalcode=@PostalCode", connection))
{
command.Parameters.AddWithValue("postalcode", "01010");
using (var reader = command.ExecuteReader())
{
string city = reader.Read() ?
reader[0] as string : "Unknown";
if (reader.Read())
city = "Ambiguous";
}
}
}
Eric Lynch
14-Jun-18 17:47pm
View
Postal codes are a tricky country-by-country thing. You have three issues to solve: 1) finding the postal code in a free-form address (hopefully you have a fixed field address) 2) a good source of postal code information and 3) a very easy lookup. For the second, check out GeoNames.org. For the third, its really easy to code. Once you know the postal code and have a source of information, simply describe the schema (format of the database) and anyone here can provide a simple solution.
Eric Lynch
12-Jun-18 20:49pm
View
My recommendation, separate the concerns. Move the common logic into a separate class that either form can call.
Eric Lynch
12-Jun-18 6:06am
View
I was just going to suggest Thaddeus Jones' improvement. Additionally, if you want ignore diacritics (as well as case), you may want to check out the following:
https://stackoverflow.com/questions/249087/how-do-i-remove-diacritics-accents-from-a-string-in-net
It's not perfect, but should cover most cases for the Portuguese language.
Surprised you don't have the "Would you like to play a game?" meme from War Games included in your choices :) Good luck.
Eric Lynch
9-Jun-18 21:43pm
View
I'm with OriginalGriff here, the explanation is not helpful. Perhaps, its a language issue? I'll take a couple of guesses, to try and help, but you need to add some detail as well.
In your textbox, it seems (maybe) you are expecting text comprised of a concatenation of the following: 1) a three character currency (e.g. USD), 2) a four character decimal value (e.g. 0005), and 3) a 1-n character decimal value (e.g. 000015). In your data grid, it appears (maybe following a button click), that you hope for the columns: Currency (1), Denomination (2), Count (3), and Total (the sum of the two decimal values 2 and 3).
Is this an accurate guess? If so, please describe your results and how they differ from your expectations. Simply show the following: expected input (to the text box), expected output (to the four columns of the data grid), and actual output (to the four columns of the data grid).
With the difference between expected and actual outputs someone may be able to help you.
Eric Lynch
5-Jun-18 8:40am
View
Looking at your attempted implementation, you are missing a few elements. With a circular buffer, one would expect your pointer rxOffset to proceed towards the end of the buffer (at buffer size) wrapping (or resetting) to the start. You seem to be missing logic to consider this case. Typically, a circular buffer would also have two pointers, which "chase" each other. One indicates where you next add data to the buffer and the other indicates where you next remove data from the buffer (aka read/write). You would also need to add logic to handle buffer overflow, mb making sure the write pointer doesn't overtake the read pointer. Finally, you probably need to handle a partial read at the buffer boundary (when a wrap occurs)...dividing your read into two parts. I have bad connectivity right now, or I'd include some sample code. I'd just Google it. It's a well-established, fairly simple pattern. There should be truckloads of samples / explanations available.
See: https://en.m.wikipedia.org/wiki/Circular_buffer
See also: http://geekswithblogs.net/blackrob/archive/2014/09/01/circular-buffer-in-c.aspx
Eric Lynch
4-Jun-18 22:04pm
View
Difficult to say, from this snippet. Speaking generally, I would check the data that is altered and add an assertion for the accuracy of that alteration. For example, if you expected a data cell to be changed from 1 to 2, assert that the data cell is equal to 2, after the method is called.
Eric Lynch
2-Jun-18 21:29pm
View
A more efficient means of achieving this same goal might be to use a JOIN and GROUP BY on the column(s) that are common between the two tables. Since you don't include many column names in your query, its difficult to provide a good example, but something like the following:
SELECT Categories.CategoryID, COUNT(Categories.CategoryID) AS RowCount FROM Products
LEFT OUTER JOIN Categories ON Categories.CategoryID=Products.CategoryID
GROUP BY Categories.CategoryID
If you don't want zero counts, you can use LEFT INNER JOIN instead.
Eric Lynch
2-Jun-18 9:05am
View
As mentioned, there are almost certainly better approaches. However, without a better understanding of your goal, its difficult to provide the best advice. At a minimum, I'd need to see how you are populating the DataGridView, the data types of the columns, the names of the columns included in the total, and the name of the column to receive the total. Again, assuming you are populating the grid via DataSource, you are probably calculating the sums at the source instead of on the grid itself.
The example I provided simply totals all columns (except the first), it assumes all columns have a value that can be converted to an integer, and it deposits the total in the first column.
Complete source for the test harness I threw together (very quickly) is...
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<myobject> values = new List<myobject>
{
new MyObject { Col2 = 1, Col3 = 2, Col4 = 3},
new MyObject { Col2 = 4, Col3 = 5, Col4 = 6},
new MyObject { Col2 = 7, Col3 = 8, Col4 = 9},
new MyObject { Col2 = 10, Col3 = 11, Col4 = 12}
};
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = values;
}
private class MyObject
{
public int Col1 { get; set; }
public int Col2 { get; set; }
public int Col3 { get; set; }
public int Col4 { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int total = 0;
for (int index = 1; index < row.Cells.Count; index++)
total += Convert.ToInt32(row.Cells[index].Value);
row.Cells[0].Value = total;
}
}
}
}
Assuming you want to total all columns except the one named "Col1" and deposit the result there, the button-click code would change as follows:
int totalIndex = 0;
for (int index = 0; index < dataGridView1.Columns.Count; index++)
if (dataGridView1.Columns[index].Name == "Col1")
{
totalIndex = index;
break;
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int total = 0;
for (int index = 0; index < row.Cells.Count; index++)
if (index != totalIndex)
total += Convert.ToInt32(row.Cells[index].Value);
row.Cells[totalIndex].Value = total;
}
However, I'll stress again that more information is needed for me (or anyone) to provide a good response. If this doesn't help you, you'll need to either mark the problem as not solved (if this allows it) or re-post. I may be unavailable for a while, so someone else may need to pick up where I left off.
Eric Lynch
1-Jun-18 14:54pm
View
The images in the referenced Wikipedia article are deceptive. There, they encrypted only the image data.
Almost all image file formats, including JPEG files, consist of a mix of data: image data, structural data, and meta data (e.g. the model of camera). The structural data identifies the file format and differentiates its parts.
To be able to open a file, following encryption, you would need to selectively avoid encrypting any structural data.
There is no built-in mechanism (of which I am aware) for avoiding structural data during encryption. This would be a fairly complicated program to write and would be dependent on the exact image file format.
Eric Lynch
1-Jun-18 10:42am
View
Ummm...in fairness, if you re-read my post I never actually did say his code was open to SQL injection. I did say that forgetting about it is a theme in the posts. Based solely on the OPs posting history, I stick by that assertion.
Regarding your other point, I am similarly annoyed by respondents who sermonize without answering the question. I've been a recipient of a few of these replies.
However, this was certainly not the case here, in Richard's solution. He answered the question AND offered great advice. So, I stick by the support I offered there as well.
Its never fun offering advice (or apparently support :)). Richard did so, in my opinion, in exactly the correct fashion (answer first and then advise).
I'd also point out that the OP was free to respond. Although, he has ZERO obligation to do so.
If it were me, after having a number of my questions answered and seeing similar concerns raised from well-intentioned folk, I might say something like: "Hey, thanks for answering the question. I hear you about SQL injection, but don't worry it in this instance, because...<insert reason here>".
The absence of a such a response worries me a little bit. Again, he has ZERO obligation to respond.
But, I still get to worry. What can I say? I'm a worrier :)
Personally, I hope Richard continues to fight the good fight (so long as he continues to answer first :)). Too many companies end up the target of this so-easy-to-prevent attack.
Anyhow, that's about as good a job as I can do clarifying my original response, so I'll probably not be responding further. Nobody ever accused me of having great communication skills :)
Eric Lynch
1-Jun-18 9:54am
View
The world's an uncertain place. That said, developing a habit of not using parameters offers no real benefit and a pretty huge downside.
Based on the OPs posts, I'd be willing to wager that this downside bites him eventually. Normally, since he's been advised, this would be fine with me.
However, in this case, other folks (his users) potentially also suffer consequences. Because of this, I strongly support Richard's attempt to avert that outcome. He first answered the question and only afterwards added a caution.
Likewise, I can't prove that driving a car blindfolded will cause a crash, but I would certainly advise against it :)
Eric Lynch
31-May-18 16:10pm
View
Sigh...forgetting SQL injection does seem to be a theme in these posts. After answering a previous post, I seconded your concerns...sad to see its ongoing :(
Eric Lynch
30-Apr-18 17:17pm
View
If you're getting an exception, then (by definition) something is going wrong. There are really only two things I can think of that might go wrong. The first is some sort of systemic failure: dropped connection, timeout, resource limit, etc. The second is a problem with the data.
The approach to handling each is different. If its a data problem, Gerry is correct, you should validate the data before the bulk insertion to prevent the problem in the first place. This remains my guess.
Systemic problems fall into two categories: transient and persistent. For transient problems (e.g. a network outage), retrying is really your only option. However, if your problem is systemic, it sounds persistent. So, to fix it you would need to understand what has gone wrong. For example, if its a timeout issue, you can increase the timeout.
Regardless of your problem, the first step to solving it is to understand it. I'm happy to try to help...as are a lot of other folks on this site.
If you update your original question to include more information about the exception, folks here will be able to better assist you. I suggest writing out e.ToString(), where "e" is the exception and then cut/pasting this into your question.
Without this information, we're both just guessing about the correct course of action to fix the problem :)
Eric Lynch
30-Apr-18 14:20pm
View
I was just about to go off and check whether the SQL bulk API let's you determine which rows failed...classic case of over-engineering.
Gerry's approach is much better...in this case (as usual) simpler is better. You are much better off validating the data before submitting it.
Eric Lynch
30-Apr-18 14:01pm
View
Since you accepted this answer, I wanted to take a moment to re-iterate a point made by a couple of other respondents.
You really should make it a habit to use SQL parameters. Eventually, you'll write a web application. If you don't make it a habit, even in your "play" code, you'll eventually make a mistake, and let it slip into your "real" code.
This makes it very, very easy (way too easy) for even an unskilled hacker to make unpleasant things happen. Its one of the top few techniques hackers exploit.
I know this may seem like something not to worry about in your "play" code. However, its really quite dangerous.
This is why the other respondents seem so concerned. They're honestly trying to do you a big favor, by helping you avoid an unpleasant outcome.
Anyhow, end of lecture...I hope you're able to resolve any remaining problems and get your application working the way you want. Good luck and happy coding :)
Eric Lynch
30-Apr-18 13:38pm
View
I am happy I could help. The IEnumerable<t> interface only provides two methods, different versions of GetEnumerator. These obviously cannot be used to add an item to a collection. Both ICollection<t> and IList<t> include an Add method. This method allows the de-serializer to add an item.
Perhaps you expected the de-desializer to be "smart" enough to call the Add method on the property (e.g. AppointReasonLi)? If the de-serializer did this, it would actually be a bit dumb.
Basically, you have a mismatch between your JSON document and the data model in your source code. Two solutions are possible: 1) fix the JSON document or 2) fix the source code.
I suggested fixing the source code, because that is what I am guessing you wanted.
The alternative would be to add an intervening JSON object. For example (not tested), I think it would end up being something like AppartmentReasonList { AppartmentReasonLi [ { ClassCode : "blah", ... }, ... ] }.
For what its worth, I struggled a little as well, way back when I first starting playing with the more complex de-serializers. In my case, it was the XML de-serializer first.
In my case, it helped to really think about how the de-serializer was implemented. I even played a little with reflection, implementing my own dumb version, to better understand it.
I hope this helps. Good luck.
Eric Lynch
30-Apr-18 7:30am
View
You're welcome. Simply test if reader4["data"] == DBNull.Value. If so, set pictureBox.Image to a different value. I recommend adding an image to the resource file and using it.
Show More