views:

653

answers:

6

Can somebody please help me with a regex (or something else), I'm really struggling to get this done and can't find anything anywhere that helps me to finish it.

I have a program where the user places some controls on a form. and when they click the save button it goes through all controls on the form and saves their details to a text file (which I know how to do)..like so:

Label
"This is text on a label"
20, 97
Tahoma, 7.5, Regular
-778225617

Explanation:

Control Type
Text property of that control
Location of the control
Font properties for that control
ForeColor for that control.

... This text file that gets created when the user saves it may contain information for just a single control, like shown above, or even multiple controls, like so:

Label
"This is text on a label"
20, 97
Tahoma, 7.5, Regular
-778225617
LinkLabel
"This text belongs to the linklabel text property."
Arial, 20, Bold
-119045893

Explanation:

Control
Text Property
Location
Font Properties
ForeColor
Control
Text Property
Location
Font Properties
ForeColor

...etc... I'm finding this to be hard for me, because I'm not an expert, by far. Can somebody please help me? I also need to convert the Font Property line from string into a Font object so it can be assigned to the Font property of the specified control at runtime.

i'd really appreciate any help at all. Thank you so much.

Thanks jay

A: 

would this work for you ?

Font font = new Font("Tahoma",12,FontStyle.Regular);
Andrew Keith
How does that help them parse "Tahoma, Regular, Size" from a text file?
Andrew Hare
read peoples questions before giving bad advice
baeltazor
AS you may see, i answered this question on the 5th of October, 3 days before you editted your question and added more detail. You original question didnt have any detail on your file format.
Andrew Keith
Yes, the original question did have enough details.
lucifer
+4  A: 

You would have do do something like this:

using System;
using System.Drawing;

class Example
{
    static void Main()
    {
     String fontName = "Tahoma, Regular, Size";
     String[] fontNameFields = fontName.Split(',');

     Font font = new Font(fontNameFields[0],
      Single.Parse(fontNameFields[2]),
      (FontStyle)Enum.Parse(typeof(FontStyle), fontNameFields[1]));
    }
}
Andrew Hare
+1 example is more detailed than Andrew.
Ganesh R.
This is of course assuming that "Size" will actually be a floating point number :)
Andrew Hare
hi andrew thanks for your answer :) i am getting an error saying that Index is outside the bounds of the array, when using the above sample. What exactly is it refering to?
baeltazor
That means that you aren't parsing a string that contains two commas. Debug the application and check to see what the string is that contains the font information.
Andrew Hare
+1  A: 

You can read the text from the file and split the string to an array and then use the overloaded constructor for font class to create the new font object.

For a list of font constructors see

Font Constructor

The size parameter is the em-size, in points, of the new font. So for font sizes in other units you have to take care of that.

rahul
+1  A: 

