zachattack05 70 Posting Pro in Training

It depends ... you need to set a maximum length for your password on the user interface side before its encrypted, of say, 20 characters. Then you need to generate a password hash for a 20 character string and make your database column about %20 longer than that value just to be safe. I use varchar since i'm doing english-only applications but I suppose you really should be using nvarchar to be "proper".

Please mark this thread as solved if you have found a solution to your issue and good luck!

Great!

I'll see what I can do with the password limit. That's a good idea.

Thanks for the help!

zachattack05 70 Posting Pro in Training

The # marks the table as a temporary table. The SQL Server drops the table when your connection dies. You don't want to do that for permanent tables. I did it so I wouldn't have to clean up afterwards ;)

You didn't specify identity on your primary key. Try this code:

private void YouDidntPostYourEntireMethod()
    {
      if (File.Exists(ExecutablePath + "\\idcc_data\\_IDCC.sdf") == true)
      {
        SqlCeCommand cmd;
        SqlCeConnection connection = new SqlCeConnection("DataSource=" + ExecutablePath + "\\idcc_data\\_IDCC.sdf");
        connection.Open();
        // the file exists let's create the user table
        string UserTableCreate = BuildSql();
        cmd = new SqlCeCommand(UserTableCreate, connection);
        cmd.ExecuteNonQuery();
        connection.Close();
      }
    }

    private static string BuildSql()
    {
      List<string> Sql = new List<string>();
      Sql.Add("IF OBJECT_ID('tblUsers', 'U') IS NULL");
      Sql.Add("Create Table tblUsers");
      Sql.Add("(");
      Sql.Add("  ID int identity(1000, 1) PRIMARY KEY,");
      Sql.Add("  txtUser nvarchar(40),");
      Sql.Add("  mdaPass text,");
      Sql.Add("  intALevel tinyint");
      Sql.Add(")");
      StringBuilder sb = new StringBuilder();
      foreach (string s in Sql)
        sb.AppendLine(s);
      return sb.ToString().Trim();
    }

Also the text datatype has been deprecated in favor of varchar(max) / nvarchar(max) in SQL2005 and later. Unless the "mdaPass" field is going to be 8000+ characters you could just use a varchar / nvarchar data type.

Yay! Your a life saver! Thank you so much!

PS - I would have posted my entire method but most of it is irrelevant...in the future I'll make sure to post all of it.

Also, the mdaPass field (which actually should be shaPass) is going to hold the encrypted password for the user...in general what data type and length do people use to hold those? I …

zachattack05 70 Posting Pro in Training

I will post the code for creating an empty table .. but how is that going to help with your problem?

...

I don't know if ce-sql is the same as standard MSSQL? But here is how you would do it with standard MSSQL:

IF OBJECT_ID('tempdb..#tblUsers', 'U') IS NOT NULL DROP TABLE #tblUsers
Create Table #tblUsers
(
  ID int identity(1,1) PRIMARY KEY,
  txtUser nvarchar (40),
  mdaPass text,
  intALevel tinyint
)

Also you're specifying a width on your tinyint column. Integral data types cannot have a size specification as that is determined by the type of integer, ie tinyint. You have the same problem for your first column int (11) .

