blah blah blah is here! blah blah » Close

q12
349
13752 views

Save/Load Class

up1down
link

SaveLoad_File.cs
http://www.sendspace.com/file/11pq8w
Warnings_File.cs
http://www.sendspace.com/file/31yohm
_______
Im still a learner so... i need a lot of help.
Actually there are 2 classes (SaveLoad_File.cs and Warnings_File.cs). The warnings i use it externally, linked by SaveLoad class. And i think i am happy with it as concept.
But the main problem remain the SaveLoad class.
_______
Its my first (external) class that i made in my life.
I want to make it perfect. Perfect as saving/loading every case scenario files. Now i have difficulties in understanding it as a whole. At what should i think when i write it?
I know its purpose but how to write it further? (adding new methods and not make my head dizzy,and also my code).
I cant find my words to explain better.
Is anybody good enough to look into this Class i made and tell me how to make it like a professional class? Whats wrong with it to this point?
_______
I am very frustrate with it as it is right now, and demoralized, because its impossible for me to accomplish what i have in mind.
Only with you i can talk about it, i have nobody who can really help me in understanding more of programming concepts.
_______
Ps...its still a working in progress Class and some methods there are private but in the end will be public(i made them like that to have a little space when im testing it). And some variables.

THANK YOU

last answered one year ago

11 answers

link

It might be a typo but this line:

private static string shadow_FullName = shadow_Path + @"\"" + shadow_Name;
// should be
private static string shadow_FullName = shadow_Path + @"\" + shadow_Name; // only one closing double quote

Now, static fields of a class are always initialized before any instance of that class is created. So, if your current directory were c:\myfiles, say, then the above line would initialize shadow_FullName to @"c:\myfiles\x" before the Form was even created.

It would then keep this value until it was assigned a different value.

Consequently, when you execute this line in textBox1_TextChanged:
shadow_Name = textBox1.Text;

it has no effect on shadow_FullName. If you wanted the latter to be changed in line with the change to shadow_Name, then you'd need to add this line immediately afterwards:
shadow_FullName = shadow_Path + @"\" + shadow_Name; // assigns altered value


You might find it easier to define shadow_FullName (and also 'dir') as read only properties rather than fields. Their values will then be dynamically calculated based on the current value of shadow_Name:

private static string shadow_Path = Directory.GetCurrentDirectory();
private static string shadow_Name = "x";

private static string shadow_FullName // now a read only property
{
get { return shadow_Path + @"\" + shadow_Name; } // always uses current value of shadow_Name
}

private DirectoryInfo dir // now a read only property
{
get { return new DirectoryInfo(shadow_FullName); } // always uses current value of shadow_FullName
}


private void textBox1_TextChanged(object sender, EventArgs e)
{
shadow_Name = textBox1.Text;

label2.Text = shadow_Name;
label1.Text = shadow_FullName;
}


However, if you're using 'dir' a lot in a particular method and you know that shadow_FullName won't be changing in the meantime, then I'd assign it to a local variable and use the local variable instead. Otherwise you'll create a new DirectoryInfo object each time you access 'dir' which isn't very efficient.

up1down
link

I find something interesting :
I was testing something and i find something disturbing :

here is a testing code that i play with:

DirectoryInfo dir = new DirectoryInfo(shadow_FullName);
private static string shadow_Path = Directory.GetCurrentDirectory();
private static string shadow_Name = "x";
private static string shadow_FullName = shadow_Path + @"\"" + shadow_Name;


private void textBox1_TextChanged(object sender, EventArgs e)
{
shadow_Name = textBox1.Text;

label2.Text = shadow_Name; //this will render correct
label1.Text = shadow_FullName; //this will NOT render correct


}


The "shadow_Name" is changing outside this method (I verify it with the line i render correct) , then why the shadow_FullName is not rendering correct? It should work.
Or if indeed (i suppose) "shadow_Name" does not change outside method, how to make it change? I need that shadow_FullName to be changeable.
And I think I have some similar mistakes in the Save/Load class somewhere.
thanks.

up0down
link

see my newly updated class here:
http://www.sendspace.com/file/0arvff

And THANKS vulpes... I take your advice in using properties into my class.
I finally see the usefulness of a custom class and the code from it. -its great.
I though wonder if there are shared classes to download from somewhere?
I know the .Net have a lot of them but i want something useful, like to have ready made some usual and very used tasks(like the save and load). Different opinions about same subject did not kill anyone.
thanks.

vulpes
17279

I'd search free sites such as Code Project or CodePlex for classes that other people have written which you may be able to use in your own work. The former, in particular, has a ton of new articles every week, many of which are written in C#. If you sign up, they'll send you an e-mail newsletter so you can see what's been added recently.

q12
349

thanks my dear vulpes. In Code Project i have already an account but i did not think to ask there. I will try the CodePlex also to see what are you talk about. I should refer to their forums and ask them the same as here. Pity really that you dont have a shared folder with such things(your fame will grow considerably[through word of world]. ) , because you will help considerably some rookies like us :) thank you vulpes. You are great guys(or a single guy).

