XPathDocument Error Will not write to file c# - xpath

private void SetValueToDocumentByXPath(XPathDocument doc, string xpath, string value)
{
var nav = doc.CreateNavigator();
var it = nav.Select(xpath, nameSpaceManager_);
if (it.MoveNext())
{
it.Current.SetValue(value);
}
}
Since I have changed the document coming in as a parameter I am getting this error:
Additional information: Specified method is not supported.
I would like to Edit the doc coming into the function

Related

Parse JSON request without creating a class

In a Spring MVC controller method, I have a JSON input (request body) with just one field: {"version":3}. I can get this value like this:
#RequestMapping
public void myMethod(#RequestBody MyJsonRequest myJsonRequest) {
int version = myJsonRequest.version;
//...
}
But I have to create MyJsonRequest class with a version field. How can I get the version value without creating a new class?
You can try using a map:
public void myMethod(#RequestBody Map<String, Integer> myJsonRequest) {
int version = myJsonRequest.get("version");
//...
}
You can parse JSON data and then you can directly access to value of JSON response.
Consider data as myJsonRequest :
var version=0;
var jsonval = $.parseJSON(data);
// you can use directly value of json data like
version = data.version;
// If you returned an array in json response, then you can use $.each method and store value into single array, like this
$.each(portals_array,function(i,v){
version[] = v.version;
});
alert(version);
};
It's working perfectly in my code. Check it out.
Try the code below, it maps your json object to a primitive int variable:
#RequestMapping(value="/yourMapping", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON)
public void myMethod (#RequestBody int version) {
//do something with your int variable version
}

Post Binary array to Web API Controller

I am trying to POST form data which consists of few string variable and binary array.
Below is the Model for the form data.
public class FileModel
{
public string Path { get; set; }
public byte[] File { get; set; }
}
Below is my Web API Controller.
[Route("")]
public IHttpActionResult Post([FromBody]FileModel media)
{
// Can I use ??
byte[] requestFile = media.File;
string requestFilePath = media.Path;
//Process the above variables
return Ok();
}
I would like to know Can I use the following code to de-serialize the following code snippet to to read the values from the JSON payload including the binary data?
byte[] requestFile = media.File;
string requestFilePath = media.Path;
If Yes, Do I need to define any formatter class to get it working?
I normally use POSTMAN to test my RESTful endpoints.
Is it possible to use POSTMAN still to POST binary array? May be not need to write my own client
You'll need to use a serializer to serialize complex objects (multiple fields) as content for a Http Request.
For your code snippet to read the object from the content you can use this:
var requestContent = Request.Content.ReadAsAsync<FileModel>(GetJsonSerializer()).Result;
Here's the serializer boilerplate code.
private JsonMediaTypeFormatter GetJsonSerializer()
{
JsonSerializerSettings settings = new JsonSerializerSettings()
{
PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All,
TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
};
return new JsonMediaTypeFormatter() { SerializerSettings = settings };
}
I'm not sure how to use POSTMAN to test this. A simple .net client would be:
var Client = new HttpClient();
Client.BaseAddress = new Uri("localhost"); //whatever your endpoint is
FileModel objectToSend = new FileModel();
var objectContent = new ObjectContent<FileModel>(objectToSend, GetJsonSerializer() );
var response = Client.PostAsync("uri", objectContent);
You are able to use POSTMAN to test binary file input. Selecting the body tab, you can then pick the radio button "binary" and then choose file.

Referencing Action Parameters from ExceptionLogger

