Converting mongoexport json to XML - c#

I export data from our mongoDb database into json file, and need to parse it to XML in order to be usable in our ETL.
Here is a sample of code I try to use to parse one line of my json export :
var json = #"{""_id"":{""$oid"":""592bbd86b029e62830c5020a""},""DraftNumber"":""A1B1CB8D"",""ProductRange"":""COMPREHENSIVE_HOME_INSURANCE"",""DraftStatus"":""QUOTATION_DRAFT"",""DraftLabel"":"""",""LastUpdateDate"":{""$date"":""2017-05-29T06:19:53.559Z""},""EndDate"":{""$date"":""2017-07-28T06:19:53.559Z""},""UserId"":""D900036"",""ProjectNumber"":""38764496"",""Identifier"":"""",""CurrencyCode"":""EUR"",""RenewalDate"":{""$date"":""0001-01-01T00:00:00.000Z""},""RenewalDay"":0,""RenewalMounth"":0,""CreationDate"":{""$date"":""2017-05-29T06:19:50.138Z""},""EffectiveHour"":""0"",""EffectiveMinute"":""0"",""HasAs"":[{""_t"":""AgreementHolder"",""_id"":{""$oid"":""000000000000000000000000""},""DistribCustomer"":{""isProspect"":true}}],""IsBasedOnProduct"":{""pricingType"":""DISCOUNT_RATE"",""pricingVersion"":""C""},""ActivityInAgreements"":[{""_t"":""AgreementRequest"",""_id"":{""$oid"":""000000000000000000000000""},""PremiumNature"":null}],""OriginalSubscriptionChannel"":""DIRECT"",""CurrentSubscriptionChannel"":""DIRECT"",""BusinessExpirationDate"":{""$date"":""0001-01-01T00:00:00.000Z""},""TechnicalExpirationDate"":{""$date"":""2017-08-27T06:19:53.559Z""},""IsEligibleToProposal"":true,""IneligibityReasonCodes"":[],""DematerialisationOfDocuments"":true}";
var doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
Console.WriteLine(doc);
Console.ReadKey();
And i face the following exception :
L'exception Newtonsoft.Json.JsonSerializationException n'a pas été
gérée HResult=-2146233088 Message=JSON root object has multiple
properties. The root object must have a single property in order to
create a valid XML document. Consider specifying a
DeserializeRootElementName. Path 'DraftNumber', line 1, position 57.
Source=Newtonsoft.Json StackTrace:
à Newtonsoft.Json.Converters.XmlNodeConverter.DeserializeNode(JsonReader
reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode
currentNode)
à Newtonsoft.Json.Converters.XmlNodeConverter.ReadJson(JsonReader
reader, Type objectType, Object existingValue, JsonSerializer
serializer)
à Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter
converter, JsonReader reader, Type objectType, Object existingValue)
à Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader
reader, Type objectType, Boolean checkAdditionalContent)
à Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
à Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
à Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonConverter[] converters)
à Newtonsoft.Json.JsonConvert.DeserializeXmlNode(String value, String deserializeRootElementName, Boolean writeArrayAttribute)
à Newtonsoft.Json.JsonConvert.DeserializeXmlNode(String value)
à ConsoleApplication3.Program.Main(String[] args) dans c:\documents\s638723\documents\visual studio
2015\Projects\ConsoleApplication3\Program.cs:ligne 17
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart() InnerException:
More globally i'm wondering if the type exported by mongoexport is usable by the jsonconverter.