This seems to be a poorly stated problem... I see a few holes in it. (I'm assuming you are talking about WinForms) I'll address those later.

I don't know of any functionality in .NET that will take all of this combined parsing for you. However, you can do formatting adjustments with WinForms with the use of the CSSName attribute [Its an attribute that is close to this] and use a CSS file on your GUI. [A bit weird but it works]

Btw that integer that is negative is an signed integer that represents a color set of: RGB:

255 255 255

Issues:

  1. The data specification for font and formatting seems to suggest that no control can embed another control, this is frequently done with buttons, labels, and panels with WinForms. (XML would be a great suggestion to embed and avoid this issue)
  2. This isn't a standard format. Why not go with RTF. With RTF its seemingly simple and you get a viewer to go with it.
  3. Property definition and value separation. It looks like you are using a property sheet format, don't imply that the properties line up with what you suggest, it becomes error prone to parsing.
monksy
+1  A: 

Why is it that you are not using XmlSerialization. All you would need to do it to create a memory stream, and call its dot Save method; and then you can at any moment reload the data.

For instance you have a class called Canvas.

Go on something like Canvas.AddControls(controlTypes.Label, "This is text on a label", 20, 97, Tahoma, 7.5, Regular, -778225617);

Please see the simplest XmlSerializer sample.

If you do not want your files to be xml typed? Use Binary Serialization. See this.

Something like:

public static void Save(object obj)
{
    using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
    {
        // Serialize an object into the storage referenced by 'stream' object.
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        // Serialize multiple objects into the stream
        formatter.Serialize(stream, obj);

        // If you want to put the stream into Array of byte use below code
        // byte[] buffer = stream.ToArray();
    }
}
KMan
i've never worked with xmlserializer before and i dont know which controls the user will add to the canvas to save, nor do i know what color, size, fontname and/or text they will be assigning to these controls. so i can't just add this info manually.
baeltazor
Please see my following comment.
KMan
A: 

10 min solution:

Ok, following is out of 5 mins 'quick-effort' what I really meant; I hope this would solve the problem.

  • STEP 1: Get a canvas - Canvas object
  • STEP 2: Add Drawings/controls to it
  • STEP 3: Serialize, save, and reload the object

See following.

STEP 1: The canvas class

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace SaveControls
{
    [Serializable()]
    public class CCanvas
    {

        List<CDrawing> _listControls;
    public List<CDrawing> Controls
    {
        get { return _listControls; }
    }

    public CCanvas()
    {
        _listControls = new List<CDrawing>();
    }

    public void AddControls(CDrawing theControls)
    {
        _listControls.Add(theControls);
    }

    public void ReloadControl(Form frm)
    {
        //foreach (CDrawing draw in _listControls) -- requires IEnumerable implementation.
        for (int i = 0; i < _listControls.Count; i++)
        {
            CDrawing d = (CDrawing)_listControls[i];
            d.Draw(frm);
        }
    }


    public void Save()
    {
        try
        {
            using (Stream stream = File.Open("data.bin", FileMode.Create))
            {
                BinaryFormatter bin = new BinaryFormatter();
                bin.Serialize(stream, this);
            }
        }
        catch (IOException)
        {
        }

    }

    public CCanvas Open()
    {
        CCanvas LoadedObj = null;
        using (Stream stream = File.Open("data.bin", FileMode.Open))
        {
            BinaryFormatter bin = new BinaryFormatter();

            LoadedObj = (CCanvas)bin.Deserialize(stream);

        }
        return LoadedObj;
    }
}

}

STEP 2: Add drawings

using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Data;

using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Drawing;

namespace SaveControls
{
    [Serializable()]
    public class CDrawing
    {
        public enum ControlTypes { Label, TextBox, None };

        private ControlTypes _controlType;
    public ControlTypes ControlType
    { get { return _controlType; } }

    private string _strControlText;
    public string Text
    { get { return _strControlText; } }

    private int _xPosition;
    public int X
    { get { return _xPosition; } }

    private int _yPosition;
    public int Y
    { get { return _yPosition; } }


    private string _strFontName;
    public string Font
    { get { return _strFontName; } }

    double _fFontSize;
    public double Size
    { get { return _fFontSize; } }

    string _strStyle;
    public string Style
    { get { return _strStyle; } }

    decimal _dForegroundColor;
    public decimal Color
    { get { return _dForegroundColor; } }

    public CDrawing(ControlTypes controlType, string strControlText, int xPosition, int yPosition,
    string strFontName, double fFontSize, string strStyle, decimal dForegroundColor)
    {
        _controlType = controlType;
        _strControlText = strControlText;
        _xPosition = xPosition;
        _yPosition = yPosition;
        _strFontName = strFontName;
        _fFontSize = fFontSize;
        _strStyle = strStyle;
        _dForegroundColor = dForegroundColor;


    }

    public void Draw(Form frm)
    {
        if (_controlType == ControlTypes.Label)
        {
            Label lbl = new Label();

            lbl.Text = _strControlText;
            lbl.Location = new Point(_xPosition, _yPosition);

            System.Drawing.FontStyle fs = (_strStyle == System.Drawing.FontStyle.Regular.ToString()) ? System.Drawing.FontStyle.Regular : System.Drawing.FontStyle.Bold;

            lbl.Font = new System.Drawing.Font(_strFontName, (float)_fFontSize, fs);
            lbl.ForeColor = SystemColors.Control;// _dForegroundColor;
            lbl.Visible = true;
            frm.Controls.Add(lbl);
        }
    }


}

}

STEP 3: Usage, serialize, save, reload

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


    public void Save()
    {
        //Create a canvas object
        CCanvas Canvas1 = new CCanvas();

        //Add controls
        Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label1", 10, 100, "Tahoma", 7.5, "Regular", -778225617));
        Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label11", 20, 200, "Verdana", 7.5, "Regular", -778225617));
        Canvas1.AddControls(new CDrawing(CDrawing.ControlTypes.Label, "This is text on a label111", 30, 300, "Times New Roman", 7.5, "Regular", -778225617));

        //Save the object
        Canvas1.Save();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Save();

    }

    private void btnLoad_Click(object sender, EventArgs e)
    {
        Load();

    }

    public void Load()
    {
        //Retrieve
        CCanvas Canvas2 = new CCanvas();

        //opens the binary file
        Canvas2 = Canvas2.Open();

        //loads control to this form.
        Canvas2.ReloadControl(this);


    }

}

Let us know about the reason, if you plan to hate this solution. Meanwhile I am trying to look for someplace to upload. Googlecode, but I dont have subversion client installed with me. :0(

KMan
Let me know if you would want a working windows forms solution files.
KMan
oh yeah that would be great if you coud send me the solution files :D
baeltazor
hold on, let me upload it.
KMan
thank you so much Kman
baeltazor
see my updated post! couldnt find a place to upload quick. isnt there a way to upload code files here in
KMan
thank you very much Kman!!! that code worked perfectly! much appreciated!!!!!!!! :D :D :D :D :D
baeltazor
Glad, I was able to help. Happy coding (0:
KMan