I'm wanting to make use of the new method for globally logging errors. I've written a class that inherits ExceptionLogger and overrides the Log() method. Then registered it as a replacement.
public class TraceExceptionLogger : ExceptionLogger
{
public async override void Log(ExceptionLoggerContext context)
{
// This is always empty string
var content = await context.Request.Content.ReadAsStringAsync();
// This is almost always null
var actionContext = context.ExceptionContext.ActionContext;
}
}
I can dig through the ExceptionLoggerContext object's properties to get pretty much everything I need, EXCEPT for action parameters. There is indeed an ActionContext property but I've only seen it null and this wiki page states that ActionContext and ControllerContext will almost always be null.
Also, I can't get the content stream because its stream is already read before it gets to my logger. So there's no way for me to get any posted json from the request's content.
Is there maybe a way to get the posted data from HttpContext.Current or in some other way?
Ok it looks like I can get the body text from HttpContext by reading InputStream on the Request object like this:
string bodyText = string.Empty;
using (var sr = new StreamReader(HttpContext.Current.Request.InputStream))
{
sr.BaseStream.Seek(0, SeekOrigin.Begin);
bodyText = sr.ReadToEnd();
}
This code has been successful me so far for getting my posted json data.
Here's action parameters for future reference
public class HomeController : ApiController {
public string Get(string id, [FromHeader] Whoever whoever) {
public string Post(Whatever whatever) {
var args = ((ApiController) context.ExceptionContext
.ControllerContext.Controller)).ActionContext.ActionArguments
if (args.ContainsKey("whatever")) {
var whatever = (Whatever)args["whatever"];

ASP.NET MVC 3 Parse JSon object and display data

I have a class
public class ConversionResultModel
{
public string ProcessId { get; set; }
public bool Result { get; set; }
public string Message { get; set; }
}
sending it to view using JSon
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> clientUpload)
{
string destinationPath = "";
JsonResult result = null;
var fileModel = new ConversionResultModel();
fileModel.ProcessId = "4558-95559-554";
fileModel.Result = true;
fileModel.Message = "test.pdf";
result = Json(new { fileModel }, "text/plain");
return result;
}
How to parse such JSon object at client side using JS or jQuery and read values?
I have tried to parse JSon object with code below but get Undefined error in alert
var obj = $.parseJSON(e.response);
alert(e.obj);
I receive JSon object like this
{"fileModel":{"ProcessId":"4558-95559-554","Result":true,"Message":null,"SourceFile":null,"ConvertedFileName":"test.pdf","ConvertedFileSize":1233444,"DownloadUrl":"http://localhost:2008/download?path=4558-95559-554","DeleteUrl":"http://localhost:2008/download?path=4558-95559-554"}}
You do not need to parse it. Just set data type to JSON during ajax request and then use received data object like entity and you easily can access to any property:
var id = data.ProcessId;
Anyway, using jQuery you can parse JSON string:
var data = jQuery.parseJSON(stringData);
P.S:
Use the following code sample for converting object to JSON in ASP.NET MVC:
return this.Json(fileModel);
http://api.jquery.com/jQuery.parseJSON/
In your case, I think you're getting back the correct JSON, but your alert is looking at the wrong object. Try alert(obj.SomeProperty) rather than alert(e.obj). e.obj doesn't exist, which is likely why you're getting an "undefined" error. For example, alert(obj.fileModel.ProcessId); should work.

VS 2010 addin: getting selected text in the editor

Coders, I am developing an add in for VS2010 and I am trying to get the selected text in the code editor. so far, i have been searching many webpages and thy all seems to use DTE.ActiveDocument which causes an error in my code. I have written two versions of a method that suppose to return a selected text in the editor but I still get the same error over and over:
the error is: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get'
and here are my two versions of the method (only relevant code is showen):
using EnvDTE;
private string getSelectedText_V1()
{
string selectedText = string.Empty;
/*PROBLEM HERE: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get'*/
Document doc = DTE.ActiveDocument;
return selectedText;
}
private string getSelectedText_V2()
{
string selectedText = string.Empty;
/*PROBLEM HERE: An object reference is required for the non-static field, method, or property 'EnvDTE._DTE.ActiveDocument.get'*/
EnvDTE.TextSelection TxtSelection = DTE.ActiveDocument.Selection;
return selectedText;
}
Please help me figure out what i did wrong in my code?
If you have access to GetService() method in your addin, you could add:
DTE dte = this.GetService(typeof(DTE)) as DTE;
Then your code would become:
private string getSelectedText_V1()
{
string selectedText = string.Empty;
DTE dte = this.GetService(typeof(DTE)) as DTE;
Document doc = dte.ActiveDocument;
return doc.Selection.Text;
}

Resources