As the exception states, JSON has multiple properties at top level.
Simply define root like:
using (StreamReader r = new StreamReader("Json_1.json"))
{
string json = r.ReadToEnd();
var doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "root");
}
Output:
<root>
<_id>
<_x0024_oid>592bbd86b029e62830c5020a</_x0024_oid>
</_id>
<DraftNumber>A1B1CB8D</DraftNumber>
<ProductRange>COMPREHENSIVE_HOME_INSURANCE</ProductRange>
<DraftStatus>QUOTATION_DRAFT</DraftStatus>
<DraftLabel/>
<LastUpdateDate>
<_x0024_date>2017-05-29T06:19:53.559Z</_x0024_date>
</LastUpdateDate>
<EndDate>
<_x0024_date>2017-07-28T06:19:53.559Z</_x0024_date>
</EndDate>
<UserId>D900036</UserId>
<ProjectNumber>38764496</ProjectNumber>
<Identifier/>
<CurrencyCode>EUR</CurrencyCode>
<RenewalDate>
<_x0024_date>0001-01-01T00:00:00Z</_x0024_date>
</RenewalDate>
<RenewalDay>0</RenewalDay>
<RenewalMounth>0</RenewalMounth>
<CreationDate>
<_x0024_date>2017-05-29T06:19:50.138Z</_x0024_date>
</CreationDate>
<EffectiveHour>0</EffectiveHour>
<EffectiveMinute>0</EffectiveMinute>
<HasAs>
<_t>AgreementHolder</_t>
<_id>
<_x0024_oid>000000000000000000000000</_x0024_oid>
</_id>
<DistribCustomer>
<isProspect>true</isProspect>
</DistribCustomer>
</HasAs>
<IsBasedOnProduct>
<pricingType>DISCOUNT_RATE</pricingType>
<pricingVersion>C</pricingVersion>
</IsBasedOnProduct>
<ActivityInAgreements>
<_t>AgreementRequest</_t>
<_id>
<_x0024_oid>000000000000000000000000</_x0024_oid>
</_id>
<PremiumNature />
</ActivityInAgreements>
<OriginalSubscriptionChannel>DIRECT</OriginalSubscriptionChannel>
<CurrentSubscriptionChannel>DIRECT</CurrentSubscriptionChannel>
<BusinessExpirationDate>
<_x0024_date>0001-01-01T00:00:00Z</_x0024_date>
</BusinessExpirationDate>
<TechnicalExpirationDate>
<_x0024_date>2017-08-27T06:19:53.559Z</_x0024_date>
</TechnicalExpirationDate>
<IsEligibleToProposal>true</IsEligibleToProposal>
<DematerialisationOfDocuments>true</DematerialisationOfDocuments>
</root>

Related

WindowsIdentity.Impersonate() in owin middleware

