how to read Data context parameter from a crm to silverlight webresource - silverlight-4.0

i have a silverlight webresource in my crm 2011.
now my task is to append a data parameter in url like
https://www.............../data=1234
now in silverlight application i need to read this data parameter.
i have tried to read the data
if (App.Current.Host.InitParams["data"] != string.Empty)
{
string CallerNumber = App.Current.Host.InitParams["data"];
...
and
i tried filtering the code to like
string url = System.Windows.Browser.HtmlPage.Document.DocumentUri.ToString();
var uri = new Uri(url);
var CallerNumber = uri.Query;
callernumber will have the ?data=1234
but still i am not able to get the data parameter. Do help

I believe that you will find those in the query string. You can access it like this
foreach (var item in HtmlPage.Document.QueryString)
{
//Do something like the data
}

Related

Google diff-match-patch : How to unpatch to get Original String?

I am using Google diff-match-patch JAVA plugin to create patch between two JSON strings and storing the patch to database.
diff_match_patch dmp = new diff_match_patch();
LinkedList<Patch> diffs = dmp.patch_make(latestString, originalString);
String patch = dmp.patch_toText(diffs); // Store patch to DB
Now is there any way to use this patch to re-create the originalString by passing the latestString?
I google about this and found this very old comment # Google diff-match-patch Wiki saying,
Unpatching can be done by just looping through the diff, swapping
DIFF_INSERT with DIFF_DELETE, then applying the patch.
But i did not find any useful code that demonstrates this. How could i achieve this with my existing code ? Any pointers or code reference would be appreciated.
Edit:
The problem i am facing is, in the front-end i am showing a revisions module that shows all the transactions of a particular fragment (take for example an employee details), like which user has updated what details etc. Now i am recreating the fragment JSON by reverse applying each patch to get the current transaction data and show it as a table (using http://marianoguerra.github.io/json.human.js/). But some JSON data are not valid JSON and I am getting JSON.parse error.
I was looking to do something similar (in C#) and what is working for me with a relatively simple object is the patch_apply method. This use case seems somewhat missing from the documentation, so I'm answering here. Code is C# but the API is cross language:
static void Main(string[] args)
{
var dmp = new diff_match_patch();
string v1 = "My Json Object;
string v2 = "My Mutated Json Object"
var v2ToV1Patch = dmp.patch_make(v2, v1);
var v2ToV1PatchText = dmp.patch_toText(v2ToV1Patch); // Persist text to db
string v3 = "Latest version of JSON object;
var v3ToV2Patch = dmp.patch_make(v3, v2);
var v3ToV2PatchTxt = dmp.patch_toText(v3ToV2Patch); // Persist text to db
// Time to re-hydrate the objects
var altV3ToV2Patch = dmp.patch_fromText(v3ToV2PatchTxt);
var altV2 = dmp.patch_apply(altV3ToV2Patch, v3)[0].ToString(); // .get(0) in Java I think
var altV2ToV1Patch = dmp.patch_fromText(v2ToV1PatchText);
var altV1 = dmp.patch_apply(altV2ToV1Patch, altV2)[0].ToString();
}
I am attempting to retrofit this as an audit log, where previously the entire JSON object was saved. As the audited objects have become more complex the storage requirements have increased dramatically. I haven't yet applied this to the complex large objects, but it is possible to check if the patch was successful by checking the second object in the array returned by the patch_apply method. This is an array of boolean values, all of which should be true if the patch worked correctly. You could write some code to check this, which would help check if the object can be successfully re-hydrated from the JSON rather than just getting a parsing error. My prototype C# method looks like this:
private static bool ValidatePatch(object[] patchResult, out string patchedString)
{
patchedString = patchResult[0] as string;
var successArray = patchResult[1] as bool[];
foreach (var b in successArray)
{
if (!b)
return false;
}
return true;
}

Accessing the Request.Content in the new ASP.NET vnext web api way of doing things?

I have searched high and low for this one and can't seem to find a way of accessing the Request.Content in an MVC web api. I basically am trying to create a File Service to and from Azure Blob and Table storage (table for storing metadata about the file, blob for the actual file)....
I was converting the steps in the following link, but this is where I have come unstuck
the back end I have working but can't find a way of the new unified controller passing a fileobject from json post through to the service! Any ideas would be greatly appreciated as always... or am I just going about this the wrong way?
Article here....
UPDATE: so to clarify, what I am trying to do in the new MVC 6 (where you no longer have an apicontroller to inherit from) is to access a file that has been uploaded to the api from a JSON post. That is the long and short of what I am trying to achieve.
I am trying to use the article based on the old Web API which uses the Request.Content to access it, however even if I use the WebAPIShim which they provide I still come unstuck with other objects or properties that are no longer available so I'm wondering if I need to approach it a different way, but either way, all I am trying to do is to get a file from a JSON post to a MVC 6 Web api and pass that file to my back end service....
ANY IDEAS?
Here is an example without relying on model binding.
You can always find the request data in Request.Body, or use Request.Form to get the request body as a form.
[HttpPost]
public async Task<IActionResult> UploadFile()
{
if (Request.Form.Files != null && Request.Form.Files.Count > 0)
{
var file = Request.Form.Files[0];
var contentType = file.ContentType;
using (var fileStream = file.OpenReadStream())
{
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream);
// do what you want with memoryStream.ToArray()
}
}
}
return new JsonResult(new { });
}
If the only thing in your request is a File you can use the IFormFile class in your action:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}

Marketo rest Api create lead

