Embedded WebResource and FileStream - asp.net

[assembly: System.Web.UI.WebResource("Project.ConfigurationFiles.Tools.xml", "text/xml")]
string resource = "Project.ConfigurationFiles.Tools.xml";
string pathXML =Page.ClientScript.GetWebResourceUrl(this.GetType(), resource);
XmlSerializer mySerializer = new XmlSerializer(typeof(ToolB));
using (FileStream myFileStream = new FileStream(pathXML, FileMode.Open))
{
The error I get:
Illegal characters in path.
I guess this happens because FilleStream need file and not url.

This exception occurs because GetWebResourceUrl function returns an HTTP address but FileStream expects a file path. From your code snippet I suppose you are trying to read the XML file that's embedded into the assembly and deserialize it back to an object. Here's how you could achieve this:
var executingAssembly = Assembly.GetExecutingAssembly();
var resource = "Project.ConfigurationFiles.Tools.xml";
using (var stream = executingAssembly.GetManifestResourceStream(resource))
{
var serializer = new XmlSerializer(typeof(ToolB));
var toolB = (ToolB)serializer.Deserialize(stream);
}

Related

How to deserialize the data of a json document stored locally in the project folder

A json file is stored in the Project folder.I want to deserialize data of that json document.Im getting error while fetching the path of json document.
I used this code and got error "An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code"
string file = HttpContext.Current.Server.MapPath("~/project.Services/xyz/myjsonfile.json");
using (StreamReader reader = new StreamReader(file))
{
collection = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());
}
below code worked for me
using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(this.GetType().Assembly.GetName().Name + "." + filename))
{using (StreamReader reader = new StreamReader(stream))
{
collection = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());
}}
Thank You Michael

Is it possible to use Json.Net to deserialise a BSON file to a dynamic object?

I have a BSON file, is there any way I can tell Json.Net to deserialise that to a dynamic object like in this example for JSON?
Yes, just deserialize as type dynamic (or JToken or ExpandoObject) following the instructions in Deserialize from BSON:
dynamic result;
using (var stream = new MemoryStream(byteArray))
using (var reader = new BsonReader(stream))
{
var serializer = JsonSerializer.CreateDefault();
result = serializer.Deserialize<dynamic>(reader); // Or ExpandoObject or JToken
}
Prototype fiddle.
To stream directly from a file, use a FileStream:
string path = "bsonData.bson"; // Or whatever
dynamic result;
using (var stream = File.OpenRead(path))
using (var reader = new BsonReader(stream))
{
var serializer = JsonSerializer.CreateDefault();
result = serializer.Deserialize<dynamic>(reader); // Or ExpandoObject or JToken
}

Downloading zip file from HttpRequestMessage : controller

I'm working on a web api's using ASP.NET MVC's which download the zip file attached in the HttpRequestMessage
as below
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
if (this.Request.Content.IsMimeMultipartContent())
{
using (Stream requestStream = task.Result)
{
// Do not know how to copy the above request to file stream or zip (ionic zip) and generate zip file from it
}
}
note:
1)
using (var fileStream = File.Create("name.zip"))
{
requestStream.CopyTo(fileStream);
}
creates invalid zip..
2) Zip contains many files inside it.
Waiting for your comments
Update 1:
var provider = new MultipartFormDataStreamProvider(ScriptPath);
Request.Content.ReadAsMultipartAsync(provider);
foreach (MultipartFileData file in provider.FileData)
{
Trace.Write(file.Headers.ContentDisposition.FileName);
Trace.Write("Server file path: " + ScriptPath);
}
though does not help me
This works for me. Please treat as pseudo as I didn't compile it. Also you may want to rework the blocking .Result call to take advantage of the Async read.
var requestStream = await Request.Content.ReadAsMultipartAsync();
HttpContent fileContent = requestStream.Contents.SingleOrDefault(c => c.Headers.ContentType != null);
byte[] fileBytes = await fileContent.ReadAsByteArrayAsync();
using (FileStream fs = File.OpenWrite(outputPath))
{
fs.Write(fileBytes, 0, (int)fileContent.Headers.ContentLength.Value);
}

Stuck Streaming Xml

This is the code i have written to get the xml of one url but it says
"Data at the root level is invalid" with any url.. Can someone specify why?
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.LoadXml("http://latestpackagingnews.blogspot.com/feeds/posts/default");//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML
Response.Write(xNodelst);
You need to first download your xml data using WebClient class
string downloadedString;
System.Net.WebClient client = new System.Net.WebClient();
downloadedString = client.DownloadString("http://latestpackagingnews.blogspot.com/feeds/posts/default");
//Now write this string as an xml
//I think you can easily do it with XmlDocument class and then read it
The xdoc.LoadXml can not for read url, change it to xdoc.Load and it will work.
You can also read : Using Returned XML with C#
XmlDocument.LoadXml method awaits XML-text, but not the source URL.
First, download page content into string and then pass it to LoadXml. Here is how you can download:
public string GetUrlContent(string url)
{
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
var content = reader.ReadToEnd();
reader.Close();
response.Close();
return content;
}
In your case it would be:
var content = GetUrlContent("http://latestpackagingnews.blogspot.com/feeds/posts/default");
var doc = new XmlDocument();
doc.LoadXml(content);

passing parameters to json web service using HttpWebRequest

I am having a problem in passing parameters to webservice which except POST data in JSON. I am using HttpWebRequest for this, following is the code i have tried so far, but everytime server returns any of these two errors:
Error 1:
{"command":null,"handle":null,"code":2003,"msg":"Required parameter missing","error":["Parameter 'login_handle' missing.","Parameter 'login_pass' missing."],"params":{"0":{"Key":"login_handle","Value":"test"},"1":{"Key":"login_pass","Value":"test"},"handle":"example.com"},"svTRID":null,"response":[]}
Error 2:
{"command":null,"handle":null,"code":2400,"msg":"Command failed","error":["Internal Server Error. resulted in the following error: array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":[],"svTRID":null,"response":[],"children":[{"command":"Internal Server Error.","handle":null,"code":2400,"msg":"Command failed","error":["array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object"],"params":{"errno":2,"errstr":"array_key_exists() [<a href='function.array-key-exists'>function.array-key-exists<\/a>]: The second argument should be either an array or an object","errfile":"\/home\/ote\/httpapi\/v1\/index.php","errline":54},"svTRID":null,"response":[]}]}
Here is the code:
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
Dictionary<string, string> data = new Dictionary<string, string>();
data["login_handle"] = "test";
data["login_pass"] = "test";
System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
webReq.Method = "POST";
webReq.ContentType = "application/json; charset=utf-8";
DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, data);
String json = Encoding.UTF8.GetString(ms.ToArray());
StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
writer.Write(json);
writer.Close();
System.Net.WebResponse webResp = webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
string s = sr.ReadToEnd().Trim();
}
catch (Exception ex)
{
string e = ex.Message;
}
If i use string data = "[login_handle:'username',login_pass:'password']"; instead of Dictionary<string, string> , i receive error number 2.
Never mind, i solved it myself, instead of using Dictionary type i used anonymous type like this var data = new { login_handle = "test", login_pass = "test" }; and it solved my problem.
What you should have done is create a DataContract class (we'll call JsonData) which has two DataMembers named login_handle and login_pass.
Then, in the DataContractJsonSerializer, pass typeof(JsonData) to the constructor.
This solution is the best because you cannot create complex types using an anonymous type. Also, by parenting your DataContracts you can easily create complex JSON.

Resources