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.
Related
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));
}
I'm trying to download a zip file in Windows Application , but is is throwing an error . My code is :
string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
using (WebClient wc = new WebClient())
{
wc.DownloadFile(url, #"c:\bhav\file.zip");
}
Exception details :
System.Net.WebException was unhandled HResult=-2146233079
Message=The remote server returned an error: (403) Forbidden.
Source=System StackTrace:
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at System.Net.WebClient.DownloadFile(String address, String fileName)
at unzip.Form1.downloadFile() in c:\users\ethicpro\documents\visual studio
2015\Projects\unzip\unzip\Form1.cs:line 30
at unzip.Form1..ctor() in c:\users\ethicpro\documents\visual studio 2015\Projects\unzip\unzip\Form1.cs:line 20
at unzip.Program.Main() in c:\users\ethicpro\documents\visual studio 2015\Projects\unzip\unzip\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
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:
Link is : https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip
I searched for other questions but didn't get the proper answer.
Try this
string url = "https://www.nseindia.com/content/historical/DERIVATIVES/2017/JUN/fo07JUN2017bhav.csv.zip";
string fileName = #"C:\Temp\tt.zip";
using (WebClient wc = new WebClient())
{
wc.Headers.Add("User-Agent: Other");
wc.DownloadFile(url, fileName);
}
The file might no longer exist.
I use VB.Net.
But you have to use the equivalent of on error resume next on this file or another file with a more recent date with and without on error resume next. Or the equivalent in C#.
Another option is that some characters cannot be downloaded, like : | > or .csv.zip should be .zip without the .csv.
When viewing the page source for a page I use CTRL-F to find all occurrences of "id=", which gives me 82 results. What I want to do is to extract only the numbers after the "id=". For example, if the attribute is id=344 then I only want to get the 344 as string and add it to the List.
The way I'm doing it now I'm not getting links I thought I will get all the links this way and make filter after it but I'm getting empty string and some texts nothing from what I wanted. I guess doing InnerText is wrong.
Source View
idsnumbers = new List<string>();
HtmlWeb hw = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = hw.Load("http://www.tapuz.co.il/forums2008/");
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
idsnumbers.Add(link.InnerText);
}
Update getting null exception:
System.NullReferenceException was unhandled
_HResult=-2147467261
_message=Object reference not set to an instance of an object.
HResult=-2147467261
IsTransient=false
Message=Object reference not set to an instance of an object.
Source=WindowsFormsApplication1
StackTrace:
at WindowsFormsApplication1.Form1..ctor() in d:\C-Sharp\Tapuz Images\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 50
at WindowsFormsApplication1.Program.Main() in d:\C-Sharp\Tapuz Images\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 19
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:
You should read ids from the attributes. InnerText is just for the text inside the tag, between the opening and closing brackets. So:
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
idsnumbers.Add(link.Attributes["id"].Value);
}
And if you want to further extract only numbers from ids, you could use RegEx or int.TryParse.
I have some code that's been working fine on Windows 7 but fails now that I've started using a Windows 8.1 dev box (see repro code below).
Is RSA different on Windows 8.1 vs. Windows 7?
using System.Security.Cryptography;
using System.Text;
namespace RsaBug
{
class Program
{
static void Main()
{
var modulus = Encoding.UTF8.GetBytes("rvco6d27bsw2fw5qx7okdcu5jahd1ifh22is76k5xyau3wjv7plo0rom66h2434tvm29cmq2ov6mbjo30bymb14j2dst5fzy7pd");
var exponent = Encoding.UTF8.GetBytes("1ekh");
using (var rsa = new RSACryptoServiceProvider())
{
//Get an instance of RSAParameters from ExportParameters function.
var rsaKeyInfo = rsa.ExportParameters(false);
//Set RSAKeyInfo to the public key values.
rsaKeyInfo.Modulus = modulus;
rsaKeyInfo.Exponent = exponent;
//Import key parameters into RSA.
rsa.ImportParameters(rsaKeyInfo); // on Windows 8.1, this throws
}
}
}
}
Here's the exception I get:
System.Security.Cryptography.CryptographicException was unhandled
_HResult=-2147024809
_message=The parameter is incorrect.
HResult=-2147024809
IsTransient=false
Message=The parameter is incorrect.
Source=mscorlib
StackTrace:
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.Utils._ImportKey(SafeProvHandle hCSP, Int32 keyNumber, CspProviderFlags flags, Object cspObject, SafeKeyHandle& hKey)
at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)
at RsaBug.Program.Main() in d:\sandbox\2015\RsaBug\RsaBug\Program.cs:line 24
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:
Based on the alphabet present it is likely that the modulus and exponent are base-36 encoded.
I'm trying to get a html page content from a private service.
The page returns status code 0, which is not valid. But the page do render when browsing through a browser.
When I try use WebResponse.GetResponseStream() it simply returns empty stream.
And when I try use HttpClient.GetStringAsync(url).Result, it throws AggregateException as follow:
System.AggregateException was unhandled
HResult=-2146233088
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at DiagnosticInfoCrawler.Program.Main(String[] args) in c:\TFS\MSNMetro\Tools\Verticals\Sports\DiagnosticInfoCrawler\Program.cs:line 47
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: System.Net.Http.HttpRequestException
HResult=-2146233088
Message=Response status code does not indicate success: 0 ().
InnerException:
Two types of code used as follow:
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
Anyone can advise how can I get the response body? (given that I have no control to fix the service to return the correct status code.)
Thank you,
DD
Catch WebException to get the response. This is a poor design decision by Microsoft since non 200 codes can be part of the normal case.
try
{
WebResponse response = GetWebResponse(url);
responseBody = (new StreamReader(response.GetResponseStream())).ReadToEnd();
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
pageSource = httpClient.GetStringAsync(url).Result;
}
catch (WebException exception)
{
var response = (HttpWebResponse)exception.GetResponse();
//the response is here..
}
Didn't resolve this issue directly, but instead went to the approach to use TcpClient to read the response.