I have a question about this create/Update leads API, http://developers.marketo.com/documentation/rest/createupdate-leads/.
There is no sample code for C# or JAVA. Only ruby available. So I have to try it by myself. But I always get null return from the response.
Here is my code:
private async Task<CreateLeadResponseResult> CreateLead(string token)
{
string url = String.Format(marketoInstanceAddress+"/rest/v1/leads.json?access_token={0}", token);
var fullUri = new Uri(url, UriKind.Absolute);
CreateLeadResponseResult createLeadResponse = new CreateLeadResponseResult();
CreateLeadInput input = new CreateLeadInput { email = "123#123.com", lastName = "Lee", firstName = "testtesttest", postCode = "00000" };
CreateLeadInput input2 = new CreateLeadInput { email = "321#gagaga.com", lastName = "Lio", firstName = "ttttttt", postCode = "00000" };
List<CreateLeadInput> inputList = new List<CreateLeadInput>();
inputList.Add(input);
inputList.Add(input2);
CreateLeadRequest createLeadRequest = new CreateLeadRequest() { input = inputList };
JavaScriptSerializer createJsonString = new JavaScriptSerializer();
string inputJsonString = createJsonString.Serialize(createLeadRequest);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(fullUri.OriginalString, inputJsonString).ConfigureAwait(false);
// I can see the JSON string is in the message body in debugging mode.
if (response.IsSuccessStatusCode)
{
createLeadResponse = await response.Content.ReadAsAsync<CreateLeadResponseResult>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return createLeadResponse;}
//get null here.
Thank you.
-C.
The best way to debug this is to capture the exact URL, parameters and JSON that are submitted by your app and try submitting those manually via a tool like Postman (Chrome plug-in) or SOAP UI. Then you see the exact error message, which you can look up here: http://developers.marketo.com/documentation/rest/error-codes/. Based on that you can update your code. I don't know much about Java, but this is how I got my Python code to work.
Your example code was really helpful in getting my own implementation off the ground. Thanks!
After playing with it for a bit, I realized that the JavaScriptSerializer step is unnecessary since PostAsJsonAsync automatically serializes whatever object you pass to it. The double serialization prevents Marketo's API from processing the input.
Also, I agree with Jep that Postman is super helpful. But in the case of this error, Postman was working fine (using the contents of inputJsonString) but my C# code still didn't work properly. So I temporarily modified the code to return a dynamic object instead of a CreateLeadResponseResult. In debugging mode this allowed me to see fields that were discarded because they didn't fit the CreateLeadResponseResult type, which led me to the solution above.

ASP.NET MVC 4 return Json resulting in double json or empty data

I am getting either empty Json results or double json results and I don't know why yet?
base line:
http://learn.knockoutjs.com/mail?folder=Inbox
looks like this in chrome F12: {"id":"Inbox","mails":[{"id":1,......}
My Action:
public ActionResult Mail()
{
string qs = "";
foreach (var q in Request.QueryString)
{
qs += string.Format("{0}={1}&", q, Request.QueryString[q.ToString()]);
}
var proxyRequest = "http://learn.knockoutjs.com/mail?" + qs;
var request = WebRequest.Create(proxyRequest);
var response = (HttpWebResponse)request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var str = reader.ReadToEnd();
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(str);
//var json = JsonConvert.SerializeObject(data);
// Text Visualization looks good {"id":"Inbox","mails":[{"id":1,"from":"Abb....}
// no outside quotes, no escaped quotes
var res = Json(data, JsonRequestBehavior.AllowGet);
return res;
}
So basically I am proxying the call, but the question is why is the result coming back as either not filled in or double jsoned.
using chrome network trace the result of the above looks like.
[[[]],[[[[[]],[[]],[[]],[[]],[[]],...]
valid json, just empty.
when I change the code to look like this
var json = JsonConvert.SerializeObject(data);
// Text Visualization looks good {"id":"Inbox","mails":[{"id":1,"from":"Abb....}
// no outside quotes, no escaped quotes
var res = Json(json, JsonRequestBehavior.AllowGet);
return res;
Chrome network trace has doubled jsoned the data.
"{\"id\":\"Inbox\",\"mails\":[{\"id\":1,\"from\":\"Ab....}"
Since I don't know what the Json actually is, I did newton soft dynamic convert
JsonConvert.DeserializeObject
That may be the problem behind my empty response?
Any help would really be appreciated.
Thanks
Your first method is failing because Json() doesn't understand the dynamic object returned from your JSON reader.
Your second method is failing because Json() is serializing a pre-serialized string.
You can return pre-serialized JSON data using Content(jsonString, "application/json")

unable to update listitem external data column sharepoint 2010

I try update Extenal data column but it doesn't work, new value is not stored. (new value is visible on details form but not on list, rehreshing external data type does not return related external column values)
using (SPSite oSiteCollection = new SPSite("site.com"))
{
using (SPWeb oWebsite = oSiteCollection.OpenWeb("site.com"))
{
using (SPWeb oWebsiteRoot = oSiteCollection.RootWeb)
{
SPList docLib = oWebsiteRoot.Lists["list name"];
SPListItemCollection items = docLib.Items;
foreach (SPListItem item in items)
{
//item["n"] is external column data field
item["n"] = item["notice"].ToString();
item.UpdateOverwriteVersion();
}
}
}
}
Check using item.Update() insted of item.UpdateOverwriteVersion()
This has to do with the field type and is quite complicated to get right.
There is a free external data field migration/copy tool here:
http://rrfreeman.blogspot.com/2013/06/bcs-bdc-external-data-lookup-field.html
I included source code and links to relevant articles.