tags:

views:

227

answers:

3

Is it possible to write a control which can create/ modify a code file in the same project - (Along the lines of the how the form designer works). I can't see the actual creating / modification of files being troublesome - however I would like to avoid the 'xyz file has been modified - would you like to reload it?' dialogue.

To be honest I'm not expecting that I can without writing a plug in or something of the like.

+1  A: 

Absolutley, take a look at the CodeDom: -

http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx

Alternatively look into creating a Visual Studio Add-in: -

http://www.c-sharpcorner.com/UploadFile/mgold/AddIns11292005015631AM/AddIns.aspx

Cheers,

Phil.

Plip
A: 

This is indeed possible to do. After referencing EnvDTE

using EnvDTE;


    var host = this.Container as IDesignerHost;
    var dte = host.GetService(typeof(DTE)) as DTE;
    var activeDoc = dte.ActiveDocument;
    var project = activeDoc.ProjectItem.Collection.Parent as Project;
    project.ProjectItems.AddFromFile("\\Test.cs");
Courtney de Lautour
A: 

Hi,

As Plip stated, use CodeDom and more specifically - CodeDocSerialier. Here`s a short example:

[Serializer(typeof(MySerializer))]
class MyControl : Control {}

class MySerializer : CodeDomSerializer
{
    public override object Serialize(IDesignerSerializationManager manager, object value)
    {
      CodeDomSerializer baseSerializer;
      CodeStatementCollection statements;
      CodeExpression targetObject;

      if(manager == null || value == null)
      {
        return null;
      }

      baseSerializer = (CodeDomSerializer)manager.GetSerializer(typeof(MyControl).BaseType, typeof(CodeDomSerializer));
      statements = baseSerializer.Serialize(manager, value) as CodeStatementCollection;
      if(statements == null)
      {
        statements = new CodeStatementCollection();
      }

      targetObject = GetExpression(manager, value);
      if(targetObject != null)
      {
        // add 'myControl.Visible = true;' statement.
        statements.Add(
          new CodeAssignStatement(
            new CodeFieldReferenceExpression(targetObject, "Visible"),
            new CodePrimitiveExpression(true)));
      }
      return statements;
    }
}
Lovely answer, but what's with the spam at the end?
Jeremy McGee
It`s not a spam! It`s my footer on many developerssites (including very respective) and none of them do not treat it as spam as it is not intrusive and offense. I do not force you to read the text after the delimiter line.
ARM, you aren't doing yourself any favors.
Will