public async Task WriteAuditRecord(string resourceType, CloudStorageAccount storageAccount) { var entry = new AuditEntry( this, await AuditActor.GetCurrentMachineActor()); // Write the blob to the storage account var client = storageAccount.CreateCloudBlobClient(); var container = client.GetContainerReference("auditing"); await container.CreateIfNotExistsAsync(); var blob = container.GetBlockBlobReference( resourceType + "/" + this.GetPath() + "/" + DateTime.UtcNow.ToString("s") + "-" + this.GetAction().ToLowerInvariant() + ".audit.v1.json"); if (await blob.ExistsAsync()) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, Strings.Package_DeleteCommand_AuditBlobExists, blob.Uri.AbsoluteUri)); } byte[] data = Encoding.UTF8.GetBytes( JsonFormat.Serialize(entry)); await blob.UploadFromByteArrayAsync(data, 0, data.Length); }
public static async Task <CloudBlockBlob> UploadJsonBlob(this CloudBlobContainer self, string path, object content) { CloudBlockBlob blob = null; try { blob = self.GetBlockBlobReference(path); blob.Properties.ContentType = "application/json"; await blob.UploadTextAsync(JsonFormat.Serialize(content)); } catch (StorageException stex) { if (stex.RequestInformation != null && stex.RequestInformation.ExtendedErrorInformation != null && (stex.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.ContainerNotFound || stex.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.BlobNotFound)) { // Ignore the error } else { throw; } } return(blob); }
public frmKeyValueDetials(string key, string value, ArrayList serverList, DataTable dt, int rowIndex) { InitializeComponent(); this.txtKey.Text = key; this.txtKey.Enabled = false; this.txtValue.Text = value; memcacheServer = serverList; this.groupBox1.Text = "Key:" + key; this.Text = "Key:" + key; oldValue = value; dtSource = dt; posIndex = rowIndex; if (posIndex == 0) { this.lbPrev.Enabled = false; } if (posIndex == dtSource.Rows.Count - 1) { this.lbNext.Enabled = false; } string errmsg = string.Empty; if (JsonFormat.CanFormatJson(value, out errmsg)) { this.lbFormat.Enabled = true; } else { this.lbFormat.Enabled = false; } this.lbCancel.Enabled = false; }
public void MergeFrom(FileAccessLog other) { if (other == null) { return; } if (other.Path.Length != 0) { Path = other.Path; } switch (other.AccessLogFormatCase) { case AccessLogFormatOneofCase.Format: Format = other.Format; break; case AccessLogFormatOneofCase.JsonFormat: if (JsonFormat == null) { JsonFormat = new global::Google.Protobuf.WellKnownTypes.Struct(); } JsonFormat.MergeFrom(other.JsonFormat); break; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); }
public void Load() { if (m_UICreator.m_OutputLanguage != OutputLanguage.JSON) { return; } string path = Path.Combine(Application.dataPath, "JSONInput"); string[] files = Directory.GetFiles(path); if (files.Length == 0) { return; } StreamReader fs = new StreamReader(files[0]); string s = fs.ReadToEnd(); fs.Close(); JsonFormat element = JsonUtility.FromJson <JsonFormat>(s); foreach (JsonElement je in element.Elements) { GameElement ge = m_Factory.Create(je.Type.ToString()); ge.SetOptions(je.Options); ge.transform.SetParent(m_ElementParent, true); ge.gameObject.transform.position = je.Position; } }
public override async Task <SecretStore> Create(string store, IEnumerable <string> allowedUsers) { // Create the root folder if it does not exist if (!Directory.Exists(_rootFolder)) { Directory.CreateDirectory(_rootFolder); } // Check if there is already a secret store here string storeDirectory = Path.Combine(_rootFolder, store); if (Directory.Exists(storeDirectory)) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, Strings.DpapiSecretStoreProvider_StoreExists, store)); } Directory.CreateDirectory(storeDirectory); // Create the directory and the metadata file string metadataFile = Path.Combine(storeDirectory, "metadata.v1.pjson"); var metadata = new SecretStoreMetadata() { AllowedUsers = allowedUsers, Datacenter = store }; // Encrypt and Save it! var protector = CreateProtector(allowedUsers, MetadataPurpose); await WriteSecretFile(metadataFile, JsonFormat.Serialize(metadata), protector); return(new DpapiSecretStore(storeDirectory, metadata)); }
private static object AttributeToJSONType(object attribute, JsonFormat jsonFormat, bool showFriendlyNames = false) { if (jsonFormat == JsonFormat.Legacy) { return(AttributeToBaseType(attribute, showFriendlyNames)); } if (attribute is AliasedValue av) { return(AttributeToJSONType(av.Value, jsonFormat, showFriendlyNames)); } else if (attribute is EntityReference er) { if (showFriendlyNames) { return(er.Name); } else { return(er.Id); } } else if (attribute is EntityReferenceCollection erc) { // What is the best format for this? Can't see where this is returned by WebAPI so currently making up our own format // This currently generates the format: // { // "logicalname1": [ "id1", "id2" ], // "logicalname2": [ "id3", "id4" ] // } return(erc.GroupBy(e => e.LogicalName) .ToDictionary(g => g.Key, g => g.Select(e => e.Id).ToArray())); } else if (attribute is EntityCollection ec) { return(ec.Entities .Select(e => ToJSONObject(e, jsonFormat)) .ToArray()); } else if (attribute is OptionSetValue osv) { return(osv.Value); } else if (attribute is OptionSetValueCollection osvc) { return(osvc.Select(o => o.Value).ToArray()); } else if (attribute is Money m) { return(m.Value); } else if (attribute is BooleanManagedProperty bmp) { return(bmp.Value); } else { return(attribute); } }
public void JsonFormatDeserialize() { Test test = new Test() { Date = new DateTime(2012, 9, 24, 10, 0, 0, DateTimeKind.Utc), Number = 42, Text = "Hello, world!" }; using (MemoryStream stream = new MemoryStream()) { Assert.AreEqual(null, new JsonFormat().Deserialize(MediaType.Parse("application/json"), typeof(Test), stream)); } using (MemoryStream stream = new MemoryStream()) { new JsonFormat().Serialize(MediaType.Parse("application/json"), test, stream); stream.Position = 0; Test deserialized = new JsonFormat().Deserialize(MediaType.Parse("application/json"), typeof(Test), stream) as Test; Assert.IsNotNull(deserialized); Assert.AreEqual(test.Date, deserialized.Date); Assert.AreEqual(test.Number, deserialized.Number); Assert.AreEqual(test.Text, deserialized.Text); } }
public override async Task <SecretStore> Open(string store) { string storeDirectory = Path.Combine(_rootFolder, store); if (!Directory.Exists(storeDirectory)) { throw new DirectoryNotFoundException(String.Format( CultureInfo.CurrentCulture, Strings.DpapiSecretStoreProvider_StoreDoesNotExist, store)); } string metadataFile = Path.Combine(storeDirectory, "metadata.v1.pjson"); if (!File.Exists(metadataFile)) { throw new FileNotFoundException(String.Format( CultureInfo.CurrentCulture, Strings.DpapiSecretStoreProvider_MissingMetadata, metadataFile)); } // Load encrypted metadata var protector = CreateProtector(MetadataPurpose); var decrypted = await ReadSecretFile(metadataFile, protector); var metadata = JsonFormat.Deserialize <SecretStoreMetadata>(decrypted); return(new DpapiSecretStore(storeDirectory, metadata)); }
public String getRegistroBitacora(int user_id, String alias_unidad, String solicitud, String date) { //String f = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"); DateTime fecha = Convert.ToDateTime(date); List <JsonFormat> list = new List <JsonFormat>(); JsonFormat format24 = getRegistro(24, user_id, fecha); JsonFormat format5_30 = getRegistro(5.50, user_id, fecha); list.Add(format24); list.Add(format5_30); JSonResponse response = new JSonResponse(); response.list = list; response.driver = getDriver(user_id); response.vehicle = getInfoUnidad(alias_unidad); Shipment s = TMSShipmentControllerHelper.GetShipment(solicitud); response.Operation_Type_Alias = TMSShipmentControllerHelper.getOperation_Type_Alias(s.Operation_Type); Performance p = getVehiclePerformance(response.vehicle); response.Marca_y_Modelo = p.Name; //response=getInfoUnidad(response, user_id, alias_unidad); //return new JavaScriptSerializer().Serialize(list); return(new JavaScriptSerializer().Serialize(response)); }
public async Task <AzureToken> LoadToken(string subscriptionId) { string path = Path.Combine(_root, "Subscriptions", subscriptionId + ".dat"); if (!File.Exists(path)) { return(null); } string content = null; using (var reader = new StreamReader(path)) { content = await reader.ReadToEndAsync(); } if (content == null) { return(null); } var unprotected = Encoding.UTF8.GetString( ProtectedData.Unprotect( Convert.FromBase64String(content), null, DataProtectionScope.CurrentUser)); return(JsonFormat.Deserialize <AzureToken>(unprotected)); }
public void GenerateToJson( CodeBuilder codeBuilder, int indentLevel, StringBuilder appendBuilder, JsonType type, string valueGetter, bool canBeNull, JsonFormat format) { codeBuilder.MakeAppend(indentLevel, appendBuilder, format); string dictionaryName = $"list{UniqueNumberGenerator.UniqueNumber}"; codeBuilder.AppendLine(indentLevel, $"var {dictionaryName} = {valueGetter};"); if (canBeNull) { codeBuilder.AppendLine(indentLevel, $"if({dictionaryName} == null)"); codeBuilder.AppendLine(indentLevel, "{"); appendBuilder.Append("null"); codeBuilder.MakeAppend(indentLevel + 1, appendBuilder, format); codeBuilder.AppendLine(indentLevel, "}"); codeBuilder.AppendLine(indentLevel, "else"); codeBuilder.AppendLine(indentLevel, "{"); indentLevel++; } var dictionaryValueType = type.GenericArguments[1]; var generator = _getGeneratorForType(dictionaryValueType); appendBuilder.Append("{"); codeBuilder.MakeAppend(indentLevel, appendBuilder, format); codeBuilder.AppendLine(indentLevel, "bool isFirst = true;"); codeBuilder.AppendLine(indentLevel, $"foreach(var pair in {dictionaryName})"); codeBuilder.AppendLine(indentLevel, "{"); codeBuilder.AppendLine(indentLevel, "if(!isFirst)"); codeBuilder.AppendLine(indentLevel + 1, "{"); appendBuilder.Append(","); codeBuilder.MakeAppend(indentLevel + 2, appendBuilder, format); codeBuilder.AppendLine(indentLevel + 1, "}"); codeBuilder.AppendLine(indentLevel + 1, "isFirst = false;"); appendBuilder.Append("\\\""); codeBuilder.MakeAppend(indentLevel + 1, appendBuilder, format); codeBuilder.AppendLine(indentLevel + 1, $"builder.Append(pair.Key);"); appendBuilder.Append("\\\":"); generator.GenerateToJson(codeBuilder, indentLevel + 1, appendBuilder, dictionaryValueType, $"pair.Value", dictionaryValueType.CanBeNull, format); codeBuilder.AppendLine(indentLevel, "}"); appendBuilder.Append("}"); codeBuilder.MakeAppend(indentLevel, appendBuilder, format); if (canBeNull) { indentLevel--; codeBuilder.AppendLine(indentLevel, "}"); } }
/// <summary> /// Bind Json Objects To Array Of Json Objects /// </summary> /// <param name="formatting"></param> /// <param name="jsonStrings"></param> /// <returns>string contains array of json objects</returns> public static string MargeJsonObjects(JsonFormat formatting = JsonFormat.Indent, params string[] jsonStrings) { var jsonObject = jsonStrings.Where(IsValidJson).Select(js => JavaScriptSerializer.DeserializeObject(js)).ToList(); return(formatting == JsonFormat.Indent ? JavaScriptSerializer.Serialize(jsonObject).Indent() : JavaScriptSerializer.Serialize(jsonObject)); }
public void GenerateToJson( CodeBuilder codeBuilder, int indentLevel, StringBuilder appendBuilder, JsonType type, string valueGetter, bool canBeNull, JsonFormat format) { appendBuilder.Append("\\\""); codeBuilder.MakeAppend(indentLevel, appendBuilder, format); codeBuilder.AppendLine(indentLevel, $"builder.Append({valueGetter});"); appendBuilder.Append("\\\""); }
/// <summary> /// Produces a JSON document containing the details of an <see cref="EntityCollection"/> /// </summary> /// <param name="collection">The entity collection to convert to JSON</param> /// <param name="format">Indicates if the generated JSON should be indented or not</param> /// <param name="jsonFormat">The format of the JSON document to produce</param> /// <returns>A string containing the JSON representation of the <paramref name="collection"/></returns> public static string ToJSON(EntityCollection collection, Formatting format, JsonFormat jsonFormat) { var rootDictionary = new Dictionary <string, object>(); var key = jsonFormat == JsonFormat.Legacy ? "entities" : "value"; rootDictionary[key] = collection.Entities.Select(e => EntitySerializer.ToJSONObject(e, jsonFormat)).ToArray(); return(Newtonsoft.Json.JsonConvert.SerializeObject(rootDictionary, format == System.Xml.Formatting.Indented ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None)); }
public DJsonReader(string text) { var ts = new JsonFormat(text); if (ts.Parse()) { _tree = ts.Tree; _index = 0; } }
private Task UnauditedWriteSecret(Secret secret) { // Generate the name of the file string secretFile = GetFileName(secret.Name); // Write the file var protector = CreateProtector(secret.Name); return(DpapiSecretStoreProvider.WriteSecretFile(secretFile, JsonFormat.Serialize(secret), protector)); }
private static string ToJson(Identity identity) { var jsonObject = new JsonFormat() { Name = identity.Name, Ver = identity.Version, PName = identity.PositionalName }; return(jsonObject.ToJson()); }
public Task <T> GetAsync <T>( Uri uri, JsonFormat jsonFormat, CancellationToken cancellationToken) { return(GetAsync <T>( uri, Enumerable.Empty <KeyValuePair <string, string> >(), jsonFormat, cancellationToken)); }
/// <summary> /// JSONの読み込み /// </summary> /// <param name="filePath">ファイルパス</param> void LoadJson(JsonFormat data, string filePath) { try { var textString = File.ReadAllText(filePath); data.Deserialize(textString); } catch { throw; } }
private async Task <Secret> UnauditedReadSecret(SecretName name, string fileName) { if (!File.Exists(fileName)) { return(null); } // Read the file var protector = CreateProtector(name); return(JsonFormat.Deserialize <Secret>(await DpapiSecretStoreProvider.ReadSecretFile(fileName, protector))); }
private void lbFormat_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e) { try { string value = JsonFormat.FormatJson(this.txtValue.Text); this.txtValue.Text = value; this.lbCancel.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
protected HttpResponseMessage ToJson(object o, int status_code = 1, string msg = "success", int total = 0) { JsonFormat jf = new JsonFormat() { Code = status_code, Data = o, Msg = msg, TotalCount = total }; string json = JsonUtil.ToJson(jf); HttpResponseMessage res = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") }; return(res); }
/// <summary> /// Initializes a new JSON document with the specified anonymous type or array content and formatting options. /// </summary> /// <param name="content">An anonymous type or array to represent as JSON</param> /// <param name="Formatting">Specifies the formatting of the generated JSON document</param> /// <param name="IndentSize">Indentation size when using spaces.</param> public JsonDocument(object content, JsonFormat Formatting, int IndentSize) { if(content != null && !content.GetType().IsGenericType && !isArray(content)) throw new ArgumentException("JsonDocument only works with anonymous types and arrays", "content"); if(Formatting == JsonFormat.Spaces && IndentSize < 0) throw new ArgumentException("Indentation size cannot be less than zero when using spaces.", "IndentSize"); this.Content = content; this.IndentSize = IndentSize; this.Formatting = Formatting; }
public void FormatJson(JsonFormat format, string expectedResult) { // Arrange JsonBuilder obj = new JsonBuilder(); string jsonResult; // Act obj.Format = format; obj.AppendProperty("name", "Jon"); jsonResult = obj.ToString(); // Assert Assert.AreEqual(jsonResult, expectedResult); }
public ActionResult LogIn(Models.ViewModels.Login model) { if (!ModelState.IsValid) { return(View()); } var StrPass = creat(model.Password); var CurUser = _Context.Users.Single(x => x.UserName == model.Email && x.PasswordHash == StrPass); var RoleUser = CurUser.Roles.FirstOrDefault(); // Don't do this in production! // if (model.Email == "*****@*****.**" && model.Password == "password") JsonFormat newjson = new JsonFormat(); List <information> p = new List <information>(); information add1 = new information { controller = "Home", action = "MyInfo" }; information add2 = new information { controller = "Home", action = "MyInfo2" }; p.Add(add1); p.Add(add2); newjson.information = p; string json = JsonConvert.SerializeObject(newjson); if (CurUser != null && RoleUser != null) { var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.UserData, CurUser.UserName), new Claim(ClaimTypes.Name, CurUser.FirstName + " " + CurUser.LastName), new Claim(ClaimTypes.Email, CurUser.Email), new Claim(ClaimTypes.Country, "Iran"), new Claim("JsonListConvert", json), new Claim(ClaimTypes.Role, RoleUser.Name) }, "ApplicationCookie"); var ctx = Request.GetOwinContext(); var authManager = ctx.Authentication; authManager.SignIn(identity); return(Redirect(GetRedirectUrl(model.ReturnUrl))); } // user authN failed ModelState.AddModelError("", "Invalid email or password"); return(View()); }
private void BtnExportToFileClick(object sender, RoutedEventArgs e) { var sfd = new SaveFileDialog(); sfd.FileName = "output"; sfd.Filter = "JavaScript Object Notation (*.json)|*.json"; if (sfd.ShowDialog() == true) { var file = sfd.FileName; JsonFormat.Export(file, Checker.Accounts.Where(a => a.State == Account.Result.Success).ToList()); this.ShowMessageAsync("Export", string.Format("Exported {0} accounts.", Checker.Accounts.Count)); } }
public async Task <T> GetAsync <T>( Uri uri, IEnumerable <KeyValuePair <string, string> > queryString, JsonFormat jsonFormat, CancellationToken cancellationToken) { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri.WithQueryString(queryString))) using (var httpResponseMessage = await SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false)) { httpResponseMessage.EnsureSuccessStatusCode(); var json = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); return(_jsonSerializer.Deserialize <T>(json, jsonFormat)); } }
/// <summary> /// Convert stream to json. /// </summary> /// <param name="stream"></param> /// <param name="format"></param> /// <returns></returns> public static string ToJson(NetStream stream, JsonFormat format) { using (BinaryStreamer streamer = new BinaryStreamer(stream)) { var obj = streamer.Decode(); if (obj == null) { return(null); } else { return(JsonSerializer.Serialize(obj, null, format)); } } }
/// <summary> /// Initializes a new JSON document with the specified anonymous type or array content and formatting options. /// </summary> /// <param name="content">An anonymous type or array to represent as JSON</param> /// <param name="Formatting">Specifies the formatting of the generated JSON document</param> /// <param name="IndentSize">Indentation size when using spaces.</param> public JsonDocument(object content, JsonFormat Formatting, int IndentSize) { if (content != null && !content.GetType().IsGenericType&& !isArray(content)) { throw new ArgumentException("JsonDocument only works with anonymous types and arrays", "content"); } if (Formatting == JsonFormat.Spaces && IndentSize < 0) { throw new ArgumentException("Indentation size cannot be less than zero when using spaces.", "IndentSize"); } this.Content = content; this.IndentSize = IndentSize; this.Formatting = Formatting; }
private void BtnExportToFileClick(object sender, RoutedEventArgs e) { SaveFileDialog sfd = new SaveFileDialog { FileName = "output", Filter = "JavaScript Object Notation (*.json)|*.json" }; if (sfd.ShowDialog() != true) { return; } var accounts = Checker.Accounts.Where(a => a.State == Account.Result.Success).ToList(); JsonFormat.Export(sfd.FileName, accounts); this.ShowMessageAsync("Export", $"Exported {accounts.Count} accounts."); }
public void MakeAppend(int indentLevel, StringBuilder appendContent, JsonFormat format) { if (appendContent.Length == 0) { return; } if (format == JsonFormat.String) { AppendLine(indentLevel, $"builder.Append(\"{appendContent.ToString()}\");"); } else if (format == JsonFormat.UTF8) { var literal = _utf8Literals.GetCopyLiteral(Unescape(appendContent.ToString())); AppendLine(indentLevel, $"builder.{literal.CodeName}();"); } appendContent.Clear(); }