I fixed the width problem (honestly I have never created tables using SQL syntax, when I do it on web servers I always used PhpMyAdmin...

Anyway I still can't figure this out, I read over your code and changed mine to nearly identically match. Here's what I have now:

if (File.Exists(ExecutablePath + "\\idcc_data\\_IDCC.sdf") == true)
                    {
                        SqlCeCommand cmd;
                        SqlCeConnection connection = new SqlCeConnection("DataSource=" + ExecutablePath + "\\idcc_data\\_IDCC.sdf");
                        connection.Open();
                        // the file exists let's create the user table
                        string UserTableCreate = "CREATE TABLE tblUsers ( "
                            + "ID INT (1,1) PRIMARY KEY, "
                            + "txtUser nvarchar (40), "
                            + "mdaPass TEXT, "
                            + "intALevel TINYINT )";
                        cmd = new SqlCeCommand(UserTableCreate, connection);
                        cmd.ExecuteNonQuery();
                        connection.Close();

I tried adding the # sign to the front of the table name...no dice, it says its a reserved character...figures. I keep getting:

The specified data …

zachattack05 70 Posting Pro in Training

Would anyone have the heart to post some example code to create an empty table? My code doesn't seem to work, it says the data type "int" in invalid...here's what I have:

if (File.Exists(ExecutablePath + "\\idcc_data\\_IDCC.sdf") == true)
                    {
                        SqlCeCommand cmd;
                        SqlCeConnection connection = new SqlCeConnection("DataSource=" + ExecutablePath + "\\idcc_data\\_IDCC.sdf");
                        connection.Open();
                        // the file exists let's create the user table
                        string UserTableCreate = "CREATE TABLE tblUsers ("
                            + "ID int (11) NOT NULL AUTO_INCREMENT, "
                            + "txtUser nvarchar (40), "
                            + "mdaPass text, "
                            + "intALevel tinyint (2) )";
                        cmd = new SqlCeCommand(UserTableCreate, connection);
                        cmd.ExecuteNonQuery();
                        connection.Close();


                    }

Some simple sample code would be great...I guess I just can't figure the syntax out and I've looked everywhere, nothing seems to work.

zachattack05 70 Posting Pro in Training

>> 1) Are "plug-ins" a common thing for applications to support? As in..."copy this .dll (or whatever) to this folder and bam! you get more features!"

That really depends on the type of application. Some applications also offer plugins but only from the software vendors. ie an accounting software package might have different modules that under the hood they treat as plugins, but you have to purchase the plugins from the vendor. However if you take a look at WinAmp they offer plugins that anyone can author. It takes quite a bit of labor & documentation to expose a plugin interface to your application.

>>2) How do most people handle updates? Replace the entire executable or "patch" the file?
This depends on your deployment package and how the code base changed. If you use a Visual Studio .NET deployment package it replaces the contents of the old installer with the updated version.

If you use InstallShield you have minor, major and patch upgrades -- and this is up to the author. I personally use "major" upgrades with InstallShield making the installation package basically reinstall everything. If you have a software suite the size of Microsft Office then patch updates are more valuable since a reinstall of the entire software set would require large downloads and a very long reinstall period. It all depends on how you want to use it, how big the software is, and what kind of user experience you can tolerate or desire.

Very good …

zachattack05 70 Posting Pro in Training

As I am working on my first application the thought occured to me:

1) Are "plug-ins" a common thing for applications to support? As in..."copy this .dll (or whatever) to this folder and bam! you get more features!"

2) How do most people handle updates? Replace the entire executable or "patch" the file?

zachattack05 70 Posting Pro in Training

Wow I just realized that my original question was answered like 300 posts ago.

I'm going to mark this one solved :)

Thanks a ton for everyone's help!

zachattack05 70 Posting Pro in Training

I think I may have my problem corrected, but it occured to me that this might be a bigger problem than I originally thought.

I am working on an application that is going to use a .sdf database file to store data. I noticed that while I was at work today blasting away at setting the database up everything was fine. Saved the project, took it home and started working on it here...problem...my Workstation at work is Vista Ultimate 32 Bit...my computer at home is Vista Home Premium 64 Bit...SQL Server Compact Edition doesn't work anymore :(

I found a work around...and it might work...I hope...

But here is the question...since this application is going to rely on SQLSCE (which is made by MS)...when I distribute my application, obviously a copy of SQLSCE will need to be distributed with it...32 bit apps run on 32 and 64 bit systems (generally speaking), but 64 bit apps don't run on 32 bit systems...right?

How can I find out if my user is running a 32 or 64 bit OS, so that they can install the correct version of SQLSCE?

BTW...the error I get is:

Unable to load DLL 'sqlceme35.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Lame.

Everything was working fine at the office, but I guess the 32 bit version of SQLSCE is distributed with Visual Studio...I didn't know that.

Is this going to be a major problem …

zachattack05 70 Posting Pro in Training

I have to ask, though--why do you need to escape the slash in the first place? You only have to escape them when you're writing string literals in code. If you're getting typed input from the user, HostAddress.Text will be the correct path string, and doubling them up will confuse the standard IO classes.

You know what? Your right.... I don't even need to escape them! I was working on using it in a connection string and for some reason I had it stuck in my head that I had to escape them...nevermind :)