up0down
link

hy vulpes. Im in trouble and i don't know what to ask properly to make my self understandable. They point me to .Net Framework, but we both know that is not what im looking for. At this point for my defence i can say that i can search (with some grad of success) in Object browser, i see(i am familiar) and understand some big classes - and also i use them(from framework). So is not about how to use or become familiar with Net Framework. I ask a little more than that, but i can't find my words properly to formulate accordingly. At what i can think right now [what i search for] is some sort of database with classes "readyToUse" , tested and working, and common used by everybody (but not so told/publicized), directly in their app(and not refer to them for use)- hell, see? i cant have the language very well learned to formulate accordingly . And here i want your help.
________
... Let me summarize a little. I need classes that are made by you, him, mr John Doe,mr Bush, or whatever etc, all that treat a single specific subject.In the final, I will have x variants to look into over a single subject.
That i search. Somebody who have some couple of classes and they are so well build that he only call a class and use its methods in the most (common) situations that he encounter - and this is at what i refer when i say "readyToUse".
I remember i see some long time ago in hurry a custom library(with classes) made by somebody (unknown) that work as i described but was for borland c language, back then.
_______
I think i find THE WORD for what im looking for: [Code Library]
This is what i need. I hope is the right word. :)
You know a good site to find some interesting 'code library' ?
thank you.
~q12~

vulpes
17279

Yes, code library is the general term for a bunch of classes which developers can use to add particular kinds of functionality to their applications. This is usually done because the functionality in question would be too difficult or time consuming for most developers to program themselves. As well as the sites I've already mentioned, there's also SourceForge though a lot of their libraries are for unmanaged C/C++ developers. But, at the end of the day, if you know what you're looking for, then google is your friend. After 10 years, there are not many topics which haven't been addessed by some .NET programmer somewhere who's prepared to share his (or her) work with others :)

up0down
link

hy vulpes.
I start searching, asking people but everywhere i ask and search i cant find something simple (just complicated Code Library -and here an example: "Open Source Zip Compatible Compression Library in C#" ) . But i don't need (for the moment(maybe in future)) to use this kinds of library , i need SIMPLE ones (most COMMON ones) like a save/load library, or what ever. Can you help me in this matter? Thank you.

~Teo aka q12~
:)

vulpes
17279

