How to serialize an object in windows phone 7 - json

How to convert an object to JSON data in windows phone. In web application I have used following code
JavaScriptSerializer serializer = new JavaScriptSerializer();
string stringData = serializer.Serialize(object);
I want to get the same output as that of the above code in windows phone 7.

JavaScriptSerializer is not supported on Windows Phone. An alternative is to use JSON.NET (you can add it via NuGet).
The code will then look like this:
string stringData = JsonConvert.SerializeObject(object);

firrst you need to download Newtonsoft.Json dll for parse web serevice
Just follow bellow step
Step1: Add Service References by right click on add References.
Step2: Now put your web service link on Service References and press go button, And also add Namespace of service Reference
Step3: Now add using Newtonsoft.Json.Linq; name space in your .cs file
Step4: Now add bellow code in your cs file
WhatsupServices.WhatsUpServiceSoapClient ws = new WhatsupServices.WhatsUpServiceSoapClient();
ws.ContactUsJSONCompleted += ws_ContactUsJSONCompleted;
ws.ContactUsJSONAsync(txtContactUsName.Text, txtContactUsPhone.Text, txtContactUsEmail.Text, txtContactUsComment.Text);
step6: now genrate your resopnce method
void ws_ContactUsJSONCompleted(object sender, dynamic e)
{
if (e.Error != null)
{
MessageBox.Show(LogIn.NetworkBusyMsg, LogIn.MsgHdr, MessageBoxButton.OK);
busyIndicator.IsRunning = false;
}
else
{
busyIndicator.IsRunning = false;
string Result = e.Result;
JObject obj = JObject.Parse(Result);
string ResultCode = (string)obj["ResultCode"];
string ResponceMessage = (string)obj["ResponseMessage"];
if (ResultCode == "1")
{
MessageBox.Show("Thank you for your message. We'll get back to you soon.", LogIn.MsgHdr, MessageBoxButton.OK);
NavigationService.GoBack();
}
else
{
}
}
}
Hope it will help you.
If any query than comment here.I wll help you

Related

Get thymeleaf html file with all includes