Thanks!

zachattack05 70 Posting Pro in Training

I was wondering if someone could give me a quick hand with this. I have a text box that a user types a directory location in. Obviously the directory path includes at least one "\" character and could contain many more.

Because the slash is the escape character and I want to use the path later on in the code, I need to replace the single "\" with "\\"

Here's what I did, and what the Immediate window reports:

string host = this.HostAddress.Text.Replace(@"\", @"\\");

Immediate reports host as:
"C:\\\\Program Files (x86)"
When it should report it as:
"C:\\Program Files (x86)"
the original text was:
"C:\Program Files (x86)"

Any thoughts?

zachattack05 70 Posting Pro in Training

The data would only be somewhat harder to access in a SQL database than in an access database if you can get access to the file.

That's one of the benefits of a true SQL Server, your application talks to the SQL Sever application and you don't have to have access to the data file. The computer with the data file could be physically secured and wouldn't have to share the file for others.

If you can't secure the file, (and maybe even if you can,) you're going to have to secure the data, probably using a form of encryption. If this is the route you take, you will have to put extra effort into securing the encryption (decryption) keys. (I don't recall if SQL Server has any direct support for ecrypted fields.)

Secondarily, the data you want to secure would appear to be readily available to the user at the terminal. Should the data be secured there as well? Is the data your trying to secure being printed on any forms? (Say insurance claims or something?)

I think some of the data you have may be protected by HIPAA and I'm not familiar with the standards. If you're writing the program, you should probably be familiar with the requirements and make sure that you're supporting them as well.

Yes, HIPAA is an obvious concern and I am looking into that as well. However I don't know if HIPAA really covers how the data is stored or encrypted electronically, it's …

zachattack05 70 Posting Pro in Training

.mdf is just a file extension, in a database context, it is usually associated with SQL Server. The file doesn't have any intrinsic support for anything. It's the database libraries that handle the file.

You stated that Access has 'lousy security' which I won't argue, but what level of security do you really need?

The level of security relates to how critical the information is and what you need to protect it from. Do you need to secure the data against reading? Against modification? Something else?

What is the impact (cost?) if the data is not secured?

What value is there to a third party to access the data?

The greater the impact (and/or the greater the value) the more that you will need to do to secure the data. If the impact and value are low, then you don't have to try very hard.

The Access Application that I have written is used in a clinical setting. Right now it is not distributed/sold (whatever) because of security. The system has multiple functions, most of which don't need much security, however, the system also holds social security numbers, names associated with them as well as some medical record information.

It would be useless to me if I got a hold of that kind of information (I wouldn't know what to do with it even if I wanted to do something), but as you probably know...that kind of information is gold to some people.

Obviously it would be better …

zachattack05 70 Posting Pro in Training

It would be possible to share the file across a network. However whether or not multiple people can use your application to access it at one time would depend on the file locking performed either by your code, or the library you use.

If your application or library supports file locking, it can either support whole-file locking or locking for part of the file. How your application / library handle the failures (due to someone else having a lock) would determine what if any error messages the user might see.

The obvious concern would be data integrity. Limiting the number of users that can access the file at once would probably be a good idea...but the question would be, if userA is working on Record1 and userB is working on Record1, and no file locking is performed at all so that all users can read/write at once...the problem becomes, if userA saves changes...unless there is some sort of looping done to check for changes to the records while it is open chances are people are going to get frustrated saving over each other's changes.

Is there a way to lock certain records? Maybe create a field in the database called locked that is either true or false or something? and when the record is open, set it to true, and when it's closed set it to false? That doesn't seem like a good idea because if the application doesn't close cleanly it might leave a record locked. Right?

zachattack05 70 Posting Pro in Training

If you're wanting to support multiple users across a network, you're probably going to want more of a real database, whether your users have to install it manually or not.

Would it be possible to have one computer host the mdf file and have other network clients access it? Or will a "file in use" error occur if more than one person tries to use the mdf file at once?

zachattack05 70 Posting Pro in Training

If you include a SQL database, even a .mdf file, then the user will need an instance of the SQL Server Service installed.
However, i havent done it myself, but i believe there is a SQL Server Compact Edition which you can use to embed the SQL functionality in your application, removing the requirement for the user to install an y version of SQL Server: http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx

What about accessing data across multiple users? Like over a network? Is the .mdf file accessable to anyone?

zachattack05 70 Posting Pro in Training

If you're programming as a hobby, or programming to learn something (and yes, I do both), then you can afford the luxury of the perfect answer. If you're programming for pay (which I also do), then the answer that will serve is seldom ever the perfect one - it's usually the one that will be good enough for now that you know how to implement right now.

Right now this is a hobby. I program VBA and get paid for it, but I don't have deadlines. The solution is finished, I am just working on updates and feature additions now.

But VBA is very limited, and requires another application to run. Solutions are hard, if even possible, to distribute and are sometimes version based.

C# on the other hand allows for a single solution to be written and deployed based on the targeted environment (or so it seems). This is very appealing to me.

The solutions that I work on now are very data driven. Most of the VBA I have written has been in MS Access. I would eventually like to convert my "pride and joy" of a VBA application to a C# project so that everyone's experience is the same. Right now it works, but end-users like to "tinker" with settings in the main Access program...some more than others. This sometimes is a problem. Having a compiled executable program that is stand-alone would be very appealing to me...but that seems like it might be way …

zachattack05 70 Posting Pro in Training

There is no web-site. I wrote that, and that's all there is to it - for now. My other activities keep me tied up most of the time, but when I can find a moment, I like to toss in my two cents.

Most of what I know is synthesized from years of reading and experience, so I can't really even point you at a specific book that would be good to read. I can tell you this, though. C# is a manifestation of a style that is common to C, C++, Java, Javascript, and other languages. If you understand C#, example code in C++ or Java will be clear enough to understand, and those are both object-oriented languages, so if you're looking for books or web-sites, don't get tunnel-vision. The truth does not depend on where you find it.

Good point! Thanks!

I'm starting to pick up on it quickly I think. I appreciate your help :)

zachattack05 70 Posting Pro in Training

Very helpful! At least to me! Thanks! Did you write that or is that from a website? Where can I read the rest of it?

zachattack05 70 Posting Pro in Training

As a general answer to your question I would say no. You can serialize an array or use a generic List<string> and serialize that, then access the strings by index. If you're wanting to do reporting and share information then a database might be a better bet.

However if you're just wanting to save the contents of a listview that has N items in it (unknown number of strings) to restore the application state after a user closes the program then serialization would be a perfect fit.

Thanks a ton for the quick reply! I'll play around a bit with it. My "test" application (what I'm playing with) is slowly turning into a journaling type solution. I don't know how or why, but it's turning out that way.

So, if this were to become a journaling type of software where a journal file is made for each user, and all journal entries are stored in a single file for each user...would that work with serialization? or would a database be better for that?

My concern with a database application would be that a user would need to install additional software wouldn't they? (the db server?)

zachattack05 70 Posting Pro in Training
[Serializable]
    public class Args
    {
        //Class to hold the data - marked as Serializable
        public string a = string.Empty;
        public string b = string.Empty;
        public string c = string.Empty;

        public Args()
...

Quick question...what if the number of strings is unknown, or is dynamic? Or in a situation like that would it be better to use a database?

zachattack05 70 Posting Pro in Training

I think I may have succeeded...and I really am starting to get this through my head. I never realized how structured and strict C# was...VBA is lazy...

Anyway, could you review my code and see if it is sloppy or marked-up incorrectly in some way? I would really appreciate it!

frmMain

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;
using System.Runtime.Serialization.Formatters.Binary;

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

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEditor currentEditor = this.ActiveMdiChild as frmEditor;
            if (currentEditor != null)
                currentEditor.saveme();
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEditor Editor = new frmEditor();
            Editor.Show();
            Editor.MdiParent = this;
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                frmEditor Editor = new frmEditor();
                Editor.Show();
                Editor.MdiParent = this;
                frmEditor actEditor = this.ActiveMdiChild as frmEditor;
                FileStream fs = new FileStream("Test.bin", FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                actEditor.editortext.Text = (String)bf.Deserialize(fs);
            }
            catch (FileNotFoundException fnfe)
            {
                MessageBox.Show(fnfe.Message);
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message);
            }
        }
    }
}