t's difficult to find something like that because, as I said earlier, the focus is on providing other programmers with stuff that they'd find it difficult or time consuming to write themselves. There are sites which provide code snippets for various tasks (check out http://www.java2s.com/Code/CSharp/CatalogCSharp.htm) which you can use to build your own classes. I also found a simple class for reading CSV text files at http://www.stellman-greene.com/CSVReader/ which I think you'll find interesting as it's a common programming task.

q12
349

thanks, vulpes, i will look into it right now.

up0down
link

Ways of Storing
I am sorry for this but i find it very interesting and i want some opinions about it:
I opened some {*.ini, *.log, *.txt, *.dat} files in c:\WINDOWS\ and i find some very-Very interesting similarities between them.
I made a compilation with some different ways of storing that i find in some of these files(most interesting ones). And I find that some specific rules are applied. Somebody know about these rules? Or they are "monkey see,monkey do" type of rules? In this moment im the monkey. But it will help some advice from the best.

here is my loooooong review:
_____________________________________________________________
; for 32-bit app support - (space separated comment)

[ac3api] ;parent (in line comment)
;When a client app opens AC3 device 0, it refers to the default device as
;specified by the following flag. Actual indexing begins from 1.
;DefaultDevice=1 refers to the first AC3 device in the system.
DefaultDevice=1 ;child(s)
; another comment(no space)
[fonts]
[extensions]
[files]
[WinampReg]
NeedReg=0 ;int value assigned to a variable
[Options]
WordSel=0
Units=0
Maximized=0
FrameRect=AAAAAACAAAAAABAAAAAAAAADAAAAAAAA ;array? values
DefaultFormat=5

[Mail]
CMCDLLNAME32=mapi32.dll ;if x opened then mapi32 active
CMC=1
MAPI=1
MAPIX=1
MAPIXVER=1.0.0.1
OLEMessaging=1
[Xtreme Sample Database 2008]
Driver32=C:\WINDOWS\system32\odbcjt32.dll

[07/01/2010 08:37:24] Success Include script: SetFolderPermissions.lua
[07/03/2010 05:37:54] Error Remove folder: d:\Matrix Games (145)
[07/03/2010 05:37:54] Notice Exit uninstall process (Return code: 0)
[07/01/2010 08:37:24] Notice Start project event: Global Functions
[07/01/2010 08:37:24] Success Run project event: Global Functions

UI_03=No
UI_20=Yes
UI_21=No
UI_25=No
UI_30=Yes

STARTUP=Yes
INSTALLDIR=C:\Program Files\HP\
[Strings] ;<<<<<<<<<<<<<<<<
_TargetDatFile=autorun,scr
%Preload%=%InstallDirx86%Digital Imaging\%CDGuid%\ ;string value assigned to a variable
%ICETemp%=%ProgramFilesx86%%ICETempInPF%\
%ICETempInPF%=%Manufacturer%\Temp\%CDGuid%

[Wup.OptOut]
1=ProductAssistantOpted ;list? values
2=ProductAssistantNever
3=HPSUNotify
4=HPSUDays
[Wup.ProductAssistantOpted]
Key=HKEY_LOCAL_MACHINE\SOFTWARE\Hewlett-Packard ;registry value assigned to a variable
Value=OptInCompleted ;obj? value assigned to a variable
OptInData=1
OptOutData=1
DisplayRegKey=HKEY_LOCAL_MACHINE\SOFTWARE\Hewlett-Packard\Installed Products\%eSupportGUID%
LanguagesInthisCD=enu,esn,fra,ita,deu,ptb,nld,cht,chs,csy,dan,ell,fin,hun,kor,nob,plk,rus,sve,trk
DefaultLanguageInThisRelease=enu ;array(definitively)/enum? value assigned to a variable
_____________________________________________________________

vulpes
17279

Well .ini files do use a standard format (see http://en.wikipedia.org/wiki/INI_file for details). The formats for .log files will differ depending on what it is that's being logged but .txt and .dat files could contain data in any format. It's common though to use the .txt suffix for 'comma separated' files where each line is a data record whose fields are separated by commas or by some other separator.

up0down
link

I finally made it working!!! I made a test here actually and i made it work. I can save and load from a text file...yeeey.
Vulpes, how can I made it more compact? I want to transform it into a stand alone Class that I can call it from anywhere in any situation. Any suggestions?
Thanks
Here is the code:

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 SaveLoadNamespace;
using WarningsNamespace;
using System.Text.RegularExpressions;

namespace test7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SaveLoadClass slc = new SaveLoadClass();
WarningsClass wc = new WarningsClass();


string tampon;
private void buttonSave_Click(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
tampon = "checkBox = true" + "\r\n";
}
else
{
tampon = "checkBox = false" + "\r\n";
}

tampon += "numericUpDown = " + numericUpDown1.Value.ToString() + "\r\n"; ;
tampon += "comboBox = " + comboBox1.Text + "\r\n"; ;

slc.file_SaveFile(tampon); label2.Text = wc.w2;

}

string buffer, s = ""; int i, j = 0;
private void buttonLoad_Click(object sender, EventArgs e)
{
//STRING MANIPULATION !!!
slc.file_LoadFile(); label1.Text = buffer = slc.textToLoadInto; label3.Text = wc.w5;

#region <_____ NumericUpDown _____>
//NumericUpDown
if (buffer.Contains("numericUpDown"))//if that,then should goto there
{
i = buffer.IndexOf("numericUpDown");
s = buffer.Remove(0, i); //remove the Begining of string
if (s.Contains("\r\n")) //folowing operations remove the Ending part of the string
{
i = s.IndexOf("\r\n");
j = s.Length - i;
s = s.Remove(i, j);
}
if (s.Contains("="))
{
i = s.IndexOf("=") + 1;
s = s.Remove(0, i).Trim();
}

i = int.Parse(s);
numericUpDown1.Value = i;
}
#endregion >NumericUpDown-END<

#region <_____ checkBox _____>
//checkBox
if (buffer.Contains("checkBox"))//if that,then should goto there
{
i = buffer.IndexOf("checkBox");
s = buffer.Remove(0, i); //remove the Begining of string
if (s.Contains("\r\n")) //folowing operations remove the Ending part of the string
{
i = s.IndexOf("\r\n");
j = s.Length - i;
s = s.Remove(i, j);
}
if (s.Contains("="))
{
i = s.IndexOf("=") + 1;
s = s.Remove(0, i).Trim();
}

if (s.Contains("true"))//s.Contains here is for: in case of whitespaces
{
checkBox1.Checked = true;
}
if (s.Contains("false"))
{
checkBox1.Checked = false;
}
}
#endregion >checkBox-END<

#region <_____ comboBox _____>
//comboBox
if (buffer.Contains("comboBox"))//if that,then should goto there
{
i = buffer.IndexOf("comboBox");
s = buffer.Remove(0, i); //remove the Begining of string
if (s.Contains("\r\n")) //folowing operations remove the Ending part of the string
{
i = s.IndexOf("\r\n");
j = s.Length - i;
s = s.Remove(i, j);
}
if (s.Contains("="))
{
i = s.IndexOf("=") + 1;
s = s.Remove(0, i).Trim();
}

comboBox1.Text = s;
}
#endregion >comboBox-END<


}
}
}

