I am new to C# and this question seems dubious but please bear with me. I have an XmlSerializer that works perfectly when written as follows (small code snippet) :
public static AbstractResponseMessageData Execute(AbstractRequestMessageData objRQ, string strComponent)
{
StreamWriter rqWriter = null;
StreamReader rsReader = null;
try
{
Cursor.Current = Cursors.WaitCursor;
String requestType = objRQ.GetType().Name;
MessageBox.Show(requestType);
String xmlRequest = "";
var serializer = new XmlSerializer(typeof(ARC_LOGONRQ));
Unforunately, as ARC_LOGONRQ is a type from an abstract data request, it is not the case that it is always the type I am needing. The only way I even knew it was the type that would get this first request to work was by using the MessageBox in my code. I figured I would simply write something like this to circumvent the issue:
Type acType = Type.GetType(requestType);
and then use acType instead of ARC_LOGONRQ in my serializer. That throws a "Type or Namespace could not be found" error however. Replacing ARC_LOGONRQ with objRQ.GetType() or objRQ throws the same error as well.
I do not understand why I get this error when using acType, nor how I should properly go about serializing objRQ without specifying the actual data type (which I can't do).
Many thanks.
FURTHER INFO:
Using the serializer:
var serializer = new XmlSerializer(typeof(objRQ.GetType()));
I also get a "Type or Namespace could not be found" error. I think it is because the type ARC_LOGONRQ appears to be arbitrary, or not in System.
You can always get the Type of an object by calling GetType. Try this:
var serializer = new XmlSerializer(objRQ.GetType());
Use typeof to obtain a Type at compile time. Use GetType to obtain a Type at run time .
Related
I am attempting to use the newer Azure.Messaging.EventGrid over the traditional Azure.EventGrid. I am getting hung up on my unit tests attempting to create object of type IotHubDeviceTelemetryEventData(). In the older library, I was able to create this no problem using the following convention.
return new object[]
{
new
{
id = "73813f6e-4d43-eb85-d6f1-f2b6a0657731",
topic = "testTopic",
data = new IotHubDeviceTelemetryEventData <-- New Up the object (no problem!)
{
Body = body} <-- Body has a setter. Great!
,
eventType = "Microsoft.Devices.DeviceTelemetry",
subject = "devices/b82bfa90fb/gw-uplink",
dataVersion = "1.0"
}
With the latest offering however, all of this is removed for some reason.
Old documentation with constructor etc (https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventgrid.models.iothubdevicetelemetryeventdata.-ctor?view=azure-dotnet
New documentation with no constructor, no setter on the body (DeviceTelemetry is sealed) etc:
https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventgrid.systemevents.iothubdevicetelemetryeventdata?view=azure-dotnet
Anyone run into this? I would like to get off the old but I have existing unit tests that logically create TelemetryEventData and send to the function. I see no way of unit testing this ? I have tried mocking IotHubDeviceTelemetryEventData with
_mockHubTelemEventData.setup(c => c.Body).Returns(foo)
but this as well throws me an error of no setter on Body.
Super frustrating.
Other attempts have included creating EventGridEvent() but this as well is missing core functionality as the EventGridEvent.parse won't find any object of type Body.
EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(req.Body));
Mocking code you don't own comes with downsides, and you just one of them. But that's not why you're here. If you want to create instances of IotHubDeviceTelemetryEventData, you can try creating them as JSON and deserialize them. Give this a shot:
using System.Text.Json;
using Azure.Messaging.EventGrid.SystemEvents;
var json = #"
{
""body"":
{
""property"": { ""foo"": ""bar"" }
}
}
";
var eventData = JsonSerializer.Deserialize<IotHubDeviceTelemetryEventData>(json);
Is there a way to prevent a $type property being added when I save my dynamic type values?
When I save this:
new Activity {
Name = "FormFieldDeleted",
Body = new {
MyDeletedFormField(),
MyCompleteForm()
}
}
I get this
<>f__AnonymousType1`2[[MyProject.Domains.Forms.Models.FormField, MyProject.Domains.Forms],[MyProject.Domains.Forms.Entities.FormRegistration, MyProject.Domains.Forms]], MyProject.Api.Forms
But when I try to fetch this saved entity, it crashes with the exception below. I know it's missing a project reference, but I really don't want to add that reference (I don't want to reference an API from a console app). It's better for me to just prevent the $type property.
/usr/local/share/dotnet/dotnet path/MyProject/MyProject/src/MyProject.Tasks.MapActivities/bin/Debug/netcoreapp3.1/MyProject.Tasks.MapActivities.dll
Unhandled exception. System.InvalidOperationException: Could not convert document 31317d58-db9e-4f60-8dee-b8593f3e06c0 to entity of type MyProject.Domains.Core.Entities.Activity
---> Newtonsoft.Json.JsonSerializationException: Error resolving type specified in JSON '<>f__AnonymousType1`2[[MyProject.Domains.Forms.Models.FormField, MyProject.Domains.Forms],[MyProject.Domains.Forms.Entities.FormRegistration, MyProject.Domains.Forms]], MyProject.Api.Forms'. Path 'Body.$type'.
---> Newtonsoft.Json.JsonSerializationException: Could not load assembly 'MyProject.Api.Forms'
....
Yes, there is a way.
You can customize the way serialization works using the following code:
store.Conventions.CustomizeJsonSerializer = serializer =>
{
serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None;
};
As an example, take a look at the code here : https://dotnetfiddle.net/voJ7US
If you execute the code at the dotnetfiddle, you can see the results here: http://live-test.ravendb.net/studio/index.html#databases/documents?collection=Activities&database=UniqueTestDB
For RavenDB 5 and higher it changed a bit.
var store = DocumentStore
{
Urls = new[] { "your-endpoint" },
Conventions = new DocumentConventions
{
Serialization = new NewtonsoftJsonSerializationConventions
{
CustomizeJsonSerializer = serializer =>
{
serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.None;
}
}
}
}.Initialize();
See https://ravendb.net/docs/article-page/5.0/file-header/migration/client-api/conventions for more information.
public ISearchResponse<object> GetById(string id) {
var uri = new Uri("<myendpoint>");
var settings = new ConnectionSettings(uri).DefaultIndex("useraction-*").PrettyJson().DisableDirectStreaming(); //or try _all
var client = new ElasticClient(settings);
var search = new SearchRequest<object>
{
Query = new TermQuery
{
Field = "field",
Value = "example"
}
};
var response = client.Search<object>(search);
return response;
}
I'm having trouble getting NEST to work. When I try to call the query defined above, I get the following error:
System.Exception: If you use a custom contract resolver be sure to subclass from ElasticResolver
at Nest.JsonExtensions.GetConnectionSettings(JsonSerializer serializer) in C:\Users\russ\source\elasticsearch-net-master\src\Nest\CommonAbstractions\Extensions\JsonExtensions.cs
I've searched the internet for mention of this and can't seem to find anything other than the source code. I've pretty much followed the documentation exactly so I don't know what to change.
Does anyone out there know what this error is trying to tell me? I feel like it's an error behind the scenes that I don't have control over.
I'm happy to answer additional questions if people need more info.
Thanks.
Also I don't know where that path is coming from in the exception because I have no user "russ"
I get the "Method may only be called on a Type for which Type.IsGenericParameter is true." from this code below. I get that error on the last line of this code. , i dont know how to fix that.
byte[] domainMainDllFileBuffer = null;
string domainMainFilePath = "myDllPath...";
FileStream domainMainFs = new FileStream(domainMainFilePath, FileMode.Open, FileAccess.Read);
BinaryReader domainMainBr = new BinaryReader(domainMainFs);
long domainMainNumBytes = new FileInfo(domainMainFilePath).Length;
domainMainDllFileBuffer = domainMainBr.ReadBytes((int)domainMainNumBytes);
System.Reflection.Assembly domainMainAssembly = System.Reflection.Assembly.Load(domainMainDllFileBuffer);
IEnumerable<Type> domainMainTypes = domainMainAssembly.GetTypes().Where(t => t.BaseType != null);
Why are you trying to read the DLL in binary format?
You can just use:
Assembly.LoadFrom("myDllPath...");
Otherwise I can't really see why you are getting that error. The only method you are calling on the assembly is GetTypes() and you are not really calling any method on the types themselves.
In order to get that exception you must be calling .GenericParameterAttributes or .GenericParameterPosition (or some similar method) somewhere that you've not posted. If that's the case, you can verify that the type is a generic parameter first:
if(type.IsGenericParameter)
{
...
}
I have successfully connected to QC using VBscript via the OTA interface. In VbScript I had the following code to filter out defects and get load them in a list.
BugFilter.Filter("BG_STATUS") = "Not Canceled and NOT Closed"
BugFilter.Filter("BG_PROJECT") = "Business*"
Set BugList = BugFilter.NewList()
The above worked flawlessly in Vbscript.
In C#.NET (4.0), I am able to connect to QC successfully but when I try to apply the filter , it give me a error..
TDConnection qcc = new TDConnection();
qcc.InitConnectionEx(sr);
qcc.ConnectProjectEx("XXXX", "------", "----", "-----");
if (qcc.Connected)
{
Console.WriteLine("connected");
BugFactory bf = (BugFactory)qcc.BugFactory;
bf.Filter["BG_STATUS"] = "Not Canceled and NOT Closed";
bf.Filter["BG_PROJECT"] = "Business*";
List bugs = (List)bf.NewList(bf.Filter);
on the last line of code , it gives me the following error "Could not convert argument 0 for call to NewList."
I am relative new to C#, Can anybody help me here?
Try bg.Filter.text()
You'd need to check the method, 'cause I do that in java. But there is a method by that name. How I normally do that is like this:
List bugs = (List)bg.NewList();
I usually pass a string into the bug factory by using the .Text property of the Filter object rather than the filter object itself.
For example, I've had success with handling the filtering like this:
var tdFilter = (TDFilter)bf_filter;
tdFilter["BG_STATUS"] = "Not Canceled and NOT Closed";
tdFilter["BG_PROJECT"] = "Business*";
var bugs = bf.NewList(tdFilter.Text);