//gets the summoner name from the search form and finds the corresponding ID //then calls to create the 3 api files static async Task<bool> DoJSON(string summonerName) { _sem.WaitOne(); string apikey = ConfigurationManager.AppSettings.Get("apikey"); string nameinfo = summonerName; string path = ConfigurationManager.AppSettings.Get("path"); var client = new HttpClient(); Stream nameInfo = await client.GetStreamAsync("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" + nameinfo + "?api_key=" + apikey); Thread.Sleep(1100); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer userser = new DataContractJsonSerializer(typeof(Dictionary<string, Summoner>), settings); Dictionary<string, Summoner> userDict = (Dictionary<string, Summoner>)userser.ReadObject(nameInfo); string key = userDict.Keys.First<string>(); id = userDict[key].id; leaguedata.LocalFileGen files = new leaguedata.LocalFileGen(); if (!File.Exists(path + "champs.txt")) { int x = await files.ChampInfoFile(); } if (!File.Exists(path + "history" + nameinfo + ".txt")) { int x = await files.MatchHistoryFile(nameinfo, id); } leaguedata.leagueDictionaries dicts = new leaguedata.leagueDictionaries(); Dictionary<int, string> champIDtoName = dicts.getCIDtoCName(); List<Match> matches = dicts.getMatchList(nameinfo); int y = await files.MatchInfoFile(nameinfo, matches, champIDtoName); _sem.Release(); return true; }
public static async Task<IEnumerable<Course>> getMyDataAsync() { //Create the httpclient and set it up var myClient = new HttpClient(); myClient.BaseAddress = new Uri(CourseUrl); myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //perform a get request to the courses api var response = await myClient.GetAsync("courses"); response.EnsureSuccessStatusCode(); //// In case you need date and time properties const string dateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; var jsonSerializerSettings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat(dateTimeFormat) }; var jsonSerializer = new DataContractJsonSerializer( typeof(Course[]), jsonSerializerSettings); var stream = await response.Content.ReadAsStreamAsync(); return (Course[])jsonSerializer.ReadObject(stream); }
private Artist GetArtist(string url) { var c = new Artist {List = new List<ArtistData>()}; c.List.Add(new ArtistData()); try { var request = WebRequest.Create(url); request.Proxy = WebRequest.DefaultWebProxy; request.Credentials = CredentialCache.DefaultCredentials; ; request.Proxy.Credentials = CredentialCache.DefaultCredentials; var response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); string json = reader.ReadToEnd(); Artist tmp; using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; var serializer = new DataContractJsonSerializer(typeof(Artist), settings); tmp = (Artist)serializer.ReadObject(ms); } return tmp ?? c; } catch (Exception) { return c; } }
/// <summary> /// API Result /// </summary> /// <param name="mbId">Albums musicbrainz release-group id</param> /// <param name="apiKey">Users api_key</param> /// <param name="clientKey">Users client_key</param> /// <returns>List of Images for a Album</returns> private static AlbumData Info(string mbId, string apiKey, string clientKey) { try { AlbumData tmp; API.ErrorOccurred = false; API.ErrorMessage = string.Empty; var json = clientKey != "" ? Helper.Json.GetJson(API.Server + "music/albums/" + mbId + "?api_key=" + apiKey) : Helper.Json.GetJson(API.Server + "music/albums/" + mbId + "?api_key=" + apiKey + "&client_key=" + clientKey); if (API.ErrorOccurred) return new AlbumData(); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var settings = new DataContractJsonSerializerSettings {UseSimpleDictionaryFormat = true}; var serializer = new DataContractJsonSerializer(typeof(AlbumData), settings); tmp = (AlbumData)serializer.ReadObject(ms); } return tmp ?? new AlbumData(); } catch (Exception ex) { API.ErrorOccurred = true; API.ErrorMessage = ex.Message; return new AlbumData(); } }
///<summary> /// Method to convert a custom Object to JSON string /// </summary> /// <param name="pObject">Object that is to be serialized to JSON</param> /// <param name="objectType"></param> /// <returns>JSON string</returns> public static String SerializeObject(Object pobject, Type objectType) { try { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o"); var jsonSerializer = new DataContractJsonSerializer(objectType, settings); //jsonSerializer.DateTimeFormat. string returnValue = ""; using (var memoryStream = new MemoryStream()) { using (var xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream)) { jsonSerializer.WriteObject(xmlWriter, pobject); xmlWriter.Flush(); returnValue = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } } return returnValue; } catch (Exception e) { throw e; } }
public async Task<allPinInfo> GetAll() { var client = new HttpClient { BaseAddress = new Uri(RestServiceUrl) }; //// I want to add and accept a header for JSON client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //// Retrieve all the groups with their items var response = await client.GetAsync("pins"); //// Throw an exception if something went wrong response.EnsureSuccessStatusCode(); //// In case you need date and time properties const string dateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; var jsonSerializerSettings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat(dateTimeFormat) }; var jsonSerializer = new DataContractJsonSerializer(typeof(allPinInfo), jsonSerializerSettings); var stream = await response.Content.ReadAsStreamAsync(); allPinInfo elem = (allPinInfo)jsonSerializer.ReadObject(stream); return elem; }
static DataContractJsonSerializer BuildSerializer() { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true, }; return new DataContractJsonSerializer(typeof(Dictionary<string, string>), settings); }
DataContractJsonSerializerSettings createJsonSettings() { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var knownTypes = new List<Type>(); knownTypes.Add(typeof(Commands.Timeline.TimelineEvent)); settings.KnownTypes = knownTypes; return settings; }
/// <summary> /// Serialize to json file /// </summary> /// <param name="json_path"></param> public void SerializeToJson(string json_path) { var setting = new System.Runtime.Serialization.Json.DataContractJsonSerializerSettings(); using (var fs = new FileStream(json_path, FileMode.OpenOrCreate)) { fs.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(ExportDetectionSettings), setting); serializer.WriteObject(fs, this); } }
public static DataContractJsonSerializerSettings GetSerializerSettings() { ObservableCollection<CortanaCommand> prebuiltCommands = InitPrebuiltCortanaCommands(); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); IList<Type> knownTypes = new List<Type>(); foreach (CortanaCommand task in prebuiltCommands) { knownTypes.Add(task.GetType()); } settings.KnownTypes = knownTypes; return settings; }
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) { #if NET_NATIVE || MERGE_DCJS _serializer = new DataContractJsonSerializerImpl(type, settings); #else if (settings == null) { settings = new DataContractJsonSerializerSettings(); } XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); #endif }
public void addParam(string param, object value) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer serializer = new DataContractJsonSerializer(value.GetType(), settings); using (MemoryStream mem = new MemoryStream()) { serializer.WriteObject(mem, value); string json = UnicodeEncoding.UTF8.GetString(mem.ToArray()); addRawParam(param, json); } }
/* Added by Tatiana Alexenko */ public static List<Skeleton> Deserialize(string json) { List<Skeleton> skellist = new List<Skeleton>(); JSONSkeletonCollection results; using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JSONSkeletonCollection), settings); results = (JSONSkeletonCollection)serializer.ReadObject(ms); } foreach (var skeleton in results.Skeletons) { Skeleton kskel = new Skeleton(); { kskel.TrackingId = Int32.Parse(skeleton.ID); kskel.TrackingState = (SkeletonTrackingState)Enum.Parse(typeof(SkeletonTrackingState), "Tracked"); //Joints = new List<JSONJoint>() }; foreach (var joint in skeleton.Joints) { JointType jtype = (JointType)Enum.Parse(typeof(JointType), joint.Label); //Joint scaled = joint.ScaleTo(1000, 1000); SkeletonPoint sp = new SkeletonPoint(); sp.X = joint.X; sp.Y=joint.Y; sp.Z=joint.Z; JointTrackingState js; js=(JointTrackingState)Enum.Parse(typeof(JointTrackingState), "Tracked"); Joint jres=kskel.Joints[jtype]; jres.TrackingState=js; jres.Position=sp; kskel.Joints[jres.JointType]=jres; } skellist.Add(kskel); } return skellist; }
public static CreateSigningResponse CreateSigning(string token, string signerUID, string postbackUrl) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent("Create----" + DateTime.Now)) { // Signed document format. Check documentation for all available options. content.Add(new StringContent("pdf"), "type"); // Signing name. Will be displayed as the main title. content.Add(new StringContent("Agreement"), "name"); // Signer's unique identifier - personal code. content.Add(new StringContent(signerUID), "signers[0][id]"); // Name content.Add(new StringContent("Tester"), "signers[0][name]"); // Surname content.Add(new StringContent("Surname"), "signers[0][surname]"); // Phone number. Optional. content.Add(new StringContent("+37260000007"), "signers[0][phone]"); // Personal code. Optional. content.Add(new StringContent("51001091072"), "signers[0][code]"); // Signing purpose. Availabe options listed in documentation. content.Add(new StringContent("signature"), "signers[0][signing_purpose]"); content.Add(new StringContent(token), "files[0][token]"); // For 'pdf' type only one file is supported. content.Add(new StringContent(postbackUrl), "postback_url"); using ( var message = client.PostAsync(Api.apiUrl + "/api/signing/create.json?access_token=" + Api.accessToken, content)) { var input = message.Result; var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; var serializator = new DataContractJsonSerializer(typeof(CreateSigningResponse), settings); return (CreateSigningResponse)serializator.ReadObject(input.Content.ReadAsStreamAsync().Result); } } } }
public static string SerializeJSon(SprinklerStatus t) { try { MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(SprinklerStatus)); DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings(); ds.WriteObject(stream, t); string jsonString = Encoding.UTF8.GetString(stream.ToArray()); //stream.Close(); return jsonString; } catch (Exception ex) { return ex.ToString(); //throw; } }
internal static string SerializeJSonZoneList(List<Zone> zones) { try { MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(List<Zone>)); DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings(); ds.WriteObject(stream, zones); string jsonString = Encoding.UTF8.GetString(stream.ToArray()); //stream.Close(); return jsonString; } catch (Exception ex) { return ex.ToString(); //throw; } }
public string ClockShow() { var time = DateTime.Now; MemoryStream stream = new MemoryStream(); DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(ClockModel)); DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings(); ds.WriteObject(stream, new ClockModel { H = time.Hour.ToString(), M = time.Minute.ToString(), S = time.Second.ToString() }); stream.Close(); string jsonString = Encoding.UTF8.GetString(stream.ToArray()); return jsonString; }
public override string Serialize() { string request; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.EmitTypeInformation = EmitTypeInformation.Never; System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(DataContext.BBCS.GeneralPurpose.AddDataRequest), settings); ser.WriteObject(ms, this); ms.Position = 0; using (System.IO.StreamReader rdr = new System.IO.StreamReader(ms)) { request = rdr.ReadToEnd(); } } return request; }
public JsonOpenHABDataContract parse(String json) { MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(json)); stream.Position = 0; DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); //settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer jsonSerielizer = new DataContractJsonSerializer(typeof(JsonOpenHABDataContract), settings); try { sh_jsonresult = (JsonOpenHABDataContract)jsonSerielizer.ReadObject(stream); //MessageDialog m = new MessageDialog("hfihdsoi"); //m.ShowAsync(); } catch (Exception ex) { ErrorLogger.printErrorToLog(ex.Message, ex.StackTrace); //errorVisualizier.showError(ex.StackTrace, ex.Message); } return sh_jsonresult; }
public static string ToJson2(this object o) { MemoryStream memoryStream = new MemoryStream(); var settings = new DataContractJsonSerializerSettings { EmitTypeInformation = EmitTypeInformation.Never, UseSimpleDictionaryFormat = true, //KnownTypes = new[] //{ // typeof(UdfResponse), // typeof(Dictionary<string, object>), // typeof(Dictionary<string, UdfResponse>) //} }; var serializer = new DataContractJsonSerializer(o.GetType(), settings); serializer.WriteObject(memoryStream, o); memoryStream.Position = 0; string result = new StreamReader(memoryStream).ReadToEnd(); //result = FormatJson(result); return result; }
/// <summary> /// Retrieve connectors for the client /// This method MUST be called on any HubClient instance prior to use /// </summary> /// <returns></returns> public async Task RetrieveConnectors() { HttpResponseMessage response = await connection.GetAsync("connectors"); if (response.IsSuccessStatusCode) { MemoryStream data = (MemoryStream)(await response.Content.ReadAsStreamAsync()); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Connector>), settings); connectors = (List<Connector>)serializer.ReadObject(data); foreach (Connector conn in connectors) { if (conn.type == "Connectors::DynamicsEmail") { dynamics = conn; } } } }
public async Task<DemoItem[]> GetItemsAsync(uint start = 1, uint count = 10) { Debug.WriteLine("GetItemsAsync({0}, {1})", start, count); var url = Const.APIBase + "json/json?start=" + start + "&count=" + count; var uri = new Uri(url); #if WINDOWS_PHONE var req = WebRequest.CreateHttp(uri); req.AllowReadStreamBuffering = true; var resp = await req.GetResponseAsync(); var stream = resp.GetResponseStream(); #elif WINDOWS_STORE_APP var httpClient = new HttpClient(); var resp = await httpClient.GetAsync(uri); var stream = await resp.Content.ReadAsStreamAsync(); #endif var serializerSettings = new DataContractJsonSerializerSettings(); serializerSettings.DateTimeFormat = new DateTimeFormat("yyyy-MM-ddTHH:mm:sszzz"); var serializer = new DataContractJsonSerializer(typeof(DemoItemAPIResponse), serializerSettings); var res = (DemoItemAPIResponse)serializer.ReadObject(stream); stream.Dispose(); return res.Result.Items; }
public async Task<int> ChampInfoFile() { string apikey = ConfigurationManager.AppSettings.Get("apikey"); string path = ConfigurationManager.AppSettings.Get("path"); var client = new HttpClient(); string champAPI = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion?api_key=" + apikey; Stream champInfo = await client.GetStreamAsync(champAPI); Thread.Sleep(1100); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer champSer = new DataContractJsonSerializer(typeof(BaseChampion), settings); BaseChampion champ = (BaseChampion)champSer.ReadObject(champInfo); champ.GenerateNameLookup(); MemoryStream champStream = new MemoryStream(); champSer.WriteObject(champStream, champ); champStream.Position = 0; StreamReader championJSON = new StreamReader(champStream); System.IO.StreamWriter champFile = File.AppendText(path + "champs.txt"); champFile.WriteLine(championJSON.ReadToEnd()); champFile.Close(); return 1; }
public RemoteDebugger(string url) { Uri uri = new Uri(url); if (uri.Scheme != "ws") { throw new ArgumentException("Remote debugging must use a ws url."); } else { // open web socket var uriS = uri.ToString(); // trailing backslash must be removed uriS = uriS.TrimEnd('/'); socket = new WebSocket(uriS); // ("ws://localhost:9222/devtools/page/1"); socket.Opened += new EventHandler(socketOpened); //socket.Error += new EventHandler<ErrorEventArgs>(socketError); socket.Closed += new EventHandler(socketClosed); socket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(socketMessageReceived); //socket.Open(); settings = createJsonSettings(); } }
/// <summary> /// Json serialize /// </summary> public static string ToJson(object value) { var settings = new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true }; var jsonSerializer = new DataContractJsonSerializer(value.GetType(), settings); using (var memory = new MemoryStream()) { jsonSerializer.WriteObject(memory, value); var writer = new StreamWriter(memory); writer.Flush(); memory.Position = 0; var reader = new StreamReader(memory); return reader.ReadToEnd(); } }
/// <summary> /// CreateHttpResponseMessage that returns a List of Events for use with mocked HttpClients /// </summary> /// <param name="events">A List of Events to return</param> /// <returns></returns> private List<HttpResponseMessage> eventResponse(List<Event> events, List<Event> subsequent) { var httpResponse = new HttpResponseMessage(HttpStatusCode.OK); MemoryStream stream = new MemoryStream(); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Event>), settings); serializer.WriteObject(stream, events); httpResponse.Content = new StringContent(Encoding.UTF8.GetString(stream.ToArray()), Encoding.UTF8, "application/json"); var subsequentResponse = new HttpResponseMessage(HttpStatusCode.OK); MemoryStream subsequentStream = new MemoryStream(); DataContractJsonSerializer subSerializer = new DataContractJsonSerializer(typeof(List<Event>), settings); serializer.WriteObject(subsequentStream, subsequent); httpResponse.Content = new StringContent(Encoding.UTF8.GetString(stream.ToArray()), Encoding.UTF8, "application/json"); subsequentResponse.Content = new StringContent(Encoding.UTF8.GetString(subsequentStream.ToArray()), Encoding.UTF8, "application/json"); return new List<HttpResponseMessage>() { httpResponse, subsequentResponse }; }
/// <summary> /// Create a an HttpResponseMessage that returns Connectors for use with mocked HttpClients /// </summary> /// <param name="types">An array of the type of connector to create</param> /// <returns></returns> private List<HttpResponseMessage> connectorResponse(string[] types) { var httpResponse = new HttpResponseMessage(HttpStatusCode.OK); MemoryStream stream = new MemoryStream(); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Connector>), settings); var connectorList = new List<Connector>(); if (types != null) { for (int i = 0; i < types.Length; i++ ) { connectorList.Add(new Connector() { id = 1, type = types[i], options = new Dictionary<string, string>() { {"option", "one"} }, links = new List<Link>() { new Link() { rel = "test", href = "/actions" } } }); } } serializer.WriteObject(stream, connectorList); httpResponse.Content = new StringContent(Encoding.UTF8.GetString(stream.ToArray()), Encoding.UTF8, "application/json"); return new List<HttpResponseMessage>() { httpResponse }; }
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) { _serializer = new DataContractJsonSerializerImpl(type, settings); }
protected override void Execute(CodeActivityContext executionContext) { IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); var settingName = SettingName.Get(executionContext); var fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' aggregate='true'> <entity name='businessunit'> <attribute name='businessunitid' groupby='true' alias='buid'/> <attribute name='parentbusinessunitid' groupby='true' alias='pbuid'/> <attribute name='name' groupby='true' alias='name'/> <link-entity name='salesorder' from='owningbusinessunit' to='businessunitid' alias='op' link-type='outer'> <attribute name='new_datetime' groupby='true' dategrouping='month' alias='month' /> <attribute name='totalamount' alias='actualvalue_sum' aggregate='sum' /> </link-entity> </entity> </fetch>"; // <attribute name='opportunityratingcode' groupby='true' alias='oppratcode' /> //opportunityratingcode var fetch = new FetchExpression(fetchXml); var bus = service.RetrieveMultiple(fetch); var nonprocesedBu = bus.Entities.ToList(); #region Aggregation Logic // var processedNodesBu = new List<Node>(); var finalNodeList = new List<Node>(); var nonprocesedNodesBu = nonprocesedBu.Select(x => new Node { Buid = (Guid)x.GetAttributeValue<AliasedValue>("buid").Value, PartialAmount = x.GetAttributeValue<AliasedValue>("actualvalue_sum").Value == null ? 0m : ((Money)x.GetAttributeValue<AliasedValue>("actualvalue_sum").Value).Value, ParentBuid = x.Attributes.ContainsKey("pbuid") ? ((EntityReference)x.GetAttributeValue<AliasedValue>("pbuid").Value).Id : Guid.Empty, Name = (string)x.GetAttributeValue<AliasedValue>("name").Value, MonthNumber = x.Attributes.ContainsKey("month") ? ((int)x.GetAttributeValue<AliasedValue>("month").Value) : -1, HasChilds = false } ) .ToList(); var nonProcesedHelperNodesBu = new List<Node>(nonprocesedNodesBu); var distinctBu = nonProcesedHelperNodesBu.GroupBy(x => x.Name).Select(x => new BuMetadata(){Color = "#000000", Name = x.Key}).ToList(); //Create tree structure of nodes //get BU where the data is completly empty var nodesFullYearAdd = nonProcesedHelperNodesBu.Where(x => x.MonthNumber == -1); //Fix the empty data in real world, this should not be executed. foreach ( var item in nodesFullYearAdd ) { for ( var i = 1; i <= 12; i++ ) { var nodeAdd = (Node)item.Clone(); nodeAdd.MonthNumber = i; nodeAdd.PartialAmount = 0m; finalNodeList.Add(nodeAdd); } } //check now var nodesAddMissingMonths = nonprocesedNodesBu.Where(x => x.MonthNumber != -1); var groupedNodesAddOtherMonths = (from node in nodesAddMissingMonths group node by node.Buid into nodeGroup select nodeGroup); //group data based on businessunit //foreach bussiness unit foreach ( var group in groupedNodesAddOtherMonths ) { for ( var i = 1; i <= 12; i++ ) { //if group contains this month if ( group.ToList().Any(x => x.MonthNumber == i) ) { //get that month var nodeFinal = group.ToList().FirstOrDefault(x => x.Buid == group.Key && x.MonthNumber == i); //add to final list finalNodeList.Add(nodeFinal); } else { //for given month record is not existing, just add empty record var nodeFinal = group.ToList().FirstOrDefault(x => x.Buid == group.Key); nodeFinal = nodeFinal ?? new Node(); var nodeAdd = (Node)nodeFinal.Clone(); nodeAdd.PartialAmount = 0m; nodeAdd.MonthNumber = i; finalNodeList.Add(nodeAdd); } } } //foreach ( Node it in finalNodeList.OrderBy(x=>x.MonthNumber).ThenBy(x=>x.Name).ToList()) //{ // Console.WriteLine("Month Number: "+it.MonthNumber); // Console.WriteLine("Partial Amount: " + it.PartialAmount); // Console.WriteLine("Name: " + it.Name); //} foreach ( var currentNode in finalNodeList ) { var childs = finalNodeList.Where(x => x.ParentBuid == currentNode.Buid && x.MonthNumber == currentNode.MonthNumber).ToList(); var amountOfChilds = childs.Count(); if (amountOfChilds <= 0) continue; currentNode.HasChilds = true; currentNode.ChildNodes = new List<Node>(childs); } foreach ( var currentNode in finalNodeList ) { currentNode.Amount = currentNode.GetNodeValue(currentNode); } // af4df01e-2977-e511-80fa-3863bb345a68 kaporg 2 var prefilteredList = finalNodeList.Where(x => x.ParentBuid == Guid.Empty);//new Guid("af4df01e-2977-e511-80fa-3863bb345a68")); var monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames; var groupedListByMonth = (from node in prefilteredList group node by node.MonthNumber into nodeGroup select new MonthGraph() { MonthName = monthNames[nodeGroup.Key - 1], MonthNumber = nodeGroup.Key, Bu = nodeGroup.Select(o => new BuItem{ Amount = o.Amount, Name = o.Name, Id = o.Buid }).ToList() } ).ToList(); var setting = new DataContractJsonSerializerSettings {UseSimpleDictionaryFormat = true}; using ( var memoryStream = new MemoryStream() ) { var serializer = new DataContractJsonSerializer(typeof(List<MonthGraph>), setting); serializer.WriteObject(memoryStream, groupedListByMonth); var json = Encoding.Default.GetString(memoryStream.ToArray()); JsonObectString.Set(executionContext, json); } using ( var memoryStream = new MemoryStream() ) { var serializer = new DataContractJsonSerializer(typeof(List<BuMetadata>), setting); serializer.WriteObject(memoryStream, distinctBu); var json = Encoding.Default.GetString(memoryStream.ToArray()); JsonMetadata.Set(executionContext, json); } #endregion }
public Dictionary<int, string> getCIDtoCName() { string path = ConfigurationManager.AppSettings.Get("path"); string champs = System.IO.File.ReadAllText(path + "champs.txt"); DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; MemoryStream champStream = new MemoryStream(Encoding.UTF8.GetBytes(champs)); DataContractJsonSerializer champser = new DataContractJsonSerializer(typeof(BaseChampion), settings); BaseChampion champDetail = (BaseChampion)champser.ReadObject(champStream); champDetail.GenerateNameLookup(); return champDetail.nameLookup; }
public DataContractJsonSerializer (Type type, DataContractJsonSerializerSettings settings) : this (type, settings.RootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.DataContractSurrogate, false) { }
public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) : this(type, settings.RootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.DataContractSurrogate, false) { }
static void Main(string[] args) { var myValue = new MyObject() { attr1 = "ABC", attr2 = new MySubObject() { attr1 = "XYZ", attr2 = "ABC", attr3 = 567 }, attr3 = 123, attr4 = new List<String>(new String[] { "abc", "def" }) }; var outputBuffer = new MemoryStream(); var serializerSettings = new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = false }; var serializer = new DataContractJsonSerializer(typeof(MyObject), serializerSettings); serializer.WriteObject(outputBuffer, myValue); System.Console.Out.WriteLine(Encoding.UTF8.GetString(outputBuffer.ToArray())); }