The output is like this:
checkBox = true
numericUpDown = 24
comboBox = red

vulpes
17279

TBH, I don't really think you can make it any more compact than it is. The problem is that a different form or project would contain different controls (or perhaps similar controls with different names). Also, what goes into the text file might be conditional on the value of certain controls (here it depends on whether checkBox1 is checked or not). So, I don't think there's any sensible alternative to hand coding your 'save' and 'load' methods each time to (respectively) concatenate or split a string depending on the controls on the form, and then using your SaveLoadClass to do the rest.

q12
349

My idea is to make some overloads methods for: [int,string,bool](i suppose even for a object but is a to high standard for me). What do you think? somebody wrote-me an answer in the mean time : " you could build a method to which you can pass a form. To get the controls at the passed form use the Controls-Property: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controls.aspx Check the type of each control to get the name like 'checkBox' for your string. Btw: Instead of using the type-name of each control I would suggest using the ID, so that you can store more than one checkbox for example. Hope this helps you a bit. " But its too advanced for me and i dont know from where to start . Can you make me a sample to start with or give me a good tutorial for this kind of stuff ? Thank you.

up0down
link

Well, you could write general methods which operate on a form's Controls collection as long as you're happy for all instances of a particular kind of control on a form to be 'serialized' and 'deserialized' in this way.

Below, I've shown how you could do this if you're only interested in checkboxes, numericupdowns and comboboxes and these are all placed directly on the form and not within other containers such as panels or groupboxes (you could still do it in these latter cases but you'd then need to iterate through the container's own Controls collection as well).

public static class SaveLoadHelper
{
public static string ConcatenateControlValues(Form form)
{
List<string> list = new List<string>();
string temp = null;

foreach (Control c in form.Controls)
{
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
temp = cb.Name + " = " + cb.Checked.ToString();
list.Add(temp);
}
else if (c is NumericUpDown)
{
NumericUpDown nud = (NumericUpDown)c;
temp = nud.Name + " = " + nud.Value.ToString();
list.Add(temp);
}
else if (c is ComboBox)
{
ComboBox combo = (ComboBox)c;
temp = combo.Name + " = " + combo.Text;
list.Add(temp);
}
}
return String.Join("\r\n", list.ToArray());
}

public static void RepopulateControls(Form form, string buffer)
{
string[] lines = buffer.Split(new string[]{"\r\n"}, StringSplitOptions.None);
foreach(string line in lines)
{
string[] items = line.Split(new string[]{" = "}, StringSplitOptions.None);
if (form.Controls.ContainsKey(items[0]))
{
Control c = form.Controls[items[0]];
if (c is CheckBox)
{
CheckBox cb = (CheckBox)c;
cb.Checked = Convert.ToBoolean(items[1]);
}
else if (c is NumericUpDown)
{
NumericUpDown nud = (NumericUpDown)c;
nud.Value = Convert.ToDecimal(items[1]);
}
else if (c is ComboBox)
{
ComboBox combo = (ComboBox)c;
combo.Text = items[1];
}
}
}
}

}

// now on form

private void buttonSave_Click(object sender, EventArgs e)
{
tampon = SaveLoadHelper.ConcatenateControlValues(this);
slc.file_SaveFile(tampon);
label2.Text = wc.w2;
}

string buffer;

private void buttonLoad_Click(object sender, EventArgs e)
{
slc.file_LoadFile();
label1.Text = buffer = slc.textToLoadInto;
label3.Text = wc.w5;
SaveLoadHelper.RepopulateControls(this, buffer);
}

