Need help to XMLSerialize Object Content - c#

I am using XMLSerialization to pass data from a client based Win7 application to our server (Server 2008 R2) via a Pipe communication process. I have been brought into this project to finish the previous developer's efforts who abandoned it ... therefore I am presently trying to fix the C# code in VS2010 that doesn't work.
The problem is that I cannot obtain full serialization of the resulting output from the following method which is in "public partial class Test". We have a table defined in the MS Compact Server database (named "Test") which matches each item below and has a FK to the "Channel" table, based on matching TestID's in both tables. EntityCollection is based on its relationship to the "Channel" table:
public Test(Guid TestID, String TestName, String TestRemarks, String ScriptPath,
EntityCollection<Channel> TChannels)
{
ID = TestID;
Name = TestName;
Remarks = TestRemarks;
Path = ScriptPath;
Channels = TChannels;
}
Here is a sample of how it is used in the execution of the method:
Test T = new Test(NewID, "Test1", "Test_120912-1729",
"C:\\Temp\\TestScript_16.txt", TChannels);
Here is the result of the serialization process:
<DataCore xsi:type="Test">
<ID>bc6a8ef7-c31f-404d-8108-86219d45be63</ID>
<Name>Test1</Name>
<Remarks>Test_120912-1729</Remarks>
<Path>C:\Temp\TestScript_16.txt</Path>
</DataCore>
The first four parameters serialize fine, but the last one (the EntityCollection) is failing to do so. However, if I try to serialize "TChannels" by itself (outside the "Test" function) the serialization of each Test Channel works perfectly. I don't fully understand the limitations/requirements for utilizing XMLserialization to solve this problem. Why am I unable to serialize the EntityCollection< > from within the function?
Thanks for your assistance!

I finally found a solution to the above problem. While the many suggestions were appreciated, none of them provided a solution to my inability to XmlSerialize a child EntityCollection. I dug deeper and looked into the ADO.NET Framework and found within the auto generated code in my database Model.Designer.cs file, an [XmlIgnoreAttribute()] near the beginning of Navigation Properties in my Test (EdmEntityTypeAttribute).
I simply removed the [XmlIgnoreAttribute()] line completely and now all the child objects of "Channels" from the EntityCollection<> are Serialized properly. I hope this can help others who are also unable to Serialize child objects.
Thanks #Dave R.

Related

SalesForce - Get all the fields of an object using .Net SDK or Api

We have our system from where we want to push the records (e.g. Contact, Account, Opportunity, etc.) to SalesForce.
To achieve this, we have used ForceToolKit for .Net. We are able to insert\update the records successfully using the ForceToolKit functions.
Example:
dynamic contact = new ExpandoObject();
contact.FirstName = "FirstName";
contact.LastName = "Last";
contact.Email = "test#test.com";
contact.MobilePhone = "1234567890";
var successResponse = await forceClient.CreateAsync("Contact", contactList);
The Issue we are facing is as mentioned below.
In our source system, we have few custom fields which are not standard field in SalesForce and it can be different for different users.
So, first we have to map the custom fields between our source system and the SalesForce.
We want to fetch all the fields of SalesForce object in order to map the fields.
We are unable to find any function in ForceToolkitForNet.
As described here, we have tried QueryById function by using the dynamic return type, but it is throwing an exception.
var contactFields = await forceClient.QueryByIdAsync<dynamic>("Contact", successResponse.Id);
Exception: "SELECT FROM Contact where Id = '{contactId}' Incorrect syntax near FROM".
What are the ways to get the fields of any object of SalesForce.
Can anyone help us on getting the fields of an object using SalesForceToolkit or SalesForceApi?
SOQL doesn't have a SELECT * FROM Account concept, you need to learn the fields beforehand. You have few options here.
You can use "describe" calls. I've recently answered similar question but it was about REST API: https://stackoverflow.com/a/48436870/313628, I think your solution is SOAP-based.
If you'd be doing this by hand...
Start here: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_list_describe.htm
List of all objects visible to your user: describeGlobal()
Get details (incl field names) for one object: describeSobject() or more: describeSobjects()
As you're using the toolkit - there's a chance these methods already are in there somewhere. Experiment a bit. Between the C# examples under the links I gave you and the library you should be able to figure something out.
I mean I'm naive but just searching the repo for "describe" looks promising: https://github.com/developerforce/Force.com-Toolkit-for-NET/search?utf8=%E2%9C%93&q=describe&type=, maybe this example
There's also a way to not learn this info at runtime but consume a WSDL file generated out of Salesforce with all fields & generate C# code out of it. The downside is that you'd need to regenerate it every time you want to support new object/field in your app. Read about "Enterprise WSDL" to get started.
Last but not least - there are more or less friendly tools that dump the Salesforce metadata. i'm a fan of https://www.datasert.com/products/realforce/ but just have a look around. Hell, even exporting some records with DataLoader will give you all field names if that's all you need.