Hy guys, I'm new to Thymeleaf, my goal is to have an endpoint which returns a String with the content of a html file. Should be easy, but that file html contains thymeleaf code and uses fragments from others files so using Files.readString(path) does not reach the goal.
How can I include them (I want to only include fragments, I don't have to process the file)?
That's what I've done till now:
#GetMapping(path = "/get-template-html")
public String getTemplateHTMLEndpoint() {
String templateHtml = "Problems reading template.html";
try {
String stringPath = new ClassPathResource("templates/template.html").getFile().getPath();
Path path = Path.of(stringPath);
templateHtml = Files.readString(path);
} catch (IOException e) {
e.printStackTrace();
}
return templateHtml;
}
But in another method where I process the file passing the context I got an error about the fragment "footer::footer"
String templateHtml = callGetTemplateHTMLEndPoint();
StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
stringTemplateResolver.setTemplateMode(TemplateMode.HTML);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(stringTemplateResolver);
Context context = new Context();
context.setVariable("expenseReportPdf", expenseReportPdf);
context.setVariable("expensePdf", expensePdfList);
context.setVariable("expenseImg", jpgFile);
context.setVariable("amountCompanyCurrency", amountCompanyCurrency);
context.setVariable("expenseIncurredList", expenseIncurredList);
context.setVariable("expenseRiepiloghiList",expenseRiepiloghiList);
context.setVariable("advancePayBigDecimal", advancePayBigDecimal);
context.setVariable("dailyAllowanceList", dailyAllowanceList);
context.setVariable("dailyAllowanceFlag", dailyAllowanceFlag);
context.setVariable("logo",logo);
context.setVariable("logoSmartex",logoSmartex);
String renderedHtmlContent = templateEngine.process(templateHtml, context);
If you created a "standard" Spring Boot with Thymeleaf project (e.g. via https://start.spring.io), then the templates are automatically resolved if you put them in src/main/resources/templates
So if you created src/main/resources/templates/templates.html, then you can create a controller that will use that template like this:
#Controller
#RequestMapping("/")
public class MyController {
#GetMapping("/get-template-html")
public String getTemplateHtml() {
return "templates"; // name of your template file without the .html extension
}
}
If you start the application and access http://localhost:8080/get-template-html, you should see the HTML of the template.

How to upload a profile picture and update it in identity asp.net core 3

I want to upload a profile picture in the identity user and update it in account management. if there is any post with good examples for asp.net core please give me links.
I did it myself with FileForm Method. First You Have to Add string property in User Class(https://learn.microsoft.com/en-us/aspnet/core/security/authentication/add-user-data?view=aspnetcore-3.0&tabs=visual-studio).
public string Avatar { get; set; }
and then, update the Manage/Index files by following the documentation. Now, How to create the file upload system? I did like the code below. but if i need to change something for security, please don't forget to help.
if (Input.Avatar != null)
{
string existfile = Path.Combine(hostingEnvironment.WebRootPath, "uploads", user.Avatar);
System.IO.File.Delete(existfile);
}
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads", "avatar");
var filePath = Path.Combine(uploads, fileName);
this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
user.Avatar = fileName; // Set the file name
GetUniqueFileName Class after the PostAsync class:
private string GetUniqueName(string fileName)
{
fileName = Path.GetFileName(fileName);
return Path.GetFileNameWithoutExtension(fileName)
+ "_" + Guid.NewGuid().ToString().Substring(0, 4)
+ Path.GetExtension(fileName);
}
You also have to add the IWebHostEnvironment dependency injection and update the cshtml form with multipart/form-data enctype. Don't forget to follow the .net documentation rules also. Good Luck!

WinRT XmlAnyElement and Serialization

We have a Windows Store application that communicates with our server using XML for requests / responses and are serialized with the XmlSerializer. The issue we are encountering is that one of our types can contain arbitrary XML as one of its properties. In non WinRT applications, the usage would have been.
public sealed ItemExtension {
[XmlAttribute("source")]
public string Source {get;set;}
[XmlAnyElement]
public XmlElement[] Data {get;set;}
}
This would allow us to have XML in our database like
<extension source="foo"><randomXml><data/></randomXml></extension>
In WinRT, XmlElement is not included, System.Xml.XmlElement does not exist and the Windows.Data.Xml.Dom.XmlElement is not compatible. Documentation mentions XElement, but XElement is not a supported WinRT type so the WinRT project won't compile if I try using it.
Is this a bug with Windows Store applications or is there a sufficient work around?
Thanks.
So far I've only found a hack to get this working. If we use
[XmlAnyElement]
public object Data {get;set;}
This will properly will properly deserialize existing data. In the debugger when inspecting it, it is of type System.Xml.XmlElement, which isn't exposed in WinRT. So there's no way to directly set this. Since we figured out that XmlSerializer can instantiate and access System.Xml.XmlElement, we use it to handle setting it by taking in an object/xml snippet, wrapping it in container xml for a wrapper type that contains [XmlAnyElement] and calling Deserialize on it to have the XmlSerializer instantiate an XmlElement, which can then be set on the target object you wish to serialize.
For getting data, since trying to read this property throws an exception in the UI layer, and trying to access InnerXml/OuterXml throw an exception as well, we are left with using the XmlSerializer to Serialize the XmlElement back into a string, and then can use that however you want.
public sealed class XmlAnyElementContainer
{
[XmlAnyElement]
public object Data { get; set; }
}
public void SetData(object extensionObject)
{
var objectSerializer = new XmlSerializer(extensionObject.GetType());
var settings = new XmlWriterSettings()
{
Indent = false,
OmitXmlDeclaration = true
};
var sb = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(sb, settings))
{
objectSerializer.Serialize(xmlWriter, extensionObject);
}
string objectXml = sb.ToString();
string newXml = "<XmlAnyElementContainer>" + objectXml + "</XmlAnyElementContainer>";
var xmlAnySerializer = new XmlSerializer(typeof(XmlAnyElementContainer));
using (var sr = new StringReader(newXml))
{
[TargetPropertyToSerialize] = (xmlAnySerializer.Deserialize(sr) as XmlAnyElementContainer).Data;
}
}

How to export data from LinqPAD as JSON?

I want to create a JSON file for use as part of a simple web prototyping exercise. LinqPAD is perfect for accessing the data from my DB in just the shape I need, however I cannot get it out as JSON very easily.
I don't really care what the schema is, because I can adapt my JavaScript to work with whatever is returned.
Is this possible?
A more fluent solution is to add the following methods to the "My Extensions" File in Linqpad:
public static String DumpJson<T>(this T obj)
{
return
obj
.ToJson()
.Dump();
}
public static String ToJson<T>(this T obj)
{
return
new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(obj);
}
Then you can use them like this in any query you like:
Enumerable.Range(1, 10)
.Select(i =>
new
{
Index = i,
IndexTimesTen = i * 10,
})
.DumpJson();
I added "ToJson" separately so it can be used in with "Expessions".
This is not directly supported, and I have opened a feature request here. Vote for it if you would also find this useful.
A workaround for now is to do the following:
Set the language to C# Statement(s)
Add an assembly reference (press F4) to System.Web.Extensions.dll
In the same dialog, add a namespace import to System.Web.Script.Serialization
Use code like the following to dump out your query as JSON
new JavaScriptSerializer().Serialize(query).Dump();
There's a solution with Json.NET since it does indented formatting, and renders Json dates properly. Add Json.NET from NuGet, and refer to Newtonsoft.Json.dll to your “My Extensions” query and as well the following code :
public static object DumpJson(this object value, string description = null)
{
return GetJson(value).Dump(description);
}
private static object GetJson(object value)
{
object dump = value;
var strValue = value as string;
if (strValue != null)
{
var obj = JsonConvert.DeserializeObject(strValue);
dump = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
}
else
{
dump = JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented);
}
return dump;
}
Use .DumpJson() as .Dump() to render the result. It's possible to override more .DumpJson() with different signatures if necessary.
As of version 4.47, LINQPad has the ability to export JSON built in. Combined with the new lprun.exe utility, it can also satisfy your needs.
http://www.linqpad.net/lprun.aspx

Is there a way to store instances of own classes in the ApplicationSettings of a Windows Store app?

In a Windows Store app I can only store WinRT types in the ApplicationSettings, according to the documentation. For roamed settings that should be held together I can use ApplicationDataCompositeValue. Trying to store an instance of an own class or struct results in an Exception with the message " WinRT information: Error trying to serialize the value to be written to the application data store. Additional Information: Data of this type is not supported". The term "trying to serialize" indicates that there must be some way so serialize a type for the application data API.
Does anyone know how I could achieve that?
I tried DataContract serialization but it did not work.
I think custom/own types are not supported.
See http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx:
"The Windows Runtime data types are supported for app settings."
But you can serialize your objects to XML and save as string... (see code below)
public static string Serialize(object obj)
{
using (var sw = new StringWriter())
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
public static T Deserialize<T>(string xml)
{
using (var sw = new StringReader(xml))
{
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(sw);
}
}
https://github.com/MyToolkit/MyToolkit/blob/master/src/MyToolkit/Serialization/XmlSerialization.cs
Check out this class too:
https://github.com/MyToolkit/MyToolkit/wiki/XmlSerialization
Disclaimer: The above links are from my project