q12
349

ohoauuuu you are the best, believe me. Extraordinary. Tested and working. Fantastic. But I see there some aliens of codes...just oau. I am looking like a monkey at a Ferrari engine. Thanks Vulpes.

q12
349

I was asking myself,looking over your code, what is this line for - ___ CheckBox cb = (CheckBox)c; ?___ How is called? And for what is used in general? ___I never find this expression anywhere and is looking to be a very helping one. I speculate that is another form to create an object? But im not so sure because intellisense dont find it for me(i usually use intellisense to correct myself in many situations) Thanks.

vulpes
17279

The reason for that line is that 'c' is a Control variable but we really want a CheckBox variable so we can access its Checked property. We therefore cast 'c' to CheckBox and store it in a new variable 'cb'. This works because CheckBox (and all other controls) ultimately derive from the Control class. Now all controls have Name and Text properties and so it's not really necessary to do this in some cases such as ComboBox. However, I thought I'd do them all the same to establish a pattern which you can follow when adding other controls.

up0down
link

I think I made it how I like it the most and i can proudly name it that is all right ... 2 nights over this but I bring it down right where I want it to be. Phew.
Now I am happy with it.
I KNOW that your method(Vulpes) is more elegant and maybe more easy to use than mine, BUT, I cant use something im not certain i understand it very well ,so i will go with what im familiar the most...so i made this class after all. Its not perfect but its very close,so im happy with it.
I know i must learn and assimilate /the faster the better/ the arrays and lists that you(Vulpes) master them soooo well, and i am angry for that, but... i will.
About this matter, some good exercises that cant be done without them(arrays&lists&othersLikeThem) ,and who can be done without make me thinking about what I know already but direct me to learn them well? Thanks,and I appreciate.

So, here is my Class:

