|
hi,
tks for the reply but i noe how to read with your code given.
what i'm looking for is how do you proceed after that? with my given xml, how do i get the value of the key and its value.
for example:
<add key="Setting1" value="Very" />
how do you get the value of Setting1;
and how do you update this value.
similarly how do you create new element and value with dataset.
i tried using the dataset table but im pretty much lost as it provide null value.
|
|
|
|
|
|
Language: C# 2.0
IDE: VS2008 Professional
OS: Windows Vista Home Premium SP2
(Just in case any of this information is needed)
Alright, I'm in the process of writing some software mostly for the fun of it, though it will be useful to others as I have already talked with people about it. Anyhow, on to my issue.
Well, when I started writing the application (a Record Label management system) I was using really inefficient methods and such. I was using things that were not necessary and I wanted this to be more of a quality application than just a "slap-together" project. So I started re-writing some code, re-creating some forms, and so on. The application is MDI and the child windows are for things such as managing sessions, artists, sales, etc.
I have this code which is used to delete an artist. The 'RecordLabel' class is a simple class I wrote that handles the main file I/O (saving/loading the record label data to/from a file). It is referenced like this "RecordLabel recordLabel" in the "MainForm" class. Here is the code from "ArtistsForm":
public Artist GetArtistData()
{
Artist newArtist;
if (null == (newArtist = new Artist()))
return null;
newArtist.UniqueId = txtUniqueId.Text;
newArtist.StageName = txtStageName.Text;
newArtist.FirstName = txtFirstName.Text;
newArtist.LastName = txtLastName.Text;
newArtist.PrimaryPhone = txtPrimaryPhone.Text;
newArtist.SecondaryPhone = txtSecondaryPhone.Text;
newArtist.Email = txtEmail.Text;
newArtist.HomePageUrl = homePageLink.Text;
newArtist.MyspaceUrl = myspaceLink.Text;
newArtist.SoundclickUrl = soundclickLink.Text;
newArtist.HourlySessionRate = txtRecordingRate.Text;
newArtist.Notes = txtNotes.Text;
if (sessionsList.Items.Count > 0)
{
foreach (ListViewItem session in sessionsList.Items)
newArtist.SessionIdList.Add(session.SubItems[0].Text);
}
return newArtist;
}
public bool IsSelectionValid()
{
if ((artistsTree.Nodes[0].Nodes.Count > 0) && (artistsTree.SelectedNode.Level > 0))
return true;
else
return false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
Artist artist;
if ((null != (artist = GetArtistData())) && (IsSelectionValid()))
{
DialogResult result = MessageBox.Show("Are you sure you want to delete the artist named \"" +
artist.StageName + "\"? This operation cannot be undone.", "L.M.E. - Delete Session",
MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (result == DialogResult.Yes)
{
MainForm parentForm;
if (null != (parentForm = (MainForm)this.MdiParent))
{
if (parentForm.DeleteArtist(artist))
{
if (artist.UniqueId != string.Empty)
{
TreeNode node = artistsTree.SelectedNode;
if (node != null)
{
artistsTree.Nodes[0].Nodes.Remove(node);
if (Artists.Count == 0)
System.Diagnostics.Debug.WriteLine("Artists.Count = 0");
foreach (Artist a in Artists)
{
System.Diagnostics.Debug.WriteLine("Unique ID: " + a.UniqueId);
if (a.UniqueId == artist.UniqueId)
{
System.Diagnostics.Debug.WriteLine("Removed: " + a.UniqueId);
System.Diagnostics.Debug.Write("\tArtist ID:" + artist.UniqueId);
Artists.Remove(a);
return;
}
}
}
}
}
}
}
}
}
I have used the Debug.WriteLine and Debug.Write functions in order to (hopefully) find the problem. However, I have had no such luck and I am no closer to the solution than when I originally started to encounter this issue.
Here is the 'MainForm.DeleteArtist' method:
public bool DeleteArtist(Artist artistData)
{
if ((recordLabel == null) || (recordLabel.Artists == null) || (recordLabel.Artists.Count == 0))
return false;
foreach (Artist artist in recordLabel.Artists)
{
if (artist.UniqueId == artistData.UniqueId)
{
recordLabel.Artists.Remove(artist);
switch (recordLabel.SaveDataToDisk(CurrentDataFilePath))
{
case IoErrorCode.NoError:
sessionTimerForm.Artists = recordLabel.Artists;
sessionsForm.ClearArtistsList();
sessionsForm.Artists = recordLabel.Artists;
sessionTimerForm.RemoveArtist(artistData.StageName);
currentActionStatus.Text = "Data saved successfully.";
currentActionStatus.Image = Lab_Management_Environment.Properties.Resources.preferences;
return true;
default:
return false;
}
}
}
return false;
}
Now for the problem. I create two or three example artists and all goes well. It saves all the data appropriately and I can select each artist and the artist's data is displayed properly in all of the input fields.
Once I delete any artist (first, last, third, whatever) it empties my "List<artist> Artists;" object in the "ArtistsForm" class. I have made sure that it is only deleting the artist with the selected artist's ID, and it's correct.
However, it only gets to this point in the code (from "ArtistsForm"):
if (parentForm.DeleteArtist(artist))
{
if (artist.UniqueId != string.Empty)
{
TreeNode node = artistsTree.SelectedNode;
if (node != null)
{
artistsTree.Nodes[0].Nodes.Remove(node);
if (Artists.Count == 0)
System.Diagnostics.Debug.WriteLine("Artists.Count = 0");
No matter what, it hits the "WriteLine" there. It seems to only happen after the call to "parentForm.DeleteArtist". Any suggestions? This is really irritating me. :-P But I've been patient with it and I can wait for a response. I'm in no hurry and this isn't a work project so I have no deadline.
I apologize for any sloppy coding and such. I'm just trying to get this working before I clean it up. I don't really like looking at this code much anymore because my standard coding practice is quite neat and well put together (at least to me).modified on Thursday, March 4, 2010 9:55 PM
|
|
|
|
|
Hi Matt,
I didn't spot the problem you reported right away; however I do have lots of comments, I'll give you some here, as I hope they will inspire you; taking care of them should simplify your code, possibly also eliminating the problem:
1.
Your Artist class is holding strings, even for items that basically are not strings: UniqueID would be better of being an int, HourlySessionRate probably needs to be a float/double/decimal, maybe an int, but not a string.
And yes, that means you need to use a Parse/TryParse method to convert user input to a number, and also ToString() to turn a number to a string for output purposes; but then you can use the numbers to perform calculations, indexing, etc.
2.
you have too many safety tests. Examples:
a) a constructor (e.g. Artist) should either return a real object, or throw an exception; it should never return null.
b) no need to test for an empty list, a foreach will just be skipped when the list is empty.
3.
I tend to name collections by using the plural of the type name they contain. So "students" would be an array, a list, a queue, whatever, holding Student instances. And I don't include "array", "list" or whatever, so I can easily change my mind later on.
4.
Since UniqueID is an important field to your Artist class, why not store Artist instances in a Dictionary<int, Artist> collection? That eliminates searches by UniqueID, just do Artists[UniqueID] as a dictionary can be indexed just like an array.
5.
at the end of btnDelete_Click, you have a foreach loop which attempts to modify the collection you are enumerating; that won't work, as a removal invalidates the enumerator. I expect it throws an exception.
6.
you seem to have several methods that return a bool to indicate success/failure. Most often that is not the best way to do error checking as it forces you to write extra code on every invocation; if you forget some, errors will go unnoticed. The modern way if dealing with this, is by throwing an Exception when something went wrong; then the caller can get that information using one or more try-catch blocks. If you're unfamiliar with them, take the time to read up on it, it comes in very handy.
7.
when catching an exception, NEVER ignore it; either solve the situation in your app, or at the very least report it somewhere, using all available information.
try {
...
} catch(Exception exc) {
Console.WriteLine(exc.ToString());
}
is what I do most of the time. It will tell you exactly what went wrong and where, up to the source line.
|
|
|
|
|
Well, it sucks that you can't find a problem with it. :-P But I do appreciate all the feedback/suggestions for sure. I'm always looking for ways to improve my ability (I'm self-taught; no formal education in the field).
I didn't know anything at all about the Dictionary but I've seen it in articles before. I will definitely take the time to learn how to use them.
The "UniqueId" property in the "Artist" class would be a string. It's generated using numbers as well as letters. I don't know why I didn't think of using a Double for GlobalRecordingRate. I'm doing that the opposite way. In one part of the application it makes calculations using the rate string something like "double Rate = double.Parse(GlobalRecordingRate)", LoL.
The feedback is greatly appreciated.
Now I hope someone can help me with this issue. I'm continuing to investigate on my own, of course. I don't expect others to solve my problem alone when I can't figure it out over time. :-P Anyone have any ideas?
|
|
|
|
|
Even when UniqueID is a string, you can still use it as the key (or index) for a dictionary, so finding the artist of interest would be automatic. Or you could add an int field ("key") that is unique and strictly internal to your app.
I didn't say I can't find the problem, I just didn't see it right away; I am stumbling all to often over things I would do completely differently. With my comments, you could simplify your code, making it much easier to see any remaining problems.
I do have some problem understanding the logic you're applying. You have a delete method that saves data to disk? And as I said, the actual removal is bound to fail, aren't you getting an InvalidOperationException?
|
|
|
|
|
I am looking forward to updating the code to follow your recommendations. I just don't have a lot of time at the moment. I simply wanted to fix this issue.
No, I am not receiving any sort of exception in the area you mentioned. However, I did solve the problem. It was a very strange cause and I really don't understand why it caused the problem. The following line of code caused the issue:
sessionsForm.ClearArtistsList();
which called "Artists.Clear();" in the "SessionsForm" class. The reason I don't understand the issue is because "Artists" is an entirely separate "List" object in an entirely different form's class file. However, making the call to "Artists.Clear()" was unnecessary and now that I look at it I'm wondering why the heck I ever put that in there to begin with.
Thank you very much for the help. I'll be looking into each of your suggestions this weekend (when my schedule permits) in order to understand how they will help me. I will then apply those techniques where needed.
By the way, I call "SaveDataToDisk" because the application has taken a different path than originally intended. I thought the application would be rather small, containing minimal data. But now that I've turned it into the beast that it is (:-P) I am going to have the user manually save via the standard "File->Save", as well as implementing an auto-save feature.
|
|
|
|
|
You're welcome.
Matt U. wrote: "Artists" is an entirely separate "List" object in an entirely different form's class file.
I can't judge that, having seen only a fraction of the code.
FYI: if you have say recordLabel.Artists=Artists; then that still is one and the same list, all the statement does is store a reference to an existing list; so if you then add/delete/modify an item in Artists, you will notice the same change in recordLabel.Artists, and vice versa.
Matt U. wrote: the application has taken a different path
I suggest you make it a habit to change the name of a method (or class) when its purpose in life changes; keep identifier names always as informative and as accurate as is reasonably feasible. And when you can't catch the functionality of a method in its name, add a little comment on top of it, explaining what the method does, using the domain or user terminology (and not the details of the code).
|
|
|
|
|
Right, I fully understand. I do have one more question. How would I go about making the 'RecordLabel recordLabel;' object (which is currently in the 'MainForm' class) accessible throughout the entire application? I currently create a new 'List<artist> Artists' in the 'ArtistsForm' class, for example. I then set it when the data file is loaded (there are other times, too) by "artistsForm.Artists = recordLabel.Artists". But wouldn't this cause the application's memory usage to go up?
BTW, I'm reading up on using 'Dictionary' now. But are there any situations in which a 'Dictionary' would NOT be the best solution?
|
|
|
|
|
Hi,
1.
string a="31232435342452";
string b=a;
string c=b;
looks like it has three strings; in reality only one piece of text is stored somewhere, and its memory address is stored inside the objects a, b, and c. So the memory penalty for copying objects is very limited.
2.
Passing objects around seems to be a difficult concept for the OO novice.
If there ever is only one list of artists, you might make it a public static member of class Artist, so it could get accessed by everyone from everywhere using Artist.artists
However that is not the best way, as sooner or later you'll want two or more lists of artists.
One normally does create the list once, then pass it on to other interested objects, either through a constructor parameter, a method parameter, or by setting a property to that effect.
3.
Dictionaries are fine; their one limitation is all key values must be unique and non-null. Which sounds fine for artists with a UniqueID field.
|
|
|
|
|
Okay, cool. So I think I'll be on the right path once I change some of the code. You're right about the Dictionary keys being fine. In the code all "Artist" objects must have an ID, and it's generated in a way that makes it unique every time. That is, unless the user changes the system date/time to match an existing ID. :-P But there's no point.
|
|
|
|
|
Hello all,
I have an image with black pixels, I want to convert all the pixels to a certain color. How can I do that without setting all the pixels that is black to that color ?
I thought something with the color matrix gdi supports.
Thanks, berlus.
|
|
|
|
|
Get the Location Color of Pixal then Create a image according to Your Requirement. If you can think then I Can.
|
|
|
|
|
Might someone recommend a good Winsock library that makes client/server communication easy? Commercial OK.
Although I'm sure the ones here on CodeProject are good, my project requires something bulletproof.
Anyone familiar with a good one?
I'm looking for something that has an API similar to that of a message-oriented named-pipe, but that, of course, works across the internet.
MSMQ is a bit more robust than I had in mind. I just want to pass messages between applications running on different machines separated by the internet.
It has to make asynchronous comm easy.modified on Thursday, March 4, 2010 4:29 PM
|
|
|
|
|
Richard,
It really depends on what you want to do. The company I currently work for uses TcpClient and TcpListener to communicate data between our apps. There are plenty of examples on this site for that. Search for "IPC" Inter process Communications.
If you are really looking for bullet proof, I would probably recommend MSMQ[^] (Microsoft Message Queue). If you're not a Microsoft fan, then try IBM WebSphere MQ[^] They are supposed to guarantee messages delivery and both are already proven.
I have had personal experience with MSMQ and it was simple to implement in C#.
Good luck and I hope I helped!
Hogan
|
|
|
|
|
Thanks for your response. I've clarified my question with details of what I'm looking for.
|
|
|
|
|
A quick search[^] shows how easy and safe it is for MSMQ over the internet.
Hogan
|
|
|
|
|
Thanks again!
I was originally under the impression that MSMQ was some enterprise thing that you had to purchase separately and run on a dedicated server.
But now it looks like it's entirely contained within .NET, and will work peer-to-peer.
Is this true?
|
|
|
|
|
Sorry I didn't explain that better. Unfortunately it isn't part of the .NET framework. MSMQ is its own install.[^] Once it is set up, it runs great. But as far as I know, you have to set it up on each machine manually. Good luck with your project!
Hogan
|
|
|
|
|
Why not go straight to the source?[^]
It is easy to use and works well.
The System.Net.Sockets.TcpClient class in C# uses it fairly well and provides a real nice interface for both synchronous and asynchronous calls.
|
|
|
|
|
hello to all
i m interested in C# coding devlopment but right now i have a problem that i want to show file names of a directory one by one in a lable when i press a button. can any anybody interested to help me in this way.............
tahnks
|
|
|
|
|
System.IO.Directory.GetFiles("Some Path");
|
|
|
|
|
hello,
I try to do a loop in my service and in the running of the start service he not give me to run the service beacuse i have my loop..
someone know what to do?
Thank You,Thank You!!
|
|
|
|
|
You have to move your actual service code to a background thread.
In the services OnStart handler, traditionally, you're expected to start your services worker on a seperate thread. Your code then can return control back to the Service Manager that told your code to start, thereby avoiding the timeout problem you're probably seeing.
|
|
|
|
|
Can anybody tell me what is wrong with my logic in the following code? I am trying to get a string array to take the names of projects entered one at a time from a text box. I have to be able to add to, delete from and sort the list alphabetically.
I can't use SQL because most of the time this program will be used offline.
When I build and run it I am getting no errors until the button click after entering the text in the box.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace Construction_Survey_Layout
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int PN;
private void btnNew_Click(object sender, EventArgs e)
{
ArrayList Projects = new ArrayList();
Projects[PN] = textBoxAddNew.ToString();
Projects.Add(Projects[PN]);
textBoxAddNew.Clear();
Projects.Sort();
for(int ctr = 0; ctr <= PN; ctr++)
{
listBox1.Items.Add(Projects[ctr]);
}
PN++;
}
}
}
|
|
|
|
|