frmEditor

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;
using System.Runtime.Serialization.Formatters.Binary;

namespace WindowsFormsApplication1
{
    [Serializable]
    public partial class frmEditor : Form
    {
        public frmEditor()
        {
            InitializeComponent();
        }
        public void saveme()
        {
            FileStream fs = new FileStream("Test.bin", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, this.editortext.Text);
            fs.Close();
        }
    }
}

Right now I can have multiple instances of the editor, but when …

sknake commented: Indeed C# is structured and strict to make programs clear and concise +6
zachattack05 70 Posting Pro in Training

Here is another quick example of serialising a few text fields - three in this case - I just created a standard from with three text boxes and a save button, this is the code behind the form.

A simple example of serialising - hope it helps

[Serializable]
    public class Args
    {
        //Class to hold the data - marked as Serializable
        public string a = string.Empty;
        public string b = string.Empty;
        public string c = string.Empty;

        public Args()
        {
        }
    }

//Save clicked
        private void btSave_Click(object sender, EventArgs e)
        {
            
            Args args = new Args();
            args.a = txt1.Text;
            args.b = txt2.Text;
            args.c = txt3.Text;

            try
            {
                FileStream fs = new FileStream(@"C:\Test.bin", FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, args);
                fs.Close();
            }
            catch (FileNotFoundException fnfe)
            {
                MessageBox.Show(fnfe.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

 //This method is called once the form is open
        public void LoadData()
        {
            try
            {
                FileStream fs = new FileStream(@"C:\Test.bin", FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                Args args = (Args)bf.Deserialize(fs);
                txt1.Text = args.a;
                txt2.Text = args.b;
                txt3.Text = args.c;
                fs.Close();
            }
            catch (FileNotFoundException fnfe)
            {
                MessageBox.Show(fnfe.Message);
                
            }
            catch (Exception e)
            {
                MessageBox.Show(ex.Message);
            }
        }

Wonderful! Let me see if I can stumble through it and see if I can get something to work.

Thanks!

zachattack05 70 Posting Pro in Training

My original thought was that you would track the current editor as a frmEditor in your code. Upon further thought and contemplation (see reading the manual) I have revised my opinion.

We can use this.ActiveMdiChild but it is of type Form and not the class we want (frmEditor). We need to 'cast' it to our type so we can call our method (as our method is not defined in the Form class).

We can use the c# 'as' to make the conversion for us, without throwing an exception if the cast fails. (If the cast fails, as returns null.)

frmEditor currentEditor = this.ActiveMdiChild as frmEditor;
if (currentEditor != null)
    currentEditor.method(arguments);

Okay I'm going to give this a try and see what happens. Thank you so much for your help again...you are helping me so much!

zachattack05 70 Posting Pro in Training

Clicking on the menu or toolbar in an MDI parent does not change the MDIChild focus. (Note that it is tracking an MDI focus, the menu or tool bar might have the event focus, but the MDI child focus was not changed.)

You have to have an instance to call a method. If you have 3 editors open, which one would you mean if you say frmEditor.method() ?

The frmEditor currentEditor = this.activeEditor; makes a copy of a reference that the class was maintaining. It ensures that the reference is of the type we expect and will generate a compile error if the type of this.activeEditor cannot be converted to frmEditor.

Now that we have a particular instance of the form, we can call currentEditor.method() the compiler knows the type that currentEditor is and calls the appropriate method based on that type. (In this case, it will call frmEditor.method() with 'this' initialized to the object referred to by currentEditor.)

Wait...should it be this.activeEditor or should it be this.ActiveMdiChild ?

doesn't activeEditor need to be defined first? like ... activeEditor = this.ActiveMdiChild ... see what I'm saying?

zachattack05 70 Posting Pro in Training
// If you setup using a framework and setup your main window to support MDI
// you might be able to use this.ActiveMdiChild
// but it will be of type Form and not frmEditor
frmEditor currentEditor = this.activeEditor.
if (currentEditor != null)
    currentEditor.Method(arguments)

That makes sense I suppose, but if it is a MDI container, and there is an active child window, when the user clicks the menu on the main form, does that make the child window lose focus? If it loses focus would using this.ActiveMdiChild work?

Also...I'm a little lost about why you would call a function in that way, it seems like you are doing it backwards... like...

frmEditor is the location of the method I want to run, so in order to run a method there I need to call the method by making a new object and then assigning that object a value that is never used anywhere? That's what it looks like you are doing. frmEditor currentEditor = this.activeEditor. so what is currentEditor and activeEditor? other than within the if statement where you reference currentEditor.method(), why would you bother doing frmEditor currentEditor = this.activeEditor. ...couldn't you just say frmEditor.method()...it seems to me that it would be the same? Maybe I'm thinking of it wrong?

zachattack05 70 Posting Pro in Training

For a multiple form interface, you will need to keep a list of all of the open forms and keep the list current when forms are closed or opened. You will also need a method to reference the 'current form', the one the user is currently interacting with.

When the user clicks save, you should save the data from the current form. (You might consider adding a 'save all' button that would iterate all of the forms saving each of them.) It also might be beneficial to have a 'dirty' flag that would let you know if the form had any changes to save. You could set the dirty flag any time a change is made to the text field.

Based on your described implementation, I think I would be tempted put the serialization in the child form. The main form would only call a method to tell the child it was time to save and the child would take care of getting it done.

Ok, so...on private void saveToolStripMenuItem_Click(object sender, EventArgs e) (Which is located on frmMain) i need to call a method located on frmEditor right? That method would serialize the form and save it...correct?

How do you call methods? Is it simply MyClass.Method(arguments); ? or would it be something like frmEditor.MyClass.Method(arguments); I'm assuming that when the menu option is clicked and the call is made to the child form that the serialization process would serialize the textbox and when that file is opened by deserializing, the …

zachattack05 70 Posting Pro in Training

I will try and help there are some quite fundamental points that you cover.

In object oriented programming a class defines an instance of an object e.g.
A class 'Car' may define this: A car is a vehicle that has four wheels an engine and a steering wheel, it can move forwads and backwards, you can steer it from side to side and it can be stopped. An instance of this class 'Car' would be my car parked on the driveway, my wifes car or any car I have ever seen apart from Del Boys Robin Reliant as that has three wheels.

When you create an instance of (instantiate) an object, that object is put in memory and any public elements can be accessed through it, any private elements cannot. Whether or not a variable is kept in memory depends on the scope of the variable. When I say scope of a variable I am refering to when it is declared, like in VBA when a variable is declared inside a method you can only access it within that method. If a varialble is declared at the top level of a class it is known as a member variable and is available for the lifetime of an instance, the moment that instance is disposed or goes out of scope it will no longer be possible to reference it.

public class MyClass
{
   public float PublicProperty{ get; set; }

   public string PublicMemberVariable;

   private int _privateMemberVar;

    public MyClass()
    {
          int count …
zachattack05 70 Posting Pro in Training

I didn't download or open your project (FYI)

I believe that your compiler error on line 18 is related to you attempting to set a member variable in a class scope, and because the thing you are setting it to (if it even resolves) is a property of an object instance that you reference through the class name.

I believe there are a couple of 'normal' ways to access data that will be updated in child forms. One way would be to pass a communication structure (that the parent owns or also references) for the child form to update (as appropriate -- usually when the user clicks OK). A second way would be for the parent form to keep the reference to the child form (from when it creates the child form) and use that reference to access the child forms data.

In your project example, I would probably have the parent form keep a reference to the open editor frame.

NOTE: You don't want to make the private string serializeme and initialize it from the child frame. It would only get the initial value. You need to ask the editor frame for the current contents when the save strip tool menu item is selected. When the open strip tool menu item is selected, you need to make the editor frame (if it does not already exist) and then tell it to update its contents from what you read. The current implementation where it sets the value of serializeme would …

zachattack05 70 Posting Pro in Training

If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

Here is a perfect example that I have run into. I need to get the text from a textbox in a form so that when i click the file menu in the parent form and click save it will serialize and write the data to the disk that is in the editor window.

Here is my code...I can't figure this out. :confused:

frmMain (This is the parent window)

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;
using System.Runtime.Serialization.Formatters.Binary;

namespace Binary_Text_Editor
{
    public partial class frmMain : Form
    {
        private String serializeme;

        serializeme = frmEditor.editorbodytext();

        public frmMain()
        {
            InitializeComponent();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            BinaryFormatter binaryFormat = new BinaryFormatter();
            Stream fStream = new FileStream("Data.dat",
            FileMode.Create, FileAccess.Write, FileShare.None);
            binaryFormat.Serialize(fStream, serializeme);
            fStream.Close();
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BinaryFormatter binaryFormat = new BinaryFormatter();   
            Stream fStream = File.OpenRead("Data.dat");
            serializeme = (string)binaryFormat.Deserialize(fStream);

        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmEditor editor = new frmEditor();
            editor.Show();
            editor.MdiParent = this;
        }

        private void quitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmOptions options = new frmOptions();
            options.Show();
            options.MdiParent = this;
        }
    }
}

frmEditor (this is the editor window)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using …
zachattack05 70 Posting Pro in Training

Now we're getting into scope a bit (and its a big topic) but class-level variables only exist once, regardless of the number of instances of the class.

Based on your example, where you want something to persist, it could be a regular member of a class instance and the form could keep that instance around as long as the form was open, it wouldn't have to be a class-level data item. Depending on the data you want to persist, the form could just have the data instead of another class (forms are usually classes too) if that would be more convenient.

class1 and class2 normally don't have any idea that the other class exists unless they need to use the class for something. That is normally a GOOD thing. It encourages and promotes modularity in the code.

If it was necessary, class2 could access the string inside class1 if the string was declared as a public member of the class. Then class2 could reference the string via something like class1::class1string . I would personally however tend to discourage it. If you have an example where you think it might be appropriate, describe it and we'll evaluate whether or not that's a valid application and discuss alternatives.

True, allowing modularity is definitely a good thing now that I think about it a bit more.

I guess the instance I am thinking of (and I might be still thinking on the VBA level) is a situation where saved settings are used.

zachattack05 70 Posting Pro in Training

Yes that would be a valid example.

Another example would be a 'person' class. Each person has attributes: name, address, phone number, birthday, ...

But any two instances of 'person' are different.

Ok, then here is my next question.

Can variables cross classes?

In the example that Ryshad gave, Method3 has no idea that Method2String exists. Does that apply to Classes? Like If I have a public class called class1 and some class strings defined there called class1string and class1string2 can a different class called class2 use the data in class1string?

I guess if I have any variables that need to persist in memory I need to declare them on the class level and keep the form that hosts the class open right?

zachattack05 70 Posting Pro in Training

I apparently wrote this while Ryshad was replying. He covers most of it in a more elegant fashion, but I'll post it anyway.

Local variables work like you mentioned your i did in VBA. If you declare it in a function, it goes out of scope when the function ends and is no longer available.

In C# as long as someone still has a reference to an object (or list or other collection of objects) the objects continue to persist.

If the form references a car, the form can continue to refer to that same car as long as the form exists. (Even if the user is not interacting with the form at the time.)

Regarding your form and button question, as long as the two components reference i in the same way relative to the form, they would be working with the same value.

Yes, the process of extracting data from an object in memory and writing it to an output (sometimes a file, but could be something else) is what serialization is.

The "objects can hold multiple values" is somewhat incorrect. I think what you're confused with is that there may be more than one instance of an object.

If Car is a class, then Car myCar = new Car(); declares an instance of a car that I called "myCar". I could then additionally declare Car yourCar = new Car(); . Than made 2 different, but similar 'cars'. Each car has its own data. There can be several …

zachattack05 70 Posting Pro in Training

Sorry if this has been confusing, it's hard to know the best way to explain it without knowing what concepts you are already comfortable with. If you are happy learning on your own i would suggest you read up around Classes and Objects, Access Modifiers, Fields Methods and Members, Value/Reference types and Static members.

Its a long list but a lot of it is related and you will need a firm grasp on those subjects if your to be a confident coder :)
The msd pages are often a good place to start.

No actually, that wasn't confusing at all really. That was very helpful! I'm starting to get the general idea. I'll go to the library today and see what I can find. Do you recommend any particular books? I was just going to check out whatever I could find...programming books, even in the big libraries in St. Louis, are hard to find...at least any that are up to date.

zachattack05 70 Posting Pro in Training

I'm heading away for the weekend so i'll probably not be on until Tuesday. I'll check in if i can, but i'm sure the other solvers can help if you have more questions.
Lists are a very powerful tool once you get the hang of them so its worth reading up. What i gave you was just a few of the ways you can use them. The Sort and Find methods are the trickier ones to understand as they involve predicates and delegates which take some getting used to :)

Good luck

That's okay! I'm pretty independent when it comes to learning stuff, but I need a base and you have definitely helped get that going. I'm going to the library tonight to get a book on C#...hopefully I can find one.

I do have an additional follow up question for clarification.

Because I'm used to VBA, I think I'm having some trouble wrapping my brain around how the basics of C# work...let me ask this and tell me if I am correct in my logic here:

In VBA we have functions and subroutines...when either of them complete, the variables that were in memory are lost (I believe they are set to 0, or "nothing") So if I run a function once and i = 2, I cannot reference i anywhere else in a different function or subroutine and expect it to be the same as the i I had before. Obviously there are ways to …

zachattack05 70 Posting Pro in Training

Props!

Thank you for that! I'll read over your explanation properly at my lunch break in a few minutes.

I think I see what is going on though. Thank you so much for taking the time to explain that to me! I'll take a closer look in a few and if I have any other questions I'll let you know. I really do appreciate your help!

zachattack05 70 Posting Pro in Training

You can use a serialiser to write whole objects (including state) to a file. If you write to binary it is not human readable as far as i know. Some things like property names are written, but the rest is usally random symbols. If you are concerned about security you can look into encryption.
If you go down the serialiser route then i'd suggest writing a class to store all of your settings in, implement ISerializable and you can write the whole calss to a binary file. Check out this, it helped me get my head around serializers.

Would you, or someone else be able to help explain what is going on in some of the code? I'm sure the code works, but like I said, I'm not a big cut/paste kinda guy. The tutorial was written well, and I think I understand what is happening, but I have some questions about the syntax. For example, this section of code:

public class ObjectToSerialize
{
   private List<Car> cars;

   public List<Car> Cars
   {
      get { return this.cars; }
      set { this.cars = value; }
   }

   public ObjectToSerialize()
   {
   }
}

what is going on in:

private List<Car> cars

"List<Car> cars" is pretty much my question...I've never seen something like that before. (again I'm a VBA user, so maybe it's not in VBA)...

zachattack05 70 Posting Pro in Training

You can use a serialiser to write whole objects (including state) to a file. If you write to binary it is not human readable as far as i know. Some things like property names are written, but the rest is usally random symbols. If you are concerned about security you can look into encryption.
If you go down the serialiser route then i'd suggest writing a class to store all of your settings in, implement ISerializable and you can write the whole calss to a binary file. Check out this, it helped me get my head around serializers.

Thanks! I've seen that site before but never paid much attention to it. I'll check into it again. Thanks!

zachattack05 70 Posting Pro in Training

I would, except that XML is human readable. Anyone can open a xml file and even with no experience can stumble through it and extract data that they shouldn't have access to. I just don't think XML will work. Maybe I'm wrong? How secure is data stored in XML files?

zachattack05 70 Posting Pro in Training

Hi! I'm new to the site! I've been searching for help on Google for a while and keep getting results that point to this site, so I figured I should jump on.

I'm new to C#. I've been programming in VBA in MS Access for a while now and have a solution that is running effectively where I work. (had to brag about that for a second :) ) But I just started with C# though. VBA is okay, but it is (to me) a little limiting.

I've decided as my first learning tutorial to teach myself how to create a custom file type, store user settings and data in it and then retrieve it later. The first problem I have run into is how to correctly save data and retrieve it.

I have a form that I created thus far, on that form is a menu bar and a text box. I have successfully exported (in binary) the data typed into the box, and then successfully retrieved it. My question is...what if I have two text boxes? What about 30?

I'd love to get some help and some suggestions on this. Code is nice if you feel up to it, but remember VB is my only real experience so comment any code up so I know what's going on...I'm not big on "ohhh! code! [copy/paste]" I like to know what every line does and why. I'll probably be learning C# for years because of that …

ddanbe commented: Nice question! +5