using System.Windows.Forms;
using SaveLoadNamespace;
namespace ExtractionsNamespace
{//call ALL these methods with :
//using ExtractionsNamespace;
//Extractions ex = new Extractions();
public class ExtractionsClass
{
SaveLoadClass slc = new SaveLoadClass();

//STRING MANIPULATION !!!




public string tampon;
#region <_____ AddControl _____>
//if (checkBox1.Checked) tampon = "checkBox = true" + "\r\n";
// else tampon = "checkBox = false" + "\r\n";
//tampon += "comboBox = " + comboBox1.Text + "\r\n";
//tampon += "numericUpDown = " + numericUpDown1.Value.ToString() + "\r\n";
//tampon += "progressBar = " + progressBar1.Value + "\r\n";
#endregion >AddControl-END<
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: ex.AddControl(checkBox1, checkBox1.Checked);</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void AddControl(Control c, bool checkToAdd)
{
if (checkToAdd)
tampon += c.Name + " = true" + "\r\n";
else tampon += c.Name + " = false" + "\r\n";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: ex.AddControl(comboBox1, comboBox1.Text);</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void AddControl(Control c, string textToAdd)
{
tampon += c.Name + " = " + textToAdd + " \r\n";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: ex.AddControl(numericUpDown1, numericUpDown1.Value.ToString());</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void AddControl(Control c, int valueToAdd)
{
tampon += c.Name + " = " + valueToAdd + " \r\n";
}
public void EraseAll()
{
tampon = "";
}







public string buffer; string s = ""; int i, j = 0; bool tf;
private void Extracttor(string _TextToExtract_)
{
i = buffer.IndexOf(_TextToExtract_);
s = buffer.Remove(0, i); //remove the Begining of string
if (s.Contains("\r\n")) //folowing operations remove the Ending part of the string
{
i = s.IndexOf("\r\n");
j = s.Length - i;
s = s.Remove(i, j);
}
if (s.Contains("="))
{
i = s.IndexOf("=") + 1;
s = s.Remove(0, i).Trim();
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: numericUpDown1.Value = Extract_int("numericUpDown");</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public int Extract_int(string _TextToSearchFor_)
{
if (buffer.Contains(_TextToSearchFor_))//if that,then should goto there
{
Extracttor(_TextToSearchFor_);
i = int.Parse(s);
}
return i;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: checkBox1.Checked = Extract_bool("checkBox");</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public bool Extract_bool(string _TextToSearchFor_)
{
if (buffer.Contains(_TextToSearchFor_))//if that,then should goto there
{
Extracttor(_TextToSearchFor_);
}
if (s.Contains("true"))
{
tf = true;
}
if (s.Contains("false"))
{
tf = false;
}
return tf;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: comboBox1.Text = Extract_string("comboBox");</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public string Extract_string(string _TextToSearchFor_)
{
if (buffer.Contains(_TextToSearchFor_))//if that,then should goto there
{
Extracttor(_TextToSearchFor_);
return s;
}
return "string_?";
}





//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: ex.file_SaveFileX();</summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void file_SaveFileX()
{
slc.file_SaveFile(tampon); //{ex.AddControl(comboBox1, comboBox1.Text);.....slc.file_SaveFile(ex.tampon);}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// <summary>call with: label1.Text= ex.file_LoadFileX(); </summary>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public string file_LoadFileX()
{
slc.file_LoadFile();
return buffer = slc.textToLoadInto; //{ slc.file_LoadFile(); label1.Text = ex.buffer = slc.textToLoadInto;......numericUpDown1.Value = ex.Extract_int("numericUpDown");}
}


}
}

And here is the implementation on form:
using System;
using System.Windows.Forms;
using WarningsNamespace;
using ExtractionsNamespace;

namespace test7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
WarningsClass wc = new WarningsClass();
ExtractionsClass ex = new ExtractionsClass();


private void buttonSave_Click(object sender, EventArgs e)
{
ex.EraseAll();


ex.AddControl(checkBox1, checkBox1.Checked);
ex.AddControl(checkBox2, checkBox2.Checked);
ex.AddControl(checkBox3, checkBox3.Checked);
ex.AddControl(numericUpDown1, numericUpDown1.Value.ToString());
ex.AddControl(numericUpDown2, numericUpDown2.Value.ToString());
ex.AddControl(comboBox1, comboBox1.Text);
ex.AddControl(progressBar1, progressBar1.Value);

ex.AddControl(radioButton1, radioButton1.Checked);
ex.AddControl(radioButton2, radioButton2.Checked);
ex.AddControl(radioButton3, radioButton3.Checked);
//------

ex.file_SaveFileX(); label2.Text = wc.w2;
}



private void buttonLoad_Click(object sender, EventArgs e)
{
label1.Text = ex.file_LoadFileX(); label3.Text = wc.w5;
//------
checkBox1.Checked = ex.Extract_bool("checkBox1");
checkBox2.Checked = ex.Extract_bool("checkBox2");
checkBox3.Checked = ex.Extract_bool("checkBox3");
numericUpDown1.Value = ex.Extract_int("numericUpDown1");
numericUpDown2.Value = ex.Extract_int("numericUpDown2");
comboBox1.Text = ex.Extract_string("comboBox1");
progressBar1.Value = ex.Extract_int("progressBar1");

radioButton1.Checked = ex.Extract_bool("radioButton1");
radioButton2.Checked = ex.Extract_bool("radioButton2");
radioButton3.Checked = ex.Extract_bool("radioButton3");
}


#region <_____ mouseProgressBar _____>
int somemousecoordonates;
private void progressBar1_MouseMove(object sender, MouseEventArgs e)
{
somemousecoordonates = e.X;
}
private void progressBar1_Click(object sender, EventArgs e)
{
progressBar1.Value = somemousecoordonates;
label2.Text = somemousecoordonates.ToString();
}
#endregion >mouseProgressBar-END<


BTW, this is what i call a perfect example of [Code Library]. Something like this somewhere, cant be found? Of course for other subjects and matters(not just for savings or loadings).
:) And the Output is looking like this somewhere in a text file:
checkBox1 = true
checkBox2 = false
checkBox3 = true
numericUpDown1 = 14
numericUpDown2 = 56
comboBox1 = red
progressBar1 = 5
radioButton1 = false
radioButton2 = true
radioButton3 = false

Thanks Vulpes for all the support. You are a veritable vulpes.

vulpes
17279

One advantage of the way you've done it is that you can specify precisely those controls whose values you want to save. So, if you had a checkBox4 whose value you weren't bothered about, you wouldn't need to save it as you would with my method. As a general rule, it's nearly always better to build your own code libraries rather than look for 'off the peg' solutions. Your classes then do exactly what you want - no more, no less - and, if your needs change, you can change your library accordingly. The only exceptions to this rule are where the code is too difficult or would be too time consuming for you to write yourself which is certainly not the case here.

q12
349

so, in essence , its good to make my own set of [Code Library] and not bother to "borrow" from others ? My contra-argument is that : is easier for me to "monkey see monkey do" /or/ recalibrate over a ready made class than make myself my own from scratch classes. ___________ Im a very good monkey and I can easily reformulate "any" class to my needs(say in 1 night I can reformulate 10 classes) , rather than make myself in 1 night a single lousy class. This is my real pain and I suffer deeply because of that. But, without alternatives i will make some classes but in a very long time and my efficiency will drop enormously. I suppose in this wide internet , they MUST exist , in form of packages or something.... you are more qualified to tell me this things because you are sniffing them more and easier than I do. (free is better, paid is good-any way, put a finger on them and show me). thanks ;)

vulpes
17279

I'm not saying you shouldn't use other people's code snippets - everybody does that - but what I am saying is that the only way to learn programming is to do some even if, at first, you make a lot of mistakes and it takes you longer than just altering somebody else's code. In the long run, this pays dividends because you can then code something that does exactly what you want. I've never seen an article which does something similar to what you want here (and you've sorted it out now anyway) but I have seen articles on the much more difficult problem of saving the entire state of a form (i.e. ALL of each control's properties) so you can restore it later. In fact there was one recently on Code Project - see http://www.codeproject.com/KB/dialog/SavingTheStateOfAForm.aspx - but it may not be particularly easy to adjust that code to just save a certain property for each control you're interested in.

up0down
link

Hy Vulpes, I need a suggestion from you:
I want to make a saving program that is for windows only (not for internet) and who can imitate the Forum(in general) type of writing a text , store and display. Like the one i am writing right now. With a list box to display some saved text from a file, a textbox under -to write and save into that file.And a comboBox that can sort all "posts". Basically this is the hard part, the rest are decorations.
How do you recommend me to do:
Make for every "post" a file (for 100 posts will be 100 files) and the sorting is based on those files-its more intuitive to program it this way for me in my stage.
OR - the very hard part: (because i know only the basics in string manipulation)...
Make a single file with all the text and sorted it out by manipulating a string who contain the entire file.(a string that can retain in itself 99999999999999 characters-its even possible?-i doubt it.
OR
Again a single file that can be sorted but with the help of another one that contain some [sortings by address] from that large one. Basically there will be 2 files one with keywords representing addresses and the text attached to them, and the second one with only the keywords address.
But This is a little overwhelming for me to think about and i seek help from you, the guru of programming world.
Please give me a good solution...and how to think it through(programmatically).
Thank you.

up0down
link

It sounds like you're trying to build some sort of 'notes' database.

I'd certainly keep each 'post' (or 'note') in a separate file, rather than in one large file, and keep them all in the same folder. I'd name the files in chronological order of creation: post1.txt, post2.txt and so on.

I'd give each post a title so you can index/sort them using that.

Finally, I'd create an index file, postindex.txt, which would look like this:

Title1,1
Title2,2
etc.

In other words each line would contain a title and the number of the corresponding post file, separated by a comma.

When the application starts, you'd then need to load postindex.txt and put the entries into a SortedList, say, which you'd then update as new posts were added or existing posts were amended or deleted.

Here's something which I've quickly thrown together though it takes a lot of work to make something like this truly robust.

You'll need a listbox to store the titles, a textbox to display/edit the current title and a richtextbox to display the text for that title.

You'll also need buttons to:

* add a new post

* edit an existing post

* cancel a new addition or edit

* save a new addition or edit

* delete an existing post

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.IO;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// private fields

private SortedList<string, int> posts;
private int lastPost = 0;
private string restoreTitle = "";
private string restoreText = "";
private const string postIndexPath = @"d:\posts\postindex.txt"; // or whatever

private enum Mode
{
None,
View,
New,
Edit
}

private Mode mode = Mode.None;

// eventhandlers - add skeletons from VS designer

private void Form1_Load(object sender, EventArgs e)
{
posts = new SortedList<string, int>();
if (File.Exists(postIndexPath))
{
string[] lines = File.ReadAllLines(postIndexPath);
if (lines.Length > 0)
{
int max = 0;

// populate the sorted list and work out number of last new post
foreach (string line in lines)
{
string[] items = line.Split(',');
int num = int.Parse(items[1]);
if (num > max) max = num;
posts.Add(items[0], num);
}

lastPost = max;

// load listBox1 with all the sorted titles and select first one
PopulateListBox(0);

// load first post
LoadPost(posts.Keys[0]);
}
}

if (posts.Count == 0)
{
ChangeMode(Mode.New);
}
else
{
ChangeMode(Mode.View);
}
}


private void btnNew_Click(object sender, EventArgs e)
{
restoreTitle = textBox1.Text;
restoreText = richTextBox1.Text;
ChangeMode(Mode.New);
textBox1.Text = "";
richTextBox1.Text = "";
}

private void btnEdit_Click(object sender, EventArgs e)
{
restoreTitle = textBox1.Text;
restoreText = richTextBox1.Text;
ChangeMode(Mode.Edit);
}

private void btnSave_Click(object sender, EventArgs e)
{
string title = textBox1.Text.Trim();
if (title == "")
{
MessageBox.Show("Please give this post a title.", "Missing Title");
textBox1.Focus();
return;
}
if (mode == Mode.New)
{
if (posts.ContainsKey(title))
{
MessageBox.Show("A post already exists with that title. Please amend.", "Duplicate Title");
textBox1.Focus();
return;
}
posts.Add(title, ++lastPost);
string path = @"d:\posts\post" + lastPost.ToString() + ".txt";
File.WriteAllText(path, richTextBox1.Text);
SaveIndexFile();
PopulateListBox(posts.IndexOfKey(title));
}
else // mode == Mode.Edit
{
int index = posts.IndexOfKey(restoreTitle);
int value = posts.Values[index];
if (title == restoreTitle)
{
string path = @"d:\posts\post" + value.ToString() + ".txt";
File.WriteAllText(path, richTextBox1.Text); // overwrites existing file
}
else if (posts.ContainsKey(title))
{
MessageBox.Show("Another post already exists with that title. Please amend.");
textBox1.Focus();
return;
}
else
{
posts.RemoveAt(index);
posts.Add(title, value);
string path = @"d:\posts\post" + value.ToString() + ".txt";
File.WriteAllText(path, richTextBox1.Text); // overwrites existing file
SaveIndexFile();
PopulateListBox(posts.IndexOfKey(title));
}
}
ChangeMode(Mode.View);
}

private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to cancel?", "Cancel Pressed", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
textBox1.Text = restoreTitle;
richTextBox1.Text = restoreText;
if (posts.Count == 0)
{
ChangeMode(Mode.New);
}
else
{
ChangeMode(Mode.View);
}
}
}

private void btnDelete_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to delete this post?", "Delete Pressed", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
int index = posts.IndexOfKey(textBox1.Text);
int value = posts.Values[index];
posts.RemoveAt(index);
string path = @"d:\posts\post" + value.ToString() + ".txt";
File.Delete(path);
SaveIndexFile();
if (posts.Count == 0)
{
listBox1.Items.Clear();
textBox1.Text = "";
richTextBox1.Text = "";
ChangeMode(Mode.New);
}
else
{
int newIndex = index;
if (newIndex > posts.Count - 1) newIndex = 0;
PopulateListBox(newIndex);
}
}
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadPost(posts.Keys[listBox1.SelectedIndex]);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (mode == Mode.New || mode == Mode.Edit)
{
DialogResult result = MessageBox.Show("Discard the current changes?", "Close Pressed", MessageBoxButtons.YesNo);

if (result == DialogResult.No)
{
e.Cancel = true;
}
}

}

// custom methods

private void PopulateListBox(int selectedIndex)
{
listBox1.Items.Clear();

foreach (string key in posts.Keys)
{
listBox1.Items.Add(key);
}

listBox1.SelectedIndex = selectedIndex;
}

private void LoadPost(string title)
{
textBox1.Text = title;
// load the text of the post into richTextBox1
string path = @"d:\posts\post" + posts[title].ToString() + ".txt";
richTextBox1.Text = File.ReadAllText(path);
}

private void ChangeMode(Mode newMode)
{
mode = newMode;

if (mode == Mode.View)
{
textBox1.ReadOnly = true;
richTextBox1.ReadOnly = true;
btnNew.Enabled = true;
btnSave.Enabled = false;
btnCancel.Enabled = false;
if (posts.Count == 0)
{
btnEdit.Enabled = false;
btnDelete.Enabled = false;
listBox1.Enabled = false;
btnNew.Focus();
}
else
{
btnEdit.Enabled = true;
btnDelete.Enabled = true;
listBox1.Enabled = true;
listBox1.Focus();
}
}
else
{
textBox1.ReadOnly = false;
richTextBox1.ReadOnly = false;
listBox1.Enabled = false;
btnSave.Enabled = true;
btnNew.Enabled = false;
btnEdit.Enabled = false;
btnDelete.Enabled = false;
btnCancel.Enabled = true;
textBox1.Focus();
}
}

private void SaveIndexFile()
{
string[] lines = new string[posts.Count];

for (int i = 0; i < posts.Count; i++)
{
lines[i] = posts.Keys[i] + "," + posts.Values[i].ToString();
}

File.WriteAllLines(postIndexPath, lines);
}
}
}

Feedback