When to use Xml Serialization - excel

Which series of XML namespaces will You use to serialize an object to XML using WCF?
For example, I have 4 types of Users (left to right) and they have data and references to members in my Users table. This way I could 1/2 have to remove functions and 2 methods because I do not have add/delete methods.
So to end up with code like
public void Save() {
microsoft.Office.Interop.Excel.Application, System.Application.Current.People, System.Runtime.Interop.Microsoft.Office.Interop.Outlook.Application,
Microsoft.Office.Interop.Outlook.Application,
Microsoft.Office.Interop.Excel.Application,
Microsoft.Office.Interop.Excel.Application,
Microsoft.Office.Interop.Outlook.
Microsoft.Office.Interop.Outlook,
Microsoft.Office.Interop.Contact,
Microsoft.Office.Interop.Outlook.
//General methods
}
It makes sense to me for someone to add the notes this method requires but that would allow me to have 2 methods.
Save a new class and create the form to save the new class
Write at least one file, Save or Open for reading?
Add a button about saving the file but then the form with some properties that the functionality should be saved to?
Is this the same? Or is there a better way?
Thanks!

Related

Revit API reopen form an keep data

I would like to make a Plugin where the user can select a source and then a target element and get all the parameters and their values.
My problem is: After I selected the source element and got all parameters and values into comboboxes I select the target (via another button). For that the form closes again and after selecting and reopening all the data from the source element is gone.
What would be a correct way to do this?
At this time both buttons close the form run another ExternalEvent to select the element and collect the data.
Can I cache this data (Lists, dictionary with list, dictionary with dictionary with list) or do I have to write it to a file or is there another way?
How do I keep/remember the data I collected when a form closes an reopens?
Thank you for any help
Philipp
There multiple ways of doing this I guess. It is more of a general programming rather than API issue. You basically need to keep the data in memory outside of just the WPF window.
Some options of the top of my head would be
Save the data into file in temp folder and read it when needed (probably a messy solution)
Create & instantiate a class with data to keep in memory and communicate it between different windows etc.
Have a Static Class with appropriate property. Once selecting an element assign it to the property. This should persist within the Revit session. Static Class.
Option 3 should be the easiest to use.
Just use Properties -> Application settings to store the ID of the entity. Then on launch get the combo boxes to auto populate if the ID can be found.
External events are only required when editing the model.
This is assuming your using Visual studio and not sharp develop. If your still using sharp develop it is time to move on to a real IDE.
I think there are a few options. You could use the built in DataStorage that a revit model provides. Here, i made a datastorage entity to store a GUID for a project...
public Guid schemaGuid = new Guid("{5F374308-9C59-42AE-ACC3-A77EF45EC146}");
public DataStorage dataStorage;
public string schemaName = "UniqueProjectId";
public DataStorage dataStorage;
public string SimpleField = "MyProjects_GUID";
public Schema CreateNewDataStorage()
{
Guid newProjectGuid = Guid.NewGuid();
Transaction t = new Transaction(doc, "Make internal storage");
t.Start();
dataStorage = DataStorage.Create(doc);
dataStorage.Name = schemaName;
SchemaBuilder schemaBuilder = new SchemaBuilder(schemaGuid);
schemaBuilder.SetSchemaName(schemaName);
schemaBuilder.AddSimpleField(SimpleField, typeof(Guid));
schema = schemaBuilder.Finish();
entity = new Entity(schema);
entity.Set(SimpleField, newProjectGuid);
dataStorage.SetEntity(entity);
t.Commit();
return schema;
}
Another way would be to write to external database or text file. For something small, SQlite is easy. A temporary text file is also a very simple way to temporarily store data.
Lastly, you could use an Idling event and keep the dialogue box active.

MFC: is it possible to to have view with multiple documents?

Is it possible to associate a view with different documents (not simultaneously of course)?
What I want to achieve: the application can have multiple documents of the same type, that can be added during runtime, and set of suitable views, the main of which is CFormview-based. The user can choose the number of the document to show per combobox in the toolbar. The views then associate themselves with this document and update with data from it.
Is it possible to achieve with CMultiDocTemplate?
If yes, how? especially is it possible to retrieve a document by it order number?
If not I'll probably have to abstain from using the templates altogether, which of course means more coding (and more questions to friendly community), but it will do what I want it to do and not Microsoft thought I should be doing
Yes, you could but not out of the 'box'. Instead I'd recommend a different strategy. Rather than trying to attach a View to an existing CDocument derived class LOAD the Views CDocument with the information you want. That could done by adding a simple Copy method to the CDocument or you could move your actual data into a separate class then just point the CDocument to 'data' you want.
Trying to change the CDocument instance for a CView is going against the MFC grain which normally means lot of ASSERTS.

Preventing StackOverflowException while serializing Entity Framework object graph into Json