We're using following OWIN middleware in our web app to impersonate user based on incoming request.
public class SomeMiddleware : OwinMiddleware
{
public SomeMiddleware(OwinMiddleware next) : base(next)
public override async Task Invoke(IOwinContext context)
{
var identity = context.Authentication.User?.Identity;
if(identity is WindowsIdentity windowsIdentity)
{
using var ctx = windowsIdentity.Impersonate();
await Next.Invoke(context);
}
}
}
The other middleware in pipeline logs stuff with log4net. The appender layout template has user identity.
Sometimes the web app blows up with following error.
System.ObjectDisposedException: Safe handle has been closed
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Microsoft.Win32.Win32Native.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.GetName()
at System.Security.Principal.WindowsIdentity.get_Name()
at log4net.Core.LoggingEvent.get_Identity()
at log4net.Layout.Pattern.IdentityPatternConverter.Convert(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Layout.Pattern.PatternLayoutConverter.Convert(TextWriter writer, Object state)
at log4net.Util.PatternConverter.Format(TextWriter writer, Object state)
at log4net.Layout.PatternLayout.Format(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Appender.AppenderSkeleton.RenderLoggingEvent(TextWriter writer, LoggingEvent loggingEvent)
at log4net.Appender.TextWriterAppender.Append(LoggingEvent loggingEvent)
at log4net.Appender.FileAppender.Append(LoggingEvent loggingEvent)
at log4net.Appender.RollingFileAppender.Append(LoggingEvent loggingEvent)
at log4net.Appender.AppenderSkeleton.DoAppend(LoggingEvent loggingEvent)
...
Invalid token for impersonation - it cannot be duplicated.</Message><StackTrace> at System.Security.Principal.WindowsIdentity.CreateFromToken(IntPtr userToken)
at System.Security.Principal.WindowsIdentity..ctor(IntPtr userToken, String authType, Int32 isAuthenticated)
at System.Security.Principal.WindowsIdentity..ctor(SafeAccessTokenHandle safeTokenHandle)
at System.Security.SecurityContext.CaptureCore(Reader currThreadEC, StackCrawlMark&amp; stackMark)
at System.Threading.ExecutionContext.Capture(StackCrawlMark&amp; stackMark, CaptureOptions options)
at System.Threading.ExecutionContext.FastCapture()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.GetCompletionAction(Task taskForTracing, MoveNextRunner&amp; runnerToInitialize)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AwaitUnsafeOnCompleted[TAwaiter,TStateMachine](TAwaiter&amp; awaiter, TStateMachine&amp; stateMachine)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.&lt;&gt;c.&lt;ThrowAsync&gt;b__6_1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()</StackTrace><ExceptionString>System.ArgumentException: Invalid token for impersonation - it cannot be duplicated.
at System.Security.Principal.WindowsIdentity.CreateFromToken(IntPtr userToken)
at System.Security.Principal.WindowsIdentity..ctor(IntPtr userToken, String authType, Int32 isAuthenticated)
at System.Security.Principal.WindowsIdentity..ctor(SafeAccessTokenHandle safeTokenHandle)
at System.Security.SecurityContext.CaptureCore(Reader currThreadEC, StackCrawlMark&amp; stackMark)
at System.Threading.ExecutionContext.Capture(StackCrawlMark&amp; stackMark, CaptureOptions options)
at System.Threading.ExecutionContext.FastCapture()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.GetCompletionAction(Task taskForTracing, MoveNextRunner&amp; runnerToInitialize)
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.AwaitUnsafeOnCompleted[TAwaiter,TStateMachine](TAwaiter&amp; awaiter, TStateMachine&amp; stateMachine)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.&lt;&gt;c.&lt;ThrowAsync&gt;b__6_1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()</ExceptionString></Exception></TraceRecord>
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
How likely is the middleware at fault here? Am I looking at the wrong place?

How to get the Previous date from the Input in C#

My Code is as follows:
String DateTime = "20221002" (Format = "yyyyMMdd" )
Expected Result:
"20220930" ( Same format as above )
Code written:
public string FormatDateTime(string param1)
{
return Convert.ToDateTime(param1).AddDays(-1).ToString();
}
Exception Detail :
System.FormatException was unhandled
HResult=-2146233033
Message=String was not recognized as a valid DateTime.
Source=mscorlib
StackTrace:
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.Convert.ToDateTime(String value)
at ConsoleApplication1.Program.Main(String[] args) in C:\Users\adharmalin\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 235
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Am I missing something? I am getting a syntax error.
You can use ParseExact (or the TryParseExact if you're not sure it's valid)
public string FormatDateTime(string param1)
{
var myDate = DateTime.ParseExact(param1, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
return myDate.AddDays(-1).ToString();
}
[TestMethod]
public void TestDate()
{
String DateTime = "20221002";
Console.WriteLine(FormatDateTime(DateTime));
}

Getting name associated with province(AdventureWorks2014) exception

im doing test using the AdventureWorks2014 microsoft database with visual studio(coding in C#).I am trying to input StateProvinceID and then display the names(Person.FirstName) that are associated with this StateProvinceID.So far I did this:
static public void provincequery()
{
Console.WriteLine("Enter province ID");
var theid = Convert.ToInt32(Console.ReadLine());
using (var context = new Model1())
{
var queryprovince = from test in context.StateProvince
where test.StateProvinceID == theid
select test;
foreach(var disp in queryprovince)
{
Console.WriteLine("\nProvince:");
Console.WriteLine(disp.Name);
foreach(var test2 in disp.SalesTerritory.Customer)
{
Console.WriteLine(test2.Person.FirstName);
}
}
}
}
however this keeps returning me an error "An error occurred while executing the command definition. See the inner exception for details."
inner exception:
à System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
à System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
à System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
à System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
à System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
à System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
à System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
à System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)
à System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption)
à System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
à System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
à System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)
à System.Data.Entity.DynamicProxies.StateProvince_0A13F786927514ECF26BEB6F7007442E73C1FCAA3A743679986FA051D479F5AA.get_SalesTerritory()
à ConsoleApplication1.Program.requete2() dans c:\Users\julianp\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:ligne 152
à ConsoleApplication1.Program.Main(String[] args) dans c:\Users\julianp\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs:ligne 33
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
I dont really understand why its not working.AdventureWorks schema can be found here:
https://moidulhassan.files.wordpress.com/2014/07/adventureworks2008_schema.gif
thank you
Solved; needed to add ToList() at the end of foreach(var disp in queryprovince).
So its foreach(var disp in queryprovince.ToList())

Azure Service Bus - Data Transmission Issue

I'm working on a project where we would like to send messages via an Azure Service Bus (Topic). In this instance, I've setup a C# Console app and a Java app that sends and receives messages between them.
When sending a message from C#, I get a strangely formatted string within Java containing "schema.microsoft.com/2003/10/serialisation". Changing the message content type makes no difference.
When sending data from Java to C# I get an exception.
Send/Receive Data - C#
private static void SendMessages()
{
topicClient = TopicClient.Create(TopicName);
List<BrokeredMessage> messageList = new List<BrokeredMessage>();
messageList.Add(CreateSampleMessage("1", "Test"));
Console.WriteLine("\nSending messages to topic...");
foreach (BrokeredMessage message in messageList)
{
while (true)
{
try
{
topicClient.Send(message);
}
catch (MessagingException e)
{
if (!e.IsTransient)
{
Console.WriteLine(e.Message);
throw;
}
else
{
HandleTransientErrors(e);
}
}
Console.WriteLine(string.Format("Message sent: Id = {0}, Body = {1}", message.MessageId, message.GetBody<string>()));
break;
}
}
topicClient.Close();
}
private static BrokeredMessage CreateSampleMessage(string messageId, string messageBody)
{
BrokeredMessage message = new BrokeredMessage(messageBody);
message.MessageId = messageId;
return message;
}
C# Stacktrace
{"There was an error deserializing the object of type System.String. Unexpected end of file. Following elements are not closed: ."}
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(XmlDictionaryReader reader)
at Microsoft.ServiceBus.Messaging.DataContractBinarySerializer.ReadObject(Stream stream)
at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T](XmlObjectSerializer serializer)
at Microsoft.ServiceBus.Messaging.BrokeredMessage.GetBody[T]()
at Microsoft.Samples.MessagingWithTopics.program.ReceiveMessages() in d:\Downloads\Getting Started Messaging With Topics (1)\C#\MessagingWithTopics\program.cs:line 127
at Microsoft.Samples.MessagingWithTopics.program.Main(String[] args) in d:\Downloads\Getting Started Messaging With Topics (1)\C#\MessagingWithTopics\program.cs:line 39
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
a) You may not use AMQP from .NET. Only then you get AMQP encoding. Append TransportType=Amqp to connection string. And then use Apache Proton-J's JMS provider.
b) If you use HTTP from Java, try constructing the message either over a self-serialized stream (Stream parameterized constructor) or using for instance the DataContractSerializer explicity with the (object, XmlObjectSerializer) parameterized constructor. That will give you an XML Test payload. By default we use the NetDataContractSerializer which yields a compact encoding but is .NET only.

Invalid URI: The Uri string is too long

I am trying to grab a schema and validate against my xml.
XmlReaderSetting settings = new System.Xml.XmlReaderSettings();
settings.Schemas.Add(null, "http://example.com/myschema.xsd");
settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(settings_ValidationEventHandler);
settings.ValidationType = ValidationType.Schema;
settings.IgnoreWhitespace = false;
XmlReader reader = XmlReader.Create(xml, settings);
I get
Invalid URI: The Uri string is too long
System.UriFormatException was unhandled Message=Invalid URI: The Uri string is too long. Source=System StackTrace:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
at System.Xml.XmlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlUrlResolver.ResolveUri(Uri baseUri, String relativeUri)
at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings)
at ConsoleApplication2.Program.Main(String[] args) in Program.cs:line 42
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
Does not tell me what the max length is or anything. Anyone ever get this before?
the problem is that the xml in your xmlreader.create function should be a uri if the argument is a string.
eg.
XmlReader reader = XmlReader.Create("http://ServerName/data/books.xml", settings);
In your case the xml file is being interpreted as the url and hence it is complaining about the limit.
look at this msdn doc XmlReader.Create Method
for different overloaded methods..
I am guessing you should use the TextReader one.

Categories