2013 C# connection to PowerPivot DataModel

This article Connecting to PowerPivot with C# is the closest to my question but it seems that it is out of date. I attempted the methods they showed in the answer but the example
ThisWorkbook.Connections["PowerPivot Data"].OLEDBConnection.ADOConnection
Does not return the connection information, rather an exception.
But I was able to access the PP Data Model using:
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1]. ModelTables[1].ModelTableColumns[1].Name`
But the object only allows you to look at the column names in the model. I wasn't able to get the connection information or anything.
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1].ModelConnection.ADOConnection`
causes an exception and so does:
ThisAddIn.Current.Application.ActiveWorkbook.Connections[1].OLEDBConnection.ADOConnection
MY QUESTIONS
Have I made a mistake in my code?
Is there another method to connect to the datamodel that I haven't listed above?
Is it possible to read the records in the datamodel? (I was able to read column names)
Thank you for your time!
string ConnString = "Provider=MSOLAP;Data Source=$Embedded$;
Locale Identifier=1033;Location=" + ThisAddIn.Current.Application.ActiveWorkbook.FullName + ";SQLQueryMode=DataKeys";
Microsoft.AnalysisServices.Server OlapServer = new Microsoft.AnalysisServices.Server();
OlapServer.Connect(ConnString);

RavenDB namespace change on document object throws "Unable to cast object" Error

So I am just trying to get RavenDB up and running and I have struggled with several issues but finally got it working. I was able to successfully insert and pull records for display.
However, I decided to move the class I was using to generate documents from to another spot which cause a namespace change. I ran ran everything and I can still insert documents to Raven. But when I try to pull them for display purposes I get the following error:
Unable to cast object of type 'Library.Logging.RewardProviderLog' to type 'Admin.ViewModels.ImportMonitorViewModel'.
So after going through all of the other posts I could find online it seems that the issue has something to do with the Raven-Clr-Type that essentially tracks the namespace information of the object you are saving as a document.
Ok. So I went in and deleted all the documents I created since I am still just testing and trying to get things running. I even went ahead and blew away the index and recreated it. I ran my process of inserting a new log. But I still get the same error message when I try to pull them and display them.
Note: ViewModels.ImportMonitorViewModel and Library.Logging.RewardProviderLog are identical. They contain the exact same properties.
Update
Index (named ImportMonitorLogs):
from doc in docs.RewardProviderLogs
select new {doc.status, doc.newItemsCount, doc.additionalInfo, doc.lastRun};
Query:
DocumentStore RavenDBStore = new Raven.Client.Document.DocumentStore { Url = "myurl" };
RavenDBStore.DefaultDatabase = "yei-logs";
RavenDBStore.Initialize();Raven.Client.Indexes.IndexCreation.CreateIndexes(System.Reflection.Assembly.GetCallingAssembly(), RavenDBStore);
using(var session = RavenDBStore.OpenSession())
{
model = (from log in session.Query<ViewModels.ImportMonitorViewModel>("ImportMonitorLogs")
orderby log.lastRun descending
select log).ToList();
}
Putting aside the rename and what might have worked before, the error matches the query you are attempting. You are indexing documents of type RewardProviderLog, and retrieving them directly as type ImportMonitorViewModel.
You say all of the properties are the same in both classes, but that alone won't get RavenDB to duck-type them for you. You have to be a little more explicit. This will probably work:
model = (from log in session.Query<RewardProviderLog>("ImportMonitorLogs")
orderby log.lastRun descending
select log).As<ViewModels.ImportMonitorViewModel>().ToList();
Or if you want slightly cleaner syntax (IMHO), this is equivalent:
model = session.Query<RewardProviderLog>("ImportMonitorLogs")
.OrderByDescending(x=> x.lastRun)
.As<ViewModels.ImportMonitorViewModel>()
.ToList();
The key here is that you are querying based on the type that matches the entity your index is returning, and that you use the As method to duck-type it into your view model. (This is the same thing as OfType<T>, and you can read more in the docs here).
If you want to get a bit fancier and project different fields or project from the index directly, you can look at AsProjection in the docs here.
If you're still scratching your head as to why this worked before, I can see that it might have worked if your viewmodel an entity were named the same thing - even if they were from different namespaces. They would still have the same Raven-Entity-Name metadata value.

