private async void Button_Click(object sender, RoutedEventArgs e) { if (CountryPhoneCode.SelectedItem != null) { var _id = Guid.NewGuid().ToString("N"); var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode; var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName; var _name = FullName.Text; var _phoneNumber = PhoneNumber.Text; var _password = Password.Password; var client = new HttpClient() { BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/") }; var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password="******"&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode); var serializer = new DataContractJsonSerializer(typeof(User)); var ms = new MemoryStream(); var user = serializer.ReadObject(ms) as User; Frame.Navigate(typeof(MainPage), user); } else { MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!"); await dialog.ShowAsync(); } }
private void ResponseCallback(IAsyncResult result) { var state = (List<object>) result.AsyncState; var googleRequest = (GooglePlaceSearchRequest) state[1]; if (result.IsCompleted) { try { var request = (HttpWebRequest)state[0]; var response = (HttpWebResponse)request.EndGetResponse(result); var responseStream = response.GetResponseStream(); var serializer = new DataContractJsonSerializer(typeof(GooglePlaceSearchResponse)); var googleSearchResponse = (GooglePlaceSearchResponse)serializer.ReadObject(responseStream); if (googleSearchResponse.Status == GoogleMapsSearchStatus.OK) SearchForPlacesAsyncCompleted(googleSearchResponse, googleRequest); else if (googleSearchResponse.Status == GoogleMapsSearchStatus.ZERO_RESULTS) SearchForPlacesAsyncNotFound(googleSearchResponse, googleRequest); } catch(Exception e) { if (SearchForPlacesAsyncFailed!= null) SearchForPlacesAsyncFailed(e.Message, e); } } else { if (SearchForPlacesAsyncFailed != null) SearchForPlacesAsyncFailed("For some reason request is not completed", null); } }
protected void Page_Load(object sender, EventArgs e) { this.RegisterAsyncTask( new PageAsyncTask( async ct => { IAuthorizationState authorization = await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), ct); if (authorization == null) { // Kick off authorization request var request = await client.PrepareRequestUserAuthorizationAsync(cancellationToken: ct); await request.SendAsync(); this.Context.Response.End(); } else { string token = authorization.AccessToken; AzureADClaims claimsAD = client.ParseAccessToken(token); // Request to AD needs a {tenantid}/users/{userid} var request = WebRequest.Create("https://graph.windows.net/" + claimsAD.Tid + "/users/" + claimsAD.Oid + "?api-version=0.9"); request.Headers = new WebHeaderCollection(); request.Headers.Add("authorization", token); using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { var serializer = new DataContractJsonSerializer(typeof(AzureADGraph)); AzureADGraph graphData = (AzureADGraph)serializer.ReadObject(responseStream); this.nameLabel.Text = HttpUtility.HtmlEncode(graphData.DisplayName); } } } })); }
private void RegisterClick(object sender, RoutedEventArgs e) { if (UsernameField.Text == "" || PasswordField.Password == "" || ConfirmPasswordField.Password == "") { ErrorField.Text = "All fields are mandatory."; return; } if (PasswordField.Password != ConfirmPasswordField.Password) { ErrorField.Text = "Password and Confirmation don't match."; return; } ErrorField.Text = ""; APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Register, "register"); Dictionary<string, string> dict = new Dictionary<string, string>() { {"username", UsernameField.Text}, {"password", PasswordField.Password} }; var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }); MemoryStream stream = new MemoryStream(); serializer.WriteObject(stream, dict); byte[] bytes = stream.ToArray(); string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); request.Execute(null, content); }
public static ExecutionResult<ListPostsModel> Execute() { try { var data = new ListPostsRequestData { AccessToken = DisqusOptions.GetInstance().AccessToken }; var request = BuildRequest("https://disqus.com/api/3.0/users/listActivity.json", HttpMethod.GET, data); var response = (HttpWebResponse)request.GetResponse(); using (var stream = new StreamReader(response.GetResponseStream())) { var serializer = new DataContractJsonSerializer(typeof(ListPostsModel)); var result = serializer.ReadObject(stream.BaseStream) as ListPostsModel; return ExecutionResult<ListPostsModel>.Create(result); } } catch (Exception e) { return ExecutionResult<ListPostsModel>.CreateError(e); } }
private PaymentReceipt DeserializeOrderBlob(PaymentReceipt receipt) { var ser = new DataContractJsonSerializer(typeof (PaymentReceipt)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(receipt.orderblob)); var deserializeReceipt = (PaymentReceipt) ser.ReadObject(ms); return deserializeReceipt; }
public static string ToJson(this object obj) { if (obj == null) { return "null"; } DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, obj); ms.Position = 0; string json = String.Empty; using (StreamReader sr = new StreamReader(ms)) { json = sr.ReadToEnd(); } //ms.Close(); return json; }
static void GetAccountInfo() { string respHTML = Util.HttpGet("https://api.dropboxapi.com/1/account/info", token); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person)); Person personinfo = (Person)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML))); Console.WriteLine(personinfo.display_name + " " + personinfo.email + " " + personinfo.quota_info.normal + "/" + personinfo.quota_info.quota); }
/// <summary> /// Deserialize String to Object /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Deserialize <T>(string json) { MemoryStream ms = null; T result = result = Activator.CreateInstance <T>(); try { DateTime startTime = DateTime.Now; ms = new MemoryStream(Encoding.UTF8.GetBytes(json)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(result.GetType()); /*System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = * new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType(), new List<Type>(), Int16.MaxValue, false, * new ZentoSurrogate(), false);*/ result = (T)serializer.ReadObject(ms); double time = (DateTime.Now - startTime).TotalSeconds; totalTimeExecution += time; } catch (Exception e) { LogHelper.LogError("exception while deserializing : " + e.Message + " - " + e.StackTrace); throw e; } finally { ms.Close(); ms.Dispose(); } return(result); }
/// <summary> /// Create a new PebbleBundle from a .pwb file and parse its metadata. /// </summary> /// <param name="bundle">The stream to the bundle.</param> /// <param name="zip">The zip library implementation.</param> public void Load(Stream bundle, IZip zip) { //TODO: This needs to be refactored, probably put into a Load method if (false == zip.Open(bundle)) throw new InvalidOperationException("Failed to open pebble bundle"); using (Stream manifestStream = zip.OpenEntryStream("manifest.json")) { if (manifestStream == null) { throw new InvalidOperationException("manifest.json not found in archive - not a valid Pebble bundle."); } var serializer = new DataContractJsonSerializer(typeof(BundleManifest)); Manifest = (BundleManifest)serializer.ReadObject(manifestStream); } HasResources = (Manifest.Resources.Size != 0); if (HasResources) { using (Stream resourcesBinary = zip.OpenEntryStream(Manifest.Resources.Filename)) { if (resourcesBinary == null) throw new PebbleException("Could not find resource entry in the bundle"); Resources = Util.GetBytes(resourcesBinary); } } LoadData(zip); }
/// <summary> /// This Function is used to write the Missing Targets Vs Missing Business Class Data Passed to corresponding FilePath /// </summary> /// <param name="LoginId"></param> /// <param name="MissingTargetsVsBusinessClass"></param> private void WriteMissingTargetsVsBusinessClassChartCacheFile(string LoginId, List <MissingTargetsVsBusinessClass> MissingTargetsVsBusinessClass) { const string FUNCTION_NAME = "WriteMissingTargetsVsBusinessClassChartCacheFile"; SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "Start for LoginId -" + LoginId); try { DepartureFormBusiness ObjDepartureFormBusiness = new DepartureFormBusiness(); BusinessUtil ObjBusinessUtil = new BusinessUtil(); string FilePath = string.Empty; string FolderPath = string.Empty; string MissingTargetsandBusinessClassData = string.Empty; ObjBusinessUtil.GetMissingTargetsVsBusinessClassChartsFilePath(LoginId, ref FilePath, ref FolderPath); Boolean IsFolderExists = System.IO.Directory.Exists(FolderPath); if (!IsFolderExists) { System.IO.Directory.CreateDirectory(FolderPath); } SICTLogger.WriteVerbose(CLASS_NAME, FUNCTION_NAME, "MissingTargetsVsBusinessClass Charts cache file for AirportLoginId- " + LoginId); using (var MemoryStream = new MemoryStream()) { var Serlizer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(List <MissingTargetsVsBusinessClass>)); Serlizer.WriteObject(MemoryStream, MissingTargetsVsBusinessClass); MissingTargetsandBusinessClassData = System.Text.Encoding.UTF8.GetString(MemoryStream.GetBuffer(), 0, Convert.ToInt32(MemoryStream.Length)); ObjDepartureFormBusiness.WriteToFile(MissingTargetsandBusinessClassData, FilePath); } } catch (Exception Ex) { SICTLogger.WriteException(CLASS_NAME, FUNCTION_NAME, Ex); } SICTLogger.WriteInfo(CLASS_NAME, FUNCTION_NAME, "End for LoginId -" + LoginId); }
public void SaveCategories(string db) { foreach (Category cat in categories) { //Get an image for every category string imageUrl = string.Empty; string products = Program.ExecuteGetCommand(string.Format(Program.SSProductQueryUrl, cat.id), string.Empty, string.Empty); using (Stream s = Program.GenerateStreamFromString(products)) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Products)); Products SSProducts = (Products)ser.ReadObject(s); imageUrl = SSProducts.products[0].images[2].url; } string query = "EXEC [stp_SS_SaveCategory] @id=N'" + cat.id.Replace("'", "\"") + "', @parentId=N'" + cat.parentId.Replace("'", "\"") + "', @name=N'" + cat.name.Replace("'", "\"") + "', @imageUrl='" + imageUrl.Replace("'", "\"") + "'"; SqlConnection myConnection = new SqlConnection(db); try { myConnection.Open(); using (SqlDataAdapter adp = new SqlDataAdapter(query, myConnection)) { SqlCommand cmd = adp.SelectCommand; cmd.CommandTimeout = 300000; cmd.ExecuteNonQuery(); } } finally { myConnection.Close(); } } }
/// <summary> /// This example uses the raw JSON string to create a POST /// request for sending one or more SMTP messages through Email-On-Demand. /// /// The JSON request generated by this sample code looks like this: /// ///{ /// "ServerId": "YOUR SERVER ID HERE", /// "ApiKey": "YOUR API KEY HERE", /// "Messages": [{ /// "Subject": "Email subject line for raw JSON example.", /// "TextBody": "The text portion of the message.", /// "HtmlBody": "<h1>The html portion of the message</h1><br/>Test", /// "To": [{ /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "Customer Name" /// }], /// "From": { /// "EmailAddress": "*****@*****.**", /// "FriendlyName": "From Address" /// }, /// }] ///} /// </summary> public static void SimpleInjectionViaStringAsJson( int serverId, string yourApiKey, string apiUrl) { // The client object processes requests to the SocketLabs Injection API. var client = new RestClient(apiUrl); // Construct the string used to generate JSON for the POST request. string stringBody = "{" + "\"ServerId\":\"" + serverId + "\"," + "\"ApiKey\":\"" + yourApiKey + "\"," + "\"Messages\":[{" + "\"Subject\":\"Email subject line for raw JSON example.\"," + "\"TextBody\":\"The text portion of the message.\"," + "\"HtmlBody\":\"<h1>The html portion of the message</h1><br/>Test\"," + "\"To\":[{" + "\"EmailAddress\":\"[email protected]\"," + "\"FriendlyName\":\"Customer Name\"" + "}]," + "\"From\":{" + "\"EmailAddress\":\"[email protected]\"," + "\"FriendlyName\":\"From Address\"" + "}," + "}]" + "}"; try { // Generate a new POST request. var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Json }; // Store the request data in the request object. request.AddParameter("application/json; charset=utf-8", stringBody, ParameterType.RequestBody); // Make the POST request. var result = client.ExecuteAsPost(request, "POST"); // Store the response result in our custom class. using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content))) { var serializer = new DataContractJsonSerializer(typeof (PostResponse)); var resp = (PostResponse) serializer.ReadObject(stream); // Display the results. if (resp.ErrorCode.Equals("Success")) { Console.WriteLine("Successful injection!"); } else { Console.WriteLine("Failed injection! Returned JSON is: "); Console.WriteLine(result.Content); } } } catch (Exception ex) { Console.WriteLine("Error, something bad happened: " + ex.Message); } }
public object Deserialize(WebFormatterDeserializationContext context, Type type) { if (context.ContentFormat != WebFormatterDeserializationContext.DeserializationFormat.Xml) throw new InvalidDataException("Data must be in xml format."); var serializer = new DataContractJsonSerializer(type); return serializer.ReadObject(context.XmlReader); }
public Response Get(UrlRequest request) { using (DbConnection connection = _factory.CreateConnection()) { connection.ConnectionString = _connectionString; connection.Open(); DbCommand cmd = connection.CreateCommand(); cmd.CommandText = "select [Value] from EmbedlyCache where [Key] = @key"; DbParameter pKey = cmd.CreateParameter(); pKey.DbType = DbType.Guid; pKey.Direction = ParameterDirection.Input; pKey.ParameterName = "key"; pKey.Value = request.CacheKey; cmd.Parameters.Add(pKey); var value = (string)cmd.ExecuteScalar(); if (value == null) return null; byte[] bytes = Encoding.Default.GetBytes(value); using (var ms = new MemoryStream(bytes)) { var serializer = new DataContractJsonSerializer(typeof (Response)); var response = (Response)serializer.ReadObject(ms); return response; } } }
private void AutenticateWNS() { try { // get an access token var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.Sid)); var urlEncodedSecret = HttpUtility.UrlEncode(this.Secret); var uri = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com", urlEncodedSid, urlEncodedSecret); var client = new WebClient(); client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string response = client.UploadString("https://login.live.com/accesstoken.srf", uri); // parse the response in JSON format OAuthToken token; using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response))) { var ser = new DataContractJsonSerializer(typeof(OAuthToken)); token = (OAuthToken)ser.ReadObject(ms); } this.accessToken = token.AccessToken; } catch (Exception ex) { //lblResult.Text = ex.Message; //lblResult.ForeColor = System.Drawing.Color.Red; throw ex; } }
public static GeocodeResponse MakeRequest(string addressNumber, string streetName, string cityName, string countryName) { string requestUrl = CreateGeocodeRequest(addressNumber, streetName, cityName, countryName); try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GeocodeResponse)); object objResponse = jsonSerializer.ReadObject(response.GetResponseStream()); GeocodeResponse jsonResponse = objResponse as GeocodeResponse; return jsonResponse; } } catch (Exception e) { Console.WriteLine(e.Message); return null; } }
//TODO: now it is assuming that the "generated" type name is the same, can we assume that? public IEnumerable<string> All(string typeName) { IProvider provider = ProviderConfiguration.GetProvider(typeName); Type type = provider.Type; IEnumerable objects = provider.All(); List<string> result = new List<string>(); foreach (var obj in objects) { using (MemoryStream stream = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(type); serializer.WriteObject(stream, obj); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { result.Add(reader.ReadToEnd()); } } } return result; //return // "{ \"<Id>k__BackingField\": \"patients/1\", \"<Name>k__BackingField\": \"Margol Foo\",\"Name\": \"Margol Foo\"}"; }
static string OfflineDownload(string url, string path) { string respHTML = Util.HttpPost("https://api.dropboxapi.com/1/save_url/auto/" + path + "?", "url=" + url, token); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(OfflineTask)); OfflineTask link = (OfflineTask)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML))); return link.job; }
/// <summary> /// Serialize object to String /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string Serialize <T>(T obj) { string result = null; MemoryStream ms = new MemoryStream(); try { DateTime startTime = DateTime.Now; /*System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = * new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType(), new List<Type>(), Int16.MaxValue, true, * new ZentoSurrogate(), false);*/ System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); serializer.WriteObject(ms, obj); result = Encoding.UTF8.GetString(ms.ToArray()); double time = (DateTime.Now - startTime).TotalSeconds; totalTimeExecution += time; } catch (Exception e) { LogHelper.LogError("exception while serializing : " + e.Message + " - " + e.StackTrace); throw e; } finally { ms.Dispose(); } return(result); }
static void GetDownloadLink() { string respHTML = Util.HttpPost("https://api.dropboxapi.com/1/media/auto/simple.txt", "", token); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DownloadLink)); DownloadLink link = (DownloadLink)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML))); Console.WriteLine(link.url); }
void clientCities_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { //MessageBox.Show(e.Result.); var serializer = new DataContractJsonSerializer(typeof(Cities)); Cities ipResult = (Cities)serializer.ReadObject(e.Result); List<AtrractionsList> citiesList = new List<AtrractionsList>(); for (int i = 0; i <= ipResult.addresses.Length - 1; i++) { Random k = new Random(); Double value = 0; String DefaultTitle = "Title"; String DefaultDescription = "Description"; String RandomType = ""; value = k.NextDouble(); DefaultTitle = ipResult.addresses[i].Name.ToString(); DefaultDescription = ipResult.addresses[i].ID.ToString(); RandomType = "Place" ; citiesList.Add(new AtrractionsList(DefaultTitle, DefaultDescription, RandomType)); } listBoxCities.ItemsSource = citiesList; listBoxAttractions.ItemsSource = citiesList; }
/// <summary> /// Загрузка из локального хранилища настроек в формате JSON /// </summary> public async void LoadSettingsAsync() { StorageFile settingsFile = null; bool isExists = true; try { settingsFile = await StorageFile.GetFileFromPathAsync(Constants.SettingsFile); } catch (FileNotFoundException) { isExists = false; } if (!isExists) { Settings = new SettingsVariables(); } else { using (var fileStream = await settingsFile.OpenStreamForReadAsync()) { MemoryStream memoryStream = new MemoryStream(); await fileStream.CopyToAsync(memoryStream); memoryStream.Position = 0; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SettingsVariables)); Settings = (SettingsVariables)serializer.ReadObject(memoryStream); } } }
void HandleResponse(IAsyncResult ar) { try { WebResponse response = ((HttpWebRequest)ar.AsyncState).EndGetResponse(ar); var serializer = new DataContractJsonSerializer(typeof(respuesta)); var resp = (respuesta)serializer.ReadObject(response.GetResponseStream()); Dispatcher.BeginInvoke(() => { this.DataContext = resp; PhoneApplicationService.Current.State["respuesta"] = resp; }); } catch (Exception ex) { Dispatcher.BeginInvoke(() => { MessageBox.Show("Tuvimos problema accediendo al internet (" + uri + "), favor verificar."); NavigationService.GoBack(); }); } }
/// <summary> /// Get Presence information per user. /// </summary> private async void AsyncPresence() { var client = new HttpClient(); var uri = new Uri(string.Format(Configurations.PresenceUrl, Configurations.ApiKey, _currentMember.id)); var response = await client.GetAsync(uri); var statusCode = response.StatusCode; switch (statusCode) { // TODO: Error handling for invalid htpp responses. } response.EnsureSuccessStatusCode(); var theResponse = await response.Content.ReadAsStringAsync(); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(theResponse))) { var serializer = new DataContractJsonSerializer(typeof(PresenceRoot)); var presenceObject = serializer.ReadObject(ms) as PresenceRoot; // This will allow the application to toggle the presence indicator color. if (presenceObject != null && presenceObject.ok && presenceObject.IsActive()) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { StatusIndicator.Fill = new SolidColorBrush(Color.FromArgb(255, 127, 153, 71)); }); } // TODO: Add more code for bad replies or invalid requests. } }
protected override void OnPreRender(EventArgs e) { if (!this.ReadOnlyMode && !UseBrowseTemplate) { string jsonData; using (var s = new MemoryStream()) { var workData = ContentType.GetContentTypes() .Select(n => new ContentTypeItem {value = n.Name, label = n.DisplayName, path = n.Path, icon = n.Icon}) .OrderBy(n => n.label); var serializer = new DataContractJsonSerializer(typeof (ContentTypeItem[])); serializer.WriteObject(s, workData.ToArray()); s.Flush(); s.Position = 0; using (var sr = new StreamReader(s)) { jsonData = sr.ReadToEnd(); } } // init control happens in prerender to handle postbacks (eg. pressing 'inherit from ctd' button) var contentTypes = _contentTypes ?? GetContentTypesFromControl(); InitControl(contentTypes); var inherit = contentTypes == null || contentTypes.Count() == 0 ? 0 : 1; UITools.RegisterStartupScript("initdropboxautocomplete", string.Format("SN.ACT.init({0},{1})", jsonData, inherit), this.Page); } base.OnPreRender(e); }
protected void Page_Load(object sender, EventArgs e) { Status.RecordHit(); String numFacesString = Request.QueryString["numFaces"]; int numFaces = numFacesString == null ? 20 : int.Parse(numFacesString); if (numFaces > 100) numFaces = 100; var faces = FacesLite.GetRandomFaces(numFaces).ToArray(); Message mess = new Message(); mess.FaceImages = new List<FaceImage>(); for (int i = 0; i < faces.Count(); i++) { FaceImage fi = new FaceImage() { ukey = faces[i].Item1, path = faces[i].Item2 }; mess.FaceImages.Add(fi); } DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FaceImage[])); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, mess.FaceImages.ToArray()); string json = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); Response.Clear(); Response.ContentType = "application/json; charset=utf-8"; Response.Write(json); Response.End(); }
/// <summary> /// Serializes a list of OracleObjectPermissionSet objects to a JSON-encoded string. /// </summary> /// <param name="permissionSetArray">The list of OracleObjectPermissionSet objects to serialize.</param> /// <returns>The list serialized as a string.</returns> public String Serialize(List<Containers.OracleObjectPermissionSet> permissionSetArray) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Containers.OracleObjectPermissionSet>)); MemoryStream tempStream = new MemoryStream(); serializer.WriteObject(tempStream, permissionSetArray); return ConvertMemoryStreamToString(tempStream); }
public void handleReply(string json) { if (json == null) { Deployment.Current.Dispatcher.BeginInvoke(() => { progressBar1.IsIndeterminate = false; MessageBox.Show("Unable to communicate with server."); }); return; } DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(StudentResponse)); student = dcjs.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json))) as StudentResponse; Deployment.Current.Dispatcher.BeginInvoke(() => { this.tStudentName.Text = student.nome; StudentProfileModel.Items[0].LineTwo = student.codigo; StudentProfileModel.Items[1].LineTwo = student.email; StudentProfileModel.Items[2].LineTwo = student.email_alternativo; StudentProfileModel.Items[3].LineTwo = student.curso_nome; StudentProfileModel.Items[4].LineTwo = student.estado; StudentProfileModel.Items[5].LineTwo = student.ano_curricular.ToString(); TiltEffect.SetIsTiltEnabled(lbItems.ItemContainerGenerator.ContainerFromIndex(1), true); TiltEffect.SetIsTiltEnabled(lbItems.ItemContainerGenerator.ContainerFromIndex(2), true); if (student.email_alternativo == null) StudentProfileModel.Items.RemoveAt(2); this.lbItems.SelectionChanged += new SelectionChangedEventHandler(sendEmailHandler); progressBar1.IsIndeterminate = false; }); }
/// <summary> /// Serializes a list of strings to a JSON-encoded string. /// </summary> /// <param name="strings">The list of strings to serialize.</param> /// <returns>The list serialized as a string.</returns> public String Serialize(List<String> strings) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<String>)); MemoryStream tempStream = new MemoryStream(); serializer.WriteObject(tempStream, strings); return ConvertMemoryStreamToString(tempStream); }
public void CanRetrieveSimpleResourceDetails() { using (var host = new InMemoryHost(new SampleApi.Configuration())) { var request = new InMemoryRequest { Uri = new Uri("http://localhost/api-docs/simple"), HttpMethod = "GET", Entity = {ContentType = MediaType.Json} }; request.Entity.Headers["Accept"] = "application/json"; var response = host.ProcessRequest(request); var statusCode = response.StatusCode; Assert.AreEqual(200, statusCode); Assert.IsTrue(response.Entity.ContentLength>0); response.Entity.Stream.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(ResourceDetails)); var resourceDetails = (ResourceDetails) serializer.ReadObject(response.Entity.Stream); Assert.IsNotNull(resourceDetails); } }
/// <summary> /// Serializes a ValidationResult to a JSON-encoded string. /// </summary> /// <param name="validationResult">The ValidationResult to serialize.</param> /// <returns>The ValidationResult serialized as a string.</returns> public String Serialize(ValidationResult validationResult) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ValidationResult)); MemoryStream tempStream = new MemoryStream(); serializer.WriteObject(tempStream, validationResult); return ConvertMemoryStreamToString(tempStream); }
static void Main(string[] args) { //DesktopUtil.Instance.GetChangedImages(); WebDesktopTCPServer server = new WebDesktopTCPServer(); server.Listen(); long now = System.DateTime.Now.Ticks / 10000; while (true) { now = System.DateTime.Now.Ticks / 10000; WebDesktopTCPClient CLIENT = new WebDesktopTCPClient("andy-PC", 3390, 3391); string base64String = CLIENT.GetSliceImages(); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(base64String)); DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DesktopSnapshotList)); DesktopSnapshotList ss = ser.ReadObject(ms) as DesktopSnapshotList; // Console.WriteLine((System.DateTime.Now.Ticks / 10000 - now) + "ms"); for (int i = 0; i < ss.Count; i++) { // Console.WriteLine(ss[i].Width + " and " + ss[i].Height); } // Console.WriteLine(ss.Count); Thread.Sleep(2000); } }
public static string Serialize<T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); string retVal = Encoding.Default.GetString(ms.ToArray()); ms.Dispose(); return retVal; }
/// <summary> /// 单个对象转JSON /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Json2Obj <T>(string json) { T obj = Activator.CreateInstance <T>(); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); return((T)serializer.ReadObject(ms)); } }
/*public static bool DeserializeJson<T>(string json, ref T t) * { * using (var memoryStream = new MemoryStream()) * { * byte[] jsonBytes = Encoding.UTF8.GetBytes(json); * memoryStream.Write(jsonBytes, 0, jsonBytes.Length); * memoryStream.Seek(0, SeekOrigin.Begin); * using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null)) * { * var serializer = new DataContractJsonSerializer(typeof(T)); * try * { * t = (T)serializer.ReadObject(jsonReader); * } * catch * { * return false; * } * } * } * return true; * }*/ static public T DeserializeJson <T>(string json) { var instance = Activator.CreateInstance <T>(); using (var ms = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(json))) { var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(instance.GetType()); return((T)serializer.ReadObject(ms)); } }
public static string To <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); string retVal = Encoding.Default.GetString(ms.ToArray()); } return(retVal); }
public static T Deserialize<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); return obj; } }
public static string GetJsonString <T>(T value) { System.Runtime.Serialization.Json.DataContractJsonSerializer json = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); MemoryStream stream = new MemoryStream(); json.WriteObject(stream, value); string str = System.Text.Encoding.UTF8.GetString(stream.ToArray()); return(str); }
///// <summary> ///// JSON字符串转化为对象 ///// </summary> ///// <param name="obj"></param> ///// <returns></returns> //public static T ToObject<T>(this string obj) //{ // JavaScriptSerializer Serializer = new JavaScriptSerializer(); // return Serializer.Deserialize<T>(obj); //} /// <summary> /// 对象转化为JSON字符串 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string Serialize <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); System.IO.MemoryStream ms = new System.IO.MemoryStream(); serializer.WriteObject(ms, obj); string retVal = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Dispose(); return(retVal); }
public static object Deserialize(Stream streamObject, Type serializedObjectType) { if ((serializedObjectType == null) || (streamObject == null)) { return(null); } System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(serializedObjectType); return(serializer.ReadObject(streamObject)); }
public void ReadExternal(IDataInput input) { string json = input.ReadUTF(); DataContractJsonSerializer serialiser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(BroadcastNotification)); Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(json)); BroadcastNotification notification = (BroadcastNotification)serialiser.ReadObject(stream); broadcastMessages = notification.broadcastMessages; }
/// <summary> /// Function to deserialize JSON string using DataContractJsonSerializer /// </summary> /// <typeparam name="RemoteContextType">RemoteContextType Generic Type</typeparam> /// <param name="jsonString">string jsonString</param> /// <returns>Generic RemoteContextType object</returns> public static RemoteContextType DeserializeJsonString <RemoteContextType>(string jsonString) { //create an instance of generic type object RemoteContextType obj = Activator.CreateInstance <RemoteContextType>(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = (RemoteContextType)serializer.ReadObject(ms); ms.Close(); return(obj); }
public T Deserialize <T>(string source, Encoding encoding) { byte[] bytes = encoding.GetBytes(source); XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max); var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var graph = (T)serializer.ReadObject(jsonReader); jsonReader.Close(); return(graph); }
public void Active() { string url = @"http://localhost:59533/Service1.svc/GetR"; B bObj = new B(); bObj.s2 = "StringToSend"; // var json = new JavaScriptSerializer().Serialize(bObj); string json; using (var ms = new MemoryStream()) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(B)); ser.WriteObject(ms, bObj); json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)); } json = "{a:b}"; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "text/plain"; byte[] byteArray = Encoding.UTF8.GetBytes(json); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); // ASCIIEncoding encoding = new ASCIIEncoding(); // byte[] byteArray = encoding.GetBytes(json); dataStream.Write(byteArray, 0, byteArray.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string result; using (Stream data = response.GetResponseStream()) using (var reader = new StreamReader(data)) { result = reader.ReadToEnd(); } } catch (Exception exp) { string s = exp.Message; } }
public static string ToJson <T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer ds = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ds.WriteObject(ms, obj); string strJSON = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(strJSON); }
/// <summary> /// Json转List<T> /// </summary> /// <param name="json"></param> /// <param name="t"></param> /// <returns></returns> public static Object Json2Obj(String json, Type t) { try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t); using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(json))) { return(serializer.ReadObject(ms)); } } catch { return(null); } }
/// <summary> /// JSON字符串转化为对象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json"></param> /// <returns></returns> public static T Deserialize <T>(string json) { T obj = Activator.CreateInstance <T>(); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); obj = (T)serializer.ReadObject(ms); ms.Close(); ms.Dispose(); return(obj); }
static void Main() { var z = new Person() { Name = "Taro", Age = 18, Type = "Student" }; var ds = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Person)); using (var sw = File.Create("test.json")) ds.WriteObject(sw, z); System.Console.WriteLine(File.ReadAllText("test.json")); }
public string ToJsonString() { var dk = new System.Runtime.Serialization.Json.DataContractJsonSerializer(this.GetType()); var ms = new MemoryStream(); dk.WriteObject(ms, this); var rdr = new StreamReader(ms); ms.Position = 0; return(rdr.ReadToEnd()); }
public string MicrosoftTranslate(string input) { string clientID = "translatedhruba_123"; string clientSecret = "sJnnJgpG12Rysf7KxjeBpY5ulaCKSdaJYot7adFzXWY="; String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"; String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1} &scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret)); System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails); webRequest.ContentLength = bytes.Length; string translatedtext = ""; try { using (System.IO.Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } System.Net.WebResponse webResponse = webRequest.GetResponse(); System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken)); AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream()); string headerValue = "Bearer " + token.access_token; string txtToTranslate = input; string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=no&to=en"; System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri); translationWebRequest.Headers.Add("Authorization", headerValue); System.Net.WebResponse response = null; response = translationWebRequest.GetResponse(); System.IO.Stream stream = response.GetResponseStream(); System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode); System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument(); xTranslation.LoadXml(translatedStream.ReadToEnd()); translatedtext = xTranslation.InnerText; } catch (Exception ex) { ExceptionHandling.errorMessage = ex.ToString(); } return(translatedtext); }
public void LoginResult(string responseStr) { //多网络 if (responseStr.IndexOf("CompanyName") > 0) { MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseStr)); var deserializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(System.Collections.Generic.List <UserInfo>)); //反序列化本地文件为List集合 var list = (System.Collections.Generic.List <UserInfo>)deserializer.ReadObject(ms); ms.Close(); ms.Dispose(); //前台 Dispatcher.BeginInvoke(() => { netsImtes.ItemsSource = list; manyProject.Visibility = Visibility.Visible; loginAnimate.Visibility = Visibility.Collapsed; }); } else { UserInfo login = new UserInfo(); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseStr)); DataContractJsonSerializer ser = new DataContractJsonSerializer(login.GetType()); login = ser.ReadObject(ms) as UserInfo; login.CompanyName = companyName; UserDataManager.SaveUserInformation(login); ms.Close(); ms.Dispose(); if (login.type == 1 || login.type == 7 || login.type == 8) { Dispatcher.BeginInvoke(() => { MessageBox.Show(login.error); //if (login.type==7) //{ // LoginViewModel.GetChkCode((x) => { // }); // Uri uri = new Uri("https://api.mingdao.com/code.aspx?0.7088238715659827", UriKind.Absolute); // vImg.Source = new BitmapImage(uri); // vBox.Visibility = Visibility.Visible; //} loginAnimate.Visibility = Visibility.Collapsed; }); } else { int codeindex = login.url.IndexOf("code") + 5; string code = login.url.Substring(codeindex); LoginViewModel.GetUserToken(code, GetUserTokenResult); } } }
/// <summary>Deserializes the JSON string as a specified object</summary> /// <typeparam name="T">Specified type of target object</typeparam> /// <param name="jsonString">JSON string source</param> /// <returns>Object of specied type</returns> public static T Deserialize <T>(string jsonString) { using (System.IO.MemoryStream _Stream = new System.IO.MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { try { var _Serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); return((T)_Serializer.ReadObject(_Stream)); } catch (Exception) { throw; } } }
/// <summary> /// List<T>转Json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> public static string Obj2Json <T>(T data) { try { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType()); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, data); return(Encoding.UTF8.GetString(ms.ToArray())); } } catch { return(null); } }
public static object Deserialize(Stream s, Type type) { if (s == null || type == null || type == null) { throw new ArgumentNullException(); } if (!s.CanRead) { throw new ArgumentException(); } R.DataContractJsonSerializer serializer = new R.DataContractJsonSerializer(type); return(serializer.ReadObject(s)); }
public static void Serialize(Stream s, object value) { if (value == null || s == null) { throw new ArgumentNullException(); } if (!s.CanWrite) { throw new ArgumentNullException(); } R.DataContractJsonSerializer serializer = new R.DataContractJsonSerializer(value.GetType()); serializer.WriteObject(s, value); }
public static T Deserialize <T>(string json) { var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); memoryStream.Position = 0; var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var serializedObject = (T)serializer.ReadObject(memoryStream); memoryStream.Dispose(); return(serializedObject); }
public string Serialize <T>(object objectToSerialize, Encoding encoding) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var ms = new MemoryStream(); ser.WriteObject(ms, objectToSerialize); string str = encoding.GetString(ms.ToArray()); ms.Close(); ms.Dispose(); return(str); }
/// <summary> /// JSON反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static T Parse <T>(string source) { if (!string.IsNullOrWhiteSpace(source)) { using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(source))) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T)); var obj = ser.ReadObject(ms); return((T)obj); } } return(default(T)); }
/// <summary> /// JSON反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static object Parse(Type t, string source) { if (!string.IsNullOrWhiteSpace(source)) { using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(source))) { var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t); var obj = ser.ReadObject(ms); return(obj); } } return(null); }