I want to serialize an Entity Framework Self-Tracking Entities full object graph (parent + children in one to many relationships) into Json.
For serializing I use ServiceStack.JsonSerializer.
This is how my database looks like (for simplicity, I dropped all irrelevant fields):
I fetch a full profile graph in this way:
public Profile GetUserProfile(Guid userID)
{
using (var db = new AcmeEntities())
{
return db.Profiles.Include("ProfileImages").Single(p => p.UserId == userId);
}
}
The problem is that attempting to serialize it:
Profile profile = GetUserProfile(userId);
ServiceStack.JsonSerializer.SerializeToString(profile);
produces a StackOverflowException.
I believe that this is because EF provides an infinite model that screws the serializer up. That is, I can techincally call: profile.ProfileImages[0].Profile.ProfileImages[0].Profile ... and so on.
How can I "flatten" my EF object graph or otherwise prevent ServiceStack.JsonSerializer from running into stack overflow situation?
Note: I don't want to project my object into an anonymous type (like these suggestions) because that would introduce a very long and hard-to-maintain fragment of code).
You have conflicting concerns, the EF model is optimized for storing your data model in an RDBMS, and not for serialization - which is what role having separate DTOs would play. Otherwise your clients will be binded to your Database where every change on your data model has the potential to break your existing service clients.
With that said, the right thing to do would be to maintain separate DTOs that you map to which defines the desired shape (aka wireformat) that you want the models to look like from the outside world.
ServiceStack.Common includes built-in mapping functions (i.e. TranslateTo/PopulateFrom) that simplifies mapping entities to DTOs and vice-versa. Here's an example showing this:
https://groups.google.com/d/msg/servicestack/BF-egdVm3M8/0DXLIeDoVJEJ
The alternative is to decorate the fields you want to serialize on your Data Model with [DataContract] / [DataMember] fields. Any properties not attributed with [DataMember] wont be serialized - so you would use this to hide the cyclical references which are causing the StackOverflowException.
For the sake of my fellow StackOverflowers that get into this question, I'll explain what I eventually did:
In the case I described, you have to use the standard .NET serializer (rather than ServiceStack's): System.Web.Script.Serialization.JavaScriptSerializer. The reason is that you can decorate navigation properties you don't want the serializer to handle in a [ScriptIgnore] attribute.
By the way, you can still use ServiceStack.JsonSerializer for deserializing - it's faster than .NET's and you don't have the StackOverflowException issues I asked this question about.
The other problem is how to get the Self-Tracking Entities to decorate relevant navigation properties with [ScriptIgnore].
Explanation: Without [ScriptIgnore], serializing (using .NET Javascript serializer) will also raise an exception, about circular
references (similar to the issue that raises StackOverflowException in
ServiceStack). We need to eliminate the circularity, and this is done
using [ScriptIgnore].
So I edited the .TT file that came with ADO.NET Self-Tracking Entity Generator Template and set it to contain [ScriptIgnore] in relevant places (if someone will want the code diff, write me a comment). Some say that it's a bad practice to edit these "external", not-meant-to-be-edited files, but heck - it solves the problem, and it's the only way that doesn't force me to re-architect my whole application (use POCOs instead of STEs, use DTOs for everything etc.)
#mythz: I don't absolutely agree with your argue about using DTOs - see me comments to your answer. I really appreciate your enormous efforts building ServiceStack (all of the modules!) and making it free to use and open-source. I just encourage you to either respect [ScriptIgnore] attribute in your text serializers or come up with an attribute of yours. Else, even if one actually can use DTOs, they can't add navigation properties from a child object back to a parent one because they'll get a StackOverflowException.
I do mark your answer as "accepted" because after all, it helped me finding my way in this issue.
Be sure to Detach entity from ObjectContext before Serializing it.
I also used Newton JsonSerializer.
JsonConvert.SerializeObject(EntityObject, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Help to restructure my Doc/View more correctly

Edited by OP.
My program is in need of a lot of cleanup and restructuring.
In another post I asked about leaving the MFC DocView framework and going to the WinProc & Message Loop way (what is that called for short?). Well at present I am thinking that I should clean up what I have in Doc View and perhaps later convert to non-MFC it that even makes sense. My Document class currently has almost nothing useful in it.
I think a place to start is the InitInstance() function (posted below).
In this part:
POSITION pos=pDocTemplate->GetFirstDocPosition();
CLCWDoc *pDoc=(CLCWDoc *)pDocTemplate->GetNextDoc(pos);
ASSERT_VALID(pDoc);
POSITION vpos=pDoc->GetFirstViewPosition();
CChildView *pCV=(CChildView *)pDoc->GetNextView(vpos);
This seem strange to me. I only have one doc and one view. I feel like I am going about it backwards with GetNextDoc() and GetNextView(). To try to use a silly analogy; it's like I have a book in my hand but I have to look up in it's index to find out what page the Title of the book is on. I'm tired of feeling embarrassed about my code. I either need correction or reassurance, or both. :)
Also, all the miscellaneous items are in no particular order. I would like to rearrange them into an order that may be more standard, structured or straightforward.
ALL suggestions welcome!
BOOL CLCWApp::InitInstance()
{
InitCommonControls();
if(!AfxOleInit())
return FALSE;
// Initialize the Toolbar dll. (Toolbar code by Nikolay Denisov.)
InitGuiLibDLL(); // NOTE: insert GuiLib.dll into the resource chain
SetRegistryKey(_T("Real Name Removed"));
// Register document templates
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CLCWDoc),
RUNTIME_CLASS(CMainFrame),
RUNTIME_CLASS(CChildView));
AddDocTemplate(pDocTemplate);
// Parse command line for standard shell commands, DDE, file open
CCmdLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
// Dispatch commands specified on the command line
// The window frame appears on the screen in here.
if (!ProcessShellCommand(cmdInfo))
{
AfxMessageBox("Failure processing Command Line");
return FALSE;
}
POSITION pos=pDocTemplate->GetFirstDocPosition();
CLCWDoc *pDoc=(CLCWDoc *)pDocTemplate->GetNextDoc(pos);
ASSERT_VALID(pDoc);
POSITION vpos=pDoc->GetFirstViewPosition();
CChildView *pCV=(CChildView *)pDoc->GetNextView(vpos);
if(!cmdInfo.m_Fn1.IsEmpty() && !cmdInfo.m_Fn2.IsEmpty())
{
pCV->OpenF1(cmdInfo.m_Fn1);
pCV->OpenF2(cmdInfo.m_Fn2);
pCV->DoCompare(); // Sends a paint message when complete
}
// enable file manager drag/drop and DDE Execute open
m_pMainWnd->DragAcceptFiles(TRUE);
m_pMainWnd->ShowWindow(SW_SHOWNORMAL);
m_pMainWnd->UpdateWindow(); // paints the window background
pCV->bDoSize=true; //Prevent a dozen useless size calculations
return TRUE;
}
Thanks
Hard to give you good recommendations without knowing what your program shall do. I have only a few general remarks:
Your InitInstance does not look very messed up for me. It's pretty much standard with a bit of custom code in it.
Also the ugly construction to retrieve the first view from the application class (the chain GetDocTemplate -> GetDoc -> GetView) is standard to my knowledge. I actually don't know another way. You might think about moving it into a separate method like CChildView* CLCWApp::GetFirstView() but well, that's only cosmetic as long as you need it only at one place.
What you are doing and which data you are placing in your Document class and in your View class(es) is more a semantic question if you only have one view. (You have only one document anyway because it's an SDI application.). From a technical viewpoint often both is possible.
But to be open for (perhaps) later extensions to more than one view and to follow the standard pattern of a doc/view architecture there are a few rules of thumb:
Data which exist and have a meaning independent of the way to present and view them (a document file, a database handle, etc.) belong to the document class. I don't know what your pCV->OpenF1(cmdInfo.m_Fn1) ... and so on does but if it's something like a file or filename or a parameter to be used to access data in any way OpenF1 might be better a method of the document class.
Methods which do any kind of data processing or modification of your underlying data belong to the document class as well
Data and methods which are only needed for a specific way to display a document belong to a view class (for instance a selected font, colours, etc.)
On the other side: If you have a fixed number of views which open with the document it might not be wrong to put view specific data into the document, especially if you want to make those view parameters persistent. An example would be a file with some statistical data - your document - and a splitter frame with two views: one displays the data as a grid table and the other as a pie chart. The table has "view data" describing the order of and width of columns, the pie chart has data to configure the colours of the pie pieces and the legend location, for instance. If you want to make sure that the user gets the last view configuration displayed when he opens the document file you have to store these view parameters somewhere. It wouldn't be wrong or bad design in my opinion to store those parameters in the document too, to store and retrieve them from any permanent storage, even if you need them only in the view classes.
If your application allows to open an unlimited number of views for a document dynamically and those views are only temporary as long as the application runs, storing all view configuration parameters directly in the view classes seems more natural to me. Otherwise in the document you would need to manage any kind of dynamic data structure and establish a relationship between a View and an entry in this data structure (an index in an array, or a key in a map, etc.)
If you are in doubt whether to place any data in the document or view class I'd prefer the document because you always have the easy GetDocument() accessor in the View class to retrieve members or call methods of the Doc. To fetch data from the View into the Document requires to iterate through the list of views. (Remember: Doc-View is a 1-n relationship, even in a SDI application.)
Just a few cents.

Adding properties to an existing object retrieved using SubSonic

I think this is more of a polymorphism question but it applies to SubSonic table objects...
Here's the thing (and I love this one):
TblUser userObj = new TblUser(1);
Which fills userObj's properties with all of PK=1's goodies.
Now, I'd like to add more properties to the existing user object, for example, an ArrayList property of say, account numbers.
I've seen questions like this around - "add a property to an existing object...", but in this case, would it be most-recommended to create a user wrapper object, then have a TblUser property type, and my own other additional properties in this?
Ok, so it looks like once-again I have come up with a solution to this, but am still curious about the possibility of adding properties to existing objects.
All the generated SubSonic classes are partials so all you need to do to add extra properties/methods to them is to create your own partial class with the same name in the same namespace and the two will be merged at compile time. For example for your TblUser class:
public partial class TblUser
{
public List<AccountNumber> AccountNumbers
{
get
{
// Get and return the AccountNumbers
}
}
}

Resources