Using Linq with SQLite: Table recognized but "Results View" gives error

I'm trying to work with SQLITE in .
However I've faced a weird problem :
// Start of code
connection = new SQLiteConnection(myConnectionString);
connection.Open();
myDataContext = new Main(connection, new SqliteVendor());
// End of code
Examing 'myDataContext' after execution (with debugger), I see it has the type 'Main' (as should be :)) and also has as members,
the names of the tables I've defind in DB (so far - so good...), but...
Trying open one table (which has(!) records), and then trying to open the "ResultView" member of that table, I'm facing the string
"SQLite error\n No such table: main:XXXX"
(XXXX is the table name...)
(I've came to examine the structure because when I've tried to fetch records by linq command - I've got an exception.)
Do you have any idea what can cause this behavior?
Thanks,
Rivka
Ok, I've found the source of it...
(actually found it several hours after I've published the question...)
I'm working with visual studio and my DB file name is part of the project.
Since I've changed the (name and content...) of th db filename, i've forgot to mark
it "Copy Always"... That has caused the problem.
Please mark that as solved...

Programmatically managing Microsoft Access Attachment-typed field with .NET

Access added a new data type in the 2007 version--the Attachment type. We are currently working on a WinForms application with .NET 3.5 (C#) that uses an Access 2007 database. We want to be able to add new attachments through the WinForms interface. I can't seem to locate any information on how to insert or select attachment data with .NET. I did try using DAO (version 12) but it didn't seem to have the SaveToFile or LoadFromFile methods discussed here: http://msdn.microsoft.com/en-us/library/bb258184.aspx
So, how can I get at the attachments with .NET?
I finally got this working in C# using a reference to Microsoft.Office.Interop.Access.Dao.
DBEngine dbe = new DBEngine();
Database db = dbe.OpenDatabase("C:\\SomeDatabase.accdb", false, false, "");
Recordset rs = db.OpenRecordset("SELECT * FROM TableWithAttachmentField", RecordsetTypeEnum.dbOpenDynaset, 0, LockTypeEnum.dbOptimistic);
rs.MoveFirst();
rs.Edit();
Recordset2 rs2 = (Recordset2)rs.Fields["AttachmentFieldName"].Value;
rs2.AddNew();
Field2 f2 = (Field2)rs2.Fields["FileData"];
f2.LoadFromFile("C:\\test.docx");
rs2._30_Update();
rs2.Close();
rs._30_Update();
rs.Close();
This will add test.docx to the Attachment field "AttachmentFieldName" in table "TableWithAttachmentField". One thing to note is that attempting to add the same file twice will throw an error.
Interesting question. I don't use A2007, but have the runtime installed, so I used the Access object browser to see what's in there. I discovered something really odd -- there are two FIELD objects, Field and Field2. The attachment functions are members of Field2 but not Field. So, my suggestion would be that perhaps what you need to do is convert this:
Recordset.Fields("FileData").LoadFromFile(<filename>)
to something like this:
Dim rs As DAO.Recordset
Dim fld2 As DAO.Field2
Set rs = CurrentDb.OpenRecordset("[SQL]")
Set fld2 = Recordset.Fields("FileData")
fld2.LoadFromFile(<filename>)
rs.Close
Set fld2=Nothing
Now, I don't know if that will correct the problem for you, but it seems to me that given the two Field objects with different properties/methods/members, you need to be explicit about which Field object you're using. The code example you cite is specifically for use in Access and maybe Access does something to automatically resolve the differences between the two object (perhaps it uses the Field object by default for non-ACCDB databases and the Field2 object for ACCDB files).
Look at this write up on the Access team blog It has basically what David is suggesting with a bit of a twist. It sets a Recordset2 type object equal to the value of the attachment field. Then appends a record to that recordset a puts the file contents in that new record.
I've been struggling to try and do this same thing. There is a reference you can include in your project to "Microsoft.Office.Interop.Access.Dao" that will get you the Recordset2 and Field2 Interfaces, but no implementation classes.
That's about as far as I've gotten, I'll post more once/if I figure it out...
I was not able to get this working in C#, so I moved on to a different solution. I would love to know how to do this though if someone figures it out.

Categories