Write() public method

public Write ( bool boolean ) : void
boolean bool
return void
Beispiel #1
0
 public override string ToString()
 {
     StringBuilder sb = new StringBuilder ();
     JsonWriter writer = new JsonWriter (sb);
     writer.WriteObjectStart ();
     writer.WritePropertyName ("option");
     writer.Write (option);
     writer.WritePropertyName ("subfield");
     writer.Write (subfield);
     writer.WritePropertyName ("tarId");
     writer.Write (tarId);
     writer.WriteObjectEnd ();
     return sb.ToString();
 }
    public static void CreateClothes()
    {
        string[] materials = Directory.GetFiles("Assets/characters_joysoft", "*.mat", SearchOption.AllDirectories);
        StringBuilder sbuilders = new StringBuilder ();
        JsonWriter writer = new JsonWriter (sbuilders);
        writer.WriteObjectStart ();
        foreach (string material in materials)
        {
            //Assets/characters_joysoft/Per Texture Materials/female_hair_01_01.mat
            string[] parts=material.Replace(".mat","").Split('/');
            string unit=parts[parts.Length-1];

            writer.WritePropertyName (unit);

            int hashkey=0;
            foreach(string key in defaultClothes){
                if(unit.Contains(key)){
                    hashkey=1;
                    break;
                }
            }
            writer.Write (""+hashkey);

            sbuilders.Append(System.Environment.NewLine);

        }
        writer.WriteObjectEnd ();

        UpdateClothesContent(sbuilders);

        Debug.Log("**********UpdateClothesContent Finish***********");
    }
Beispiel #3
0
        private void OnExecute()
        {
            try
            {
                StudentCsvReader      reader   = new StudentCsvReader();
                IEnumerable <Student> students = reader.Read(InputFilePath);
                IFileWriter           writer   = null;
                switch (FileFormat.ToLower())
                {
                case ExcelFormatName:
                    writer = new ExcelWriter();
                    break;

                case JsonFormatName:
                    writer = new JsonWriter();
                    break;

                default:
                    logger.Error($"{FileFormat} is unknown format");
                    break;
                }
                writer?.Write(students, OutputFilePath);
            }
            catch (Exception ex)
            {
                logger.Error($"The result not recorded. Inner exception: {ex.StackTrace}");
            }
        }
    void Deactivate()
    {
        state = 0;
        renderer.material.color = colours[0];

        StringBuilder sb = new StringBuilder();
        JsonWriter writer = new JsonWriter(sb);
        writer.WriteObjectStart();
        writer.WritePropertyName("id");
        writer.Write(id);
        writer.WritePropertyName("state");
        writer.Write(0);
        writer.WriteObjectEnd();

        monome.SendMessage("SendToSaul", sb.ToString());
    }
Beispiel #5
0
        static void Main()
        {
            #if !DEBUG
            try {
            #endif
                // Load all configurations and if the config file does not exist, generate a new one.
            string settings_file = Path.Combine(Client.directory_app_data, "settings.dcf");

                Client.config = new Config(delegate(Config current_config) {
                    DC_Server[] server_list = new DC_Server[1];
                    server_list[0] = new DC_Server {
                        name = "NFGaming Upload Server",
                        url = "http://uploads.nfgaming.com",
                        times_connected = 0
                    };

                    current_config.set("frmlogin.servers_list", server_list);
                }, settings_file);

                // Set the max connections this program is allowed to have to a HTTP server.
                System.Net.ServicePointManager.DefaultConnectionLimit = Client.config.get<short>("net.default_connection_limit", 4);

                Client.config.save();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new frmLogin());

                // Run the cleanup script since the main form has been closed.
                cleanup();

            #if !DEBUG
            } catch(Exception e) {
                StringBuilder sb = new StringBuilder();
                JsonWriter jw = new JsonWriter(sb);
                DC_Exception exception = new DC_Exception() {
                    help_link = e.HelpLink,
                    inner_exception_message = (e.InnerException != null) ? e.InnerException.Message : null,
                    inner_exception_stack_trace = (e.InnerException != null)? e.InnerException.StackTrace : null,
                    source = e.Source,
                    stack_trace = e.StackTrace,
                    message = e.Message
                };

                jw.Write(exception);

                string args = Utilities.base64Encode(sb.ToString());
                args += " ";
                args += "http://dtronix.com/dtxCrashReporter/";

                System.Diagnostics.Process.Start("dtxCrashReporter.exe", args);
            }
            #endif
        }
Beispiel #6
0
    void OnGUI()
    {
        content = GUI.TextArea(new Rect(100, 100, 400, 100), content);

           /* if (GUI.Button(new Rect(330, 60, 60, 30), "Little jasson"))
        {
            Debug.Log("write jsson");

            TextWriter wr = new StreamWriter("students.txt");
            JsonWriter jsonwr = new JsonWriter(wr);
            jsonwr.IndentValue = 0;
            JsonMapper.ToJson(st1, jsonwr);
            jsonwr.WriteObjectStart();

            JsonMapper.ToJson(st2, jsonwr);
            wr.Close();

        }*/

        if (GUI.Button(new Rect(380, 60, 60, 30), "FX jasson"))
        {
            /*Классы короткая запись*/
            string json = JsonFx.Json.JsonWriter.Serialize(st1);
           // Debug.Log(json);
            Student st3 = JsonFx.Json.JsonReader.Deserialize<Student>(json);
            //Debug.Log("age " + st3.age + " count " + st3.count[5] + " name " + st3.name);

            /*массив*/

            JsonWriterSettings settw = new JsonWriterSettings();
            settw.TypeHintName = "__type";
            JsonReaderSettings settr = new JsonReaderSettings();
            settr.TypeHintName = "__type";

            /*пример чтоб разобраться, но либа работает только с классами нормально. */
            System.Text.StringBuilder builder=new System.Text.StringBuilder();
            JsonWriter wr = new JsonWriter(builder,settw);
                Student[] arr = new Student[3];
                arr[0] = st1;
                arr[1] = st2;
                arr[2] = st3;
                wr.Write(arr);
                System.IO.File.WriteAllText("testJSON.txt", builder.ToString());

            string jsonText = System.IO.File.ReadAllText("testJSON.txt");
            //Debug.Log(""+jsonText);
            Student[] tempSt = JsonReader.Deserialize<Student[]>(jsonText);
            content = "";
                foreach( var s in tempSt)
                    content +="" + s.name+System.Environment.NewLine;

        }
    }
Beispiel #7
0
	/// <summary>
	/// 数据存Json
	/// </summary>
	public void SaveData()
	{
		StringBuilder sb = new StringBuilder();
		JsonWriter jw = new JsonWriter(sb);
		jw.WriteObjectStart();
		//写入玩家名称
		jw.WritePropertyName("Name");
		jw.Write(GlobalManager.userName);
		//写入开始索引
		jw.WritePropertyName("StartIndex");
		jw.Write(GlobalManager.startIndex);
		//写入最高分
		jw.WritePropertyName("MaxScore");
		jw.Write(GlobalManager.maxScore);
		//写入已经完成的单词总数
		jw.WritePropertyName("WordAmount");
		jw.Write(GlobalManager.wordAmount);
		//...

		jw.WriteObjectEnd();
		SaveJsonString(sb.ToString());
	}
Beispiel #8
0
    public static void SaveJson()
    {
        string filePath = Application.dataPath + @"/StringAssets/file/pos.txt";
        FileInfo fileInfo = new FileInfo(filePath);
        if (!File.Exists(filePath))
        {
            File.Delete(filePath);
        }

        StreamWriter sw = fileInfo.CreateText();
        StringBuilder sb = new StringBuilder();
        JsonWriter writer = new JsonWriter(sb);

        //从场景中开始一个个的遍历
        foreach (EditorBuildSettingsScene s in EditorBuildSettings.scenes)
        {
            if (s.enabled == true)
            {
                string name = s.path;
                EditorApplication.OpenScene(name);
                GameObject parent = GameObject.Find("PosObj");
                if (parent)
                {
                    writer.WriteArrayStart(); //开始写数据
                    for (int i = 0; i < parent.transform.childCount; i++)
                    {
                        Transform obj = parent.transform.GetChild(i);
                        writer.WriteObjectStart();
                        writer.WritePropertyName(obj.name);
                        writer.Write(obj.position.x.ToString() + "," + obj.position.y.ToString() + "," +
                                     obj.position.z.ToString());
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }
            }
        }

        sw.WriteLine(sb.ToString());
        sw.Close();
        sw.Dispose(); //关闭文件流
        AssetDatabase.Refresh();  //刷新
    }
Beispiel #9
0
    IEnumerator PostTest1()
    {
        string str = @"";
        // string like this
        // str = @"{""Id"":0,""IMEI"":""String"",""Phone"":""String"",""Name"":""String"",""Status"":0,""CreateTime"":""\/Date(-62135596800000+0800)\/"",""UpdateTime"":""\/Date(-62135596800000+0800)\/""}";
        // write Json
        JsonWriter writer = new JsonWriter();
        writer.WriteObjectStart();
        writer.WritePropertyName("Id");
        writer.Write(0);
        writer.WritePropertyName("IMEI");
        writer.Write("7654321");
        writer.WritePropertyName("Phone");
        writer.Write("13802817183");
        writer.WritePropertyName("Name");
        writer.Write("bbzm");
        writer.WritePropertyName("Status");
        writer.Write("1");
        writer.WritePropertyName("CreateTime");
        writer.Write("2013-01-01");
        writer.WritePropertyName("UpdateTime");
        writer.Write("2013-10-10");
        writer.WriteObjectEnd();
        str = writer.ToString();

        Debug.Log(str);
        WWWForm parameter = new WWWForm();
        parameter.AddField("Body", str);

        WWW postRequest = new WWW(@"http://192.168.133.225:82/Client/123456?format=json", parameter);
        yield return postRequest;

        JsonReader read = new JsonReader(postRequest.text);
        Debug.Log(postRequest.text);
        Debug.Log(" ----------------- ");
        while (read.Read())
        {
            Debug.Log(read.Token + " : " + read.Value + " : " + read.GetType().ToString());
        }
        Debug.Log(" ----------------- ");
    }
 private static void exportFloatAsDecimal(float value, JsonWriter writer)
 {
     writer.Write((decimal)value);
 }
        public IRequest Marshall(DescribeElasticIpsRequest describeElasticIpsRequest)
        {
            IRequest request = new DefaultRequest(describeElasticIpsRequest, "AmazonOpsWorks");
            string   target  = "OpsWorks_20130218.DescribeElasticIps";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";



            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (describeElasticIpsRequest != null && describeElasticIpsRequest.IsSetInstanceId())
                {
                    writer.WritePropertyName("InstanceId");
                    writer.Write(describeElasticIpsRequest.InstanceId);
                }
                if (describeElasticIpsRequest != null && describeElasticIpsRequest.IsSetStackId())
                {
                    writer.WritePropertyName("StackId");
                    writer.Write(describeElasticIpsRequest.StackId);
                }

                if (describeElasticIpsRequest != null && describeElasticIpsRequest.Ips != null && describeElasticIpsRequest.Ips.Count > 0)
                {
                    List <string> ipsList = describeElasticIpsRequest.Ips;
                    writer.WritePropertyName("Ips");
                    writer.WriteArrayStart();

                    foreach (string ipsListValue in ipsList)
                    {
                        writer.Write(StringUtils.FromString(ipsListValue));
                    }

                    writer.WriteArrayEnd();
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #12
0
        public String jsonConfigFromMod(LocalMod mod)
        {
            JsonWriter writer = new JsonWriter();

            return(writer.Write(mod));
        }
 void WriteJsonAndPrint()
 {
     System.Text.StringBuilder strB = new System.Text.StringBuilder();
     JsonWriter jsWrite = new JsonWriter(strB);
     jsWrite.WriteObjectStart();
     jsWrite.WritePropertyName("Name");
     jsWrite.Write("taotao");
     jsWrite.WritePropertyName("Age");
     jsWrite.Write(25);
     jsWrite.WritePropertyName("MM");
     jsWrite.WriteArrayStart();
     jsWrite.WriteObjectStart();
     jsWrite.WritePropertyName("name");
     jsWrite.Write("xiaomei");
     jsWrite.WritePropertyName("age");
     jsWrite.Write("17");
     jsWrite.WriteObjectEnd();
     jsWrite.WriteObjectStart();
     jsWrite.WritePropertyName("name");
     jsWrite.Write("xiaoli");
     jsWrite.WritePropertyName("age");
     jsWrite.Write("18");
     jsWrite.WriteObjectEnd();
     jsWrite.WriteArrayEnd();
     jsWrite.WriteObjectEnd();
     Debug.Log(strB);
     JsonData jd = JsonMapper.ToObject(strB.ToString());
     Debug.Log("name=" + jd["Name"]);
     Debug.Log("age=" + jd["Age"]);
     JsonData jdItems = jd["MM"];
     for (int i = 0; i < jdItems.Count; i++)
     {
         Debug.Log("MM name=" + jdItems["name"]);
         Debug.Log("MM age=" + jdItems["age"]);
     }
 }
Beispiel #14
0
        public void Export()
        {
            try
            {
                int pos = EditorApplication.currentScene.LastIndexOf("/", StringComparison.Ordinal);
                string sceneName = EditorApplication.currentScene.Substring(pos + 1);

                exportationOptions.DefaultFolder = EditorUtility.SaveFolderPanel("Please select a folder", exportationOptions.DefaultFolder, "");

                if (string.IsNullOrEmpty(exportationOptions.DefaultFolder))
                {
                    return;
                }

                Stopwatch watch = new Stopwatch();

                watch.Start();

                var jsWriter = new JsonWriter();                
                File.WriteAllText("Unity3D2Babylon.ini", jsWriter.Write(exportationOptions));
                logs.Clear();

                ReportProgress(0);

                var sceneBuilder = new SceneBuilder(exportationOptions.DefaultFolder, sceneName, exportationOptions);

                sceneBuilder.ConvertFromUnity();

                ReportProgress(1, "Generating output file");
                sceneBuilder.WriteToBabylonFile();

                watch.Stop();
                ReportProgress(1, string.Format("Exportation done in {0:0.00}s", watch.Elapsed.TotalSeconds));
                EditorUtility.ClearProgressBar();

                sceneBuilder.GenerateStatus(logs);

                ShowMessage("Exportation done");
            }
            catch (Exception ex)
            {
                EditorUtility.ClearProgressBar();
                ShowMessage("A problem occurred: " + ex.Message + ex.StackTrace, "Error");
            }
        }
        public void Export(bool run)
        {
            try
            {
                string sceneName = EditorSceneManager.GetActiveScene().name;

                exportationOptions.DefaultFolder = EditorUtility.SaveFolderPanel("Please select a folder", exportationOptions.DefaultFolder, "");

                if (string.IsNullOrEmpty(exportationOptions.DefaultFolder))
                {
                    return;
                }

                Stopwatch watch = new Stopwatch();

                watch.Start();

                var jsWriter = new JsonWriter();
                File.WriteAllText("Unity3D2Babylon.ini", jsWriter.Write(exportationOptions));
                logs.Clear();

                ReportProgress(0);

                var sceneBuilder = new SceneBuilder(exportationOptions.DefaultFolder, sceneName, exportationOptions);

                sceneBuilder.ConvertFromUnity();

                ReportProgress(1, "Generating output file");
                var outputFile = sceneBuilder.WriteToBabylonFile();

                watch.Stop();
                ReportProgress(1, string.Format("Exportation done in {0:0.00}s", watch.Elapsed.TotalSeconds));
                EditorUtility.ClearProgressBar();

                sceneBuilder.GenerateStatus(logs);

                ShowMessage("Exportation done");

                if (run)
                {
                    WebServer.SceneFolder = Path.GetDirectoryName(outputFile);
                    WebServer.SceneFilename = Path.GetFileName(outputFile);

                    Process.Start("http://localhost:" + WebServer.Port);
                }
            }
            catch (Exception ex)
            {
                EditorUtility.ClearProgressBar();
                ShowMessage("A problem occurred: " + ex.Message + ex.StackTrace, "Error");
            }
        }
        public IRequest Marshall(GetWorkflowExecutionHistoryRequest getWorkflowExecutionHistoryRequest)
        {
            IRequest request = new DefaultRequest(getWorkflowExecutionHistoryRequest, "AmazonSimpleWorkflow");
            string   target  = "SimpleWorkflowService.GetWorkflowExecutionHistory";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.0";

            string uriResourcePath = "";

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetDomain())
                {
                    writer.WritePropertyName("domain");
                    writer.Write(getWorkflowExecutionHistoryRequest.Domain);
                }

                if (getWorkflowExecutionHistoryRequest != null)
                {
                    WorkflowExecution execution = getWorkflowExecutionHistoryRequest.Execution;
                    if (execution != null)
                    {
                        writer.WritePropertyName("execution");
                        writer.WriteObjectStart();
                        if (execution != null && execution.IsSetWorkflowId())
                        {
                            writer.WritePropertyName("workflowId");
                            writer.Write(execution.WorkflowId);
                        }
                        if (execution != null && execution.IsSetRunId())
                        {
                            writer.WritePropertyName("runId");
                            writer.Write(execution.RunId);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetNextPageToken())
                {
                    writer.WritePropertyName("nextPageToken");
                    writer.Write(getWorkflowExecutionHistoryRequest.NextPageToken);
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetMaximumPageSize())
                {
                    writer.WritePropertyName("maximumPageSize");
                    writer.Write(getWorkflowExecutionHistoryRequest.MaximumPageSize);
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetReverseOrder())
                {
                    writer.WritePropertyName("reverseOrder");
                    writer.Write(getWorkflowExecutionHistoryRequest.ReverseOrder);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #17
0
	private static void writeMatrix(ref JsonWriter cfg, Transform mt) {
		cfg.WritePropertyName("pos");
		cfg.WriteArrayStart();
		cfg.Write(mt.localPosition.x);
		cfg.Write(mt.localPosition.y);
		cfg.Write(mt.localPosition.z);
		cfg.WriteArrayEnd();

		cfg.WritePropertyName("scale");
		cfg.WriteArrayStart();
		cfg.Write(mt.localScale.x);
		cfg.Write(mt.localScale.y);
		cfg.Write(mt.localScale.z);
		cfg.WriteArrayEnd();

		cfg.WritePropertyName("rotation");
		cfg.WriteArrayStart();
		cfg.Write(mt.localRotation.eulerAngles.x);
		cfg.Write(mt.localRotation.eulerAngles.y);
		cfg.Write(mt.localRotation.eulerAngles.z);
		cfg.WriteArrayEnd();
	}
Beispiel #18
0
	private static void writeObject(GameObject obj, ref JsonWriter cfg) {
		cfg.WriteObjectStart();
		cfg.WritePropertyName("name");
		cfg.Write(obj.name);
		cfg.WritePropertyName("Layer");
		cfg.Write(obj.layer);
		writeMatrix(ref cfg, obj.transform);

		if (obj.renderer) {
			Mesh mesh = obj.renderer.GetComponent<MeshFilter>().sharedMesh;
			if (obj.renderer.material.mainTexture != null) {
				cfg.WritePropertyName("MainTexture");
				cfg.Write(getFileName(AssetDatabase.GetAssetPath(obj.renderer.material.mainTexture.GetInstanceID())));
			}
			if (mesh) {
				cfg.WritePropertyName("Mesh");
				cfg.Write(mesh.name);
			}
			if (obj.renderer.lightmapIndex != -1) {
				cfg.WritePropertyName("lightmap");
				cfg.Write(LightmapSettings.lightmaps[obj.renderer.lightmapIndex].lightmapFar.name);
				cfg.WritePropertyName("tilingOffset");
				cfg.WriteArrayStart();
				cfg.Write(obj.renderer.lightmapTilingOffset.x);
				cfg.Write(obj.renderer.lightmapTilingOffset.y);
				cfg.Write(obj.renderer.lightmapTilingOffset.z);
				cfg.Write(obj.renderer.lightmapTilingOffset.w);
				cfg.WriteArrayEnd();
			}
		}

		cfg.WritePropertyName("children");
		cfg.WriteArrayStart();

		for (int i = 0; i < obj.transform.childCount; i++) {
			writeObject(obj.transform.GetChild(i).gameObject, ref cfg);
		}

		cfg.WriteArrayEnd();
		cfg.WriteObjectEnd();
	}
    /// <summary>
    /// Post to a a URL endpoint with required field(s) and gives an optional response handler.
    /// </summary>
    /// <param name="url">The URL to post to.</param>
    /// <param name="responseHandler">An Action that handles the response (optional).</param>
    public void PostURL(string url, Dictionary<string, object> fields, Action<Dictionary<string, object>> responseHandler=null) {

        // Kill networking immediately if no connection
        // if(Application.internetReachability == NetworkReachability.NotReachable)
        //     KillNetwork(true);

        if(_ignoreNetwork) {
            fields.Add("local", true);
            responseHandler(fields);
            return;
        }

        string absoluteURL = DataManager.RemoteURL + url;

        // Send form as raw byte array
        System.Text.StringBuilder output = new System.Text.StringBuilder();
        
        JsonWriter writer = new JsonWriter (output);
        
        if(_sessionCookie != null)
            fields.Add("sessionID", System.Convert.ChangeType(_sessionCookie, typeof(object)));
        
        // If no session cookie, client has no auth, so cache this request to do later
        else if(url != "/auth/") {
            PostCache cacheObj = new PostCache();
            cacheObj.url = url;
            cacheObj.fields = fields;
            cacheObj.responseHandler = responseHandler;
            _cachedRequests.Add(cacheObj);

            return;
        }

        writer.Write(fields);
     
        // Encode output as UTF8 bytes
        _currentRoutine = WaitForForm(absoluteURL, Encoding.UTF8.GetBytes(output.ToString()), responseHandler);
        StartCoroutine(_currentRoutine);
    
    }
Beispiel #20
0
 public static string WriteJson(SharedObjects sharedObjects, object input)
 {
     return(jsonWriter.Write(new Serializer(sharedObjects).Serialize(input)));
 }
Beispiel #21
0
    /// <summary>
    /// Returns a <see cref="System.String"/> that represents the current <see cref="Recording"/> using JSON
    /// </summary>
    /// <returns>
    /// A <see cref="System.String"/> that represents the current <see cref="Recording"/>.
    /// </returns>
    public override string ToString()
    {
        StringBuilder jsonB = new StringBuilder();
        JsonWriter writer = new JsonWriter( jsonB );

        writer.WriteObjectStart();
        //{
        writer.WritePropertyName( "frameRate" );
        writer.Write( frameRate );

        writer.WritePropertyName( "frames" );
        writer.WriteArrayStart();
        //[
        foreach ( RecordingFrame frame in frames )
        {
            writer.WriteObjectStart();
            //{

            writer.WritePropertyName( "inputs" );
            writer.WriteArrayStart();
            //[
            foreach ( InputInfo input in frame.inputs )
            {
                writer.WriteObjectStart();
                //{
                writer.WritePropertyName( "inputName" );
                writer.Write( input.inputName );

                writer.WritePropertyName( "inputType" );
                writer.Write( (int)input.inputType );

                writer.WritePropertyName( "mouseButtonNum" );
                writer.Write( input.mouseButtonNum );

                writer.WritePropertyName( "buttonState" );
                writer.Write( input.buttonState );

                writer.WritePropertyName( "axisValue" );
                writer.Write( input.axisValue );
                //}
                writer.WriteObjectEnd();
            }
            //]
            writer.WriteArrayEnd();

            writer.WritePropertyName( "syncedProperties" );
            writer.WriteObjectStart();
            //[
            foreach ( var prop in frame.syncedProperties )
            {
                writer.WritePropertyName( prop.Key );
                writer.WriteObjectStart();
                //{
                writer.WritePropertyName( "name" );
                writer.Write( prop.Value.name );

                writer.WritePropertyName( "property" );
                writer.Write( prop.Value.property );
                //}
                writer.WriteObjectEnd();
            }
            //]
            writer.WriteObjectEnd();
            //}
            writer.WriteObjectEnd();
        }
        //]
        writer.WriteArrayEnd();
        //}
        writer.WriteObjectEnd();

        return jsonB.ToString();
    }
 public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
 {
     JsonWriter jsonWriter = new JsonWriter();
         StreamWriter writer = new StreamWriter(writeStream);
         return Task.Factory.StartNew(() => jsonWriter.Write(value, writer));
 }
Beispiel #23
0
        /// <summary>
        /// Requests the JSON string.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="auth">The auth type of the route.</param>
        /// <param name="routeStyle">The route style.</param>
        /// <param name="requestArg">The request argument.</param>
        /// <param name="body">The body to upload if <paramref name="routeStyle"/>
        /// is <see cref="RouteStyle.Upload"/>.</param>
        /// <returns>The asynchronous task with the result.</returns>
        private async Task <Result> RequestJsonString(
            string host,
            string routeName,
            string auth,
            RouteStyle routeStyle,
            string requestArg,
            Stream body = null)
        {
            var hostname = this.options.HostMap[host];
            var uri      = this.GetRouteUri(hostname, routeName);

            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            if (auth == AuthType.User || auth == AuthType.Team)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.options.OAuth2AccessToken);
            }
            else if (auth == AuthType.App)
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Basic", this.options.OAuth2AccessToken);
            }
            else if (auth == AuthType.NoAuth)
            {
            }
            else
            {
                throw new ArgumentException("Invalid auth type", auth);
            }

            request.Headers.TryAddWithoutValidation("User-Agent", this.options.UserAgent);

            if (this.selectUser != null)
            {
                request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-User", this.selectUser);
            }

            if (this.selectAdmin != null)
            {
                request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-Admin", this.selectAdmin);
            }

            if (this.pathRoot != null)
            {
                request.Headers.TryAddWithoutValidation(
                    "Dropbox-Api-Path-Root",
                    JsonWriter.Write(this.pathRoot, PathRoot.Encoder));
            }

            var completionOption = HttpCompletionOption.ResponseContentRead;

            switch (routeStyle)
            {
            case RouteStyle.Rpc:
                request.Content = new StringContent(requestArg, Encoding.UTF8, "application/json");
                break;

            case RouteStyle.Download:
                request.Headers.Add(DropboxApiArgHeader, requestArg);

                // This is required to force libcurl remove default content type header.
                request.Content = new StringContent("");
                request.Content.Headers.ContentType = null;

                completionOption = HttpCompletionOption.ResponseHeadersRead;
                break;

            case RouteStyle.Upload:
                request.Headers.Add(DropboxApiArgHeader, requestArg);
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }

                request.Content = new CustomStreamContent(body);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                break;

            default:
                throw new InvalidOperationException(string.Format(
                                                        CultureInfo.InvariantCulture,
                                                        "Unknown route style: {0}",
                                                        routeStyle));
            }

            var disposeResponse = true;
            var response        = await this.getHttpClient(host).SendAsync(request, completionOption).ConfigureAwait(false);

            var requestId = GetRequestId(response);

            try
            {
                if ((int)response.StatusCode >= 500)
                {
                    var text = await response.Content.ReadAsStringAsync();

                    text = this.CheckForError(text);
                    throw new RetryException(requestId, (int)response.StatusCode, message: text, uri: uri);
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    var text = await response.Content.ReadAsStringAsync();

                    text = this.CheckForError(text);
                    throw new BadInputException(requestId, text, uri);
                }
                else if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    var reason = await response.Content.ReadAsStringAsync();

                    throw AuthException.Decode(reason, () => new AuthException(GetRequestId(response)));
                }
                else if ((int)response.StatusCode == 429)
                {
                    var reason = await response.Content.ReadAsStringAsync();

                    throw RateLimitException.Decode(reason, () => new RateLimitException(GetRequestId(response)));
                }
                else if (response.StatusCode == HttpStatusCode.Forbidden)
                {
                    var reason = await response.Content.ReadAsStringAsync();

                    throw AccessException.Decode(reason, () => new AccessException(GetRequestId(response)));
                }
                else if ((int)response.StatusCode == 422)
                {
                    var reason = await response.Content.ReadAsStringAsync();

                    throw PathRootException.Decode(reason, () => new PathRootException(GetRequestId(response)));
                }
                else if (response.StatusCode == HttpStatusCode.Conflict ||
                         response.StatusCode == HttpStatusCode.NotFound)
                {
                    var reason = await response.Content.ReadAsStringAsync();

                    return(new Result
                    {
                        IsError = true,
                        ObjectResult = reason,
                        RequestId = GetRequestId(response)
                    });
                }
                else if ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299)
                {
                    if (routeStyle == RouteStyle.Download)
                    {
                        disposeResponse = false;
                        return(new Result
                        {
                            IsError = false,
                            ObjectResult = response.Headers.GetValues(DropboxApiResultHeader).FirstOrDefault(),
                            HttpResponse = response
                        });
                    }
                    else
                    {
                        return(new Result
                        {
                            IsError = false,
                            ObjectResult = await response.Content.ReadAsStringAsync()
                        });
                    }
                }
                else
                {
                    var text = await response.Content.ReadAsStringAsync();

                    text = this.CheckForError(text);
                    throw new HttpException(requestId, (int)response.StatusCode, text, uri);
                }
            }
            finally
            {
                if (disposeResponse)
                {
                    response.Dispose();
                }
            }
        }
 public virtual String toJson()
 {
     var writer = new JsonWriter();
     return writer.Write(this);
 }
Beispiel #25
0
    public void SaveLocal()
    {
        var charWriter = new JsonWriter(new JsonFx.Serialization.DataWriterSettings(new JsonFx.Json.Resolvers.JsonResolverStrategy()));
        var charData = charWriter.Write(Characters);

        var filePath = Application.dataPath + @"/Data/save.json";

        using (var saveFile = new StreamWriter(filePath))
        {
            saveFile.Write(charData);
        }
    }
Beispiel #26
0
    public static void CreateClothes()
    {
        string rootName="DocTexts_ch";
        if(English_Caption){
            rootName="DocTexts_en";
        }
        TextAsset xmlAsset = Resources.Load<TextAsset>(rootName);
        string xmlContent = xmlAsset.text;

        StringBuilder sbuilders = new StringBuilder ();
        JsonWriter writer = new JsonWriter (sbuilders);
        writer.WriteObjectStart ();

        string[] captions = xmlContent.Split('?');
        foreach(string caption in captions)
        {
            writer.WritePropertyName ("captions");
            writer.WriteArrayStart();

            writer.WriteObjectStart ();
            string[] subtitles = caption.Split(';');

            writer.WritePropertyName ("subtitles");
            writer.WriteArrayStart();//[
            foreach (string subtitle in subtitles)
            {
                writer.WriteObjectStart();

                string[] parts=subtitle.Split('/');

                string time_from=parts[0];
                string time_to=parts[1];
                string article=parts[2];

                //1
                writer.WritePropertyName ("time_from");
                writer.Write (time_from);
                sbuilders.Append(System.Environment.NewLine);

                //2
                writer.WritePropertyName ("time_to");
                writer.Write (time_to);
                sbuilders.Append(System.Environment.NewLine);

                //3
                writer.WritePropertyName ("article");
                writer.Write (article);
                sbuilders.Append(System.Environment.NewLine);

                writer.WriteObjectEnd();
            }
            writer.WriteArrayEnd();
            writer.WriteObjectEnd();
            writer.WriteArrayEnd();
        }
        writer.WriteObjectEnd ();

        string clothFile=sbuilders.ToString();
        string desName="captions_ch.xml";
        if(English_Caption){
            desName="captions_en.xml";
        }

        System.IO.File.WriteAllText(Application.persistentDataPath+"/"+desName,clothFile);

        Debug.Log("**********UpdateClothesContent Finish***********");
    }
Beispiel #27
0
    public static void ExportScenesToJSON()
    {
        string path = EditorUtility.SaveFilePanel("SaveJason", Application.dataPath, "Scenes_Config_JSON", "txt");
        FileInfo fileInfo = new FileInfo(path);
        StreamWriter sw = fileInfo.CreateText();

        StringBuilder sb = new StringBuilder();
        JsonWriter writer = new JsonWriter(sb);
        writer.WriteObjectStart();
        writer.WritePropertyName("root");
        writer.WriteArrayStart();

        foreach (EditorBuildSettingsScene S in EditorBuildSettings.scenes)
        {
            if (S.enabled)
            {
                EditorApplication.OpenScene(S.path);
                writer.WriteObjectStart();
                writer.WritePropertyName("Scene");
                writer.WriteArrayStart();
                writer.WriteObjectStart();
                writer.WritePropertyName("SceneName");
                writer.Write(S.path);
                writer.WritePropertyName("GameObjects");
                writer.WriteArrayStart();

                foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject)))
                {
                    if (obj.transform.parent == null)
                    {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("GameObjectName");
                        writer.Write(obj.name);

                        writer.WritePropertyName("Position");
                        writer.WriteArrayStart();
                        writer.WriteObjectStart();
                        writer.WritePropertyName("X");
                        writer.Write(obj.transform.position.x.ToString("F5"));
                        writer.WritePropertyName("Y");
                        writer.Write(obj.transform.position.y.ToString("F5"));
                        writer.WritePropertyName("Z");
                        writer.Write(obj.transform.position.z.ToString("F5"));
                        writer.WriteObjectEnd();
                        writer.WriteArrayEnd();

                        writer.WritePropertyName("Rotation");
                        writer.WriteArrayStart();
                        writer.WriteObjectStart();
                        writer.WritePropertyName("X");
                        writer.Write(obj.transform.rotation.eulerAngles.x.ToString("F5"));
                        writer.WritePropertyName("Y");
                        writer.Write(obj.transform.rotation.eulerAngles.y.ToString("F5"));
                        writer.WritePropertyName("Z");
                        writer.Write(obj.transform.rotation.eulerAngles.z.ToString("F5"));
                        writer.WriteObjectEnd();
                        writer.WriteArrayEnd();

                        writer.WritePropertyName("Scale");
                        writer.WriteArrayStart();
                        writer.WriteObjectStart();
                        writer.WritePropertyName("X");
                        writer.Write(obj.transform.localScale.x.ToString("F5"));
                        writer.WritePropertyName("Y");
                        writer.Write(obj.transform.localScale.y.ToString("F5"));
                        writer.WritePropertyName("Z");
                        writer.Write(obj.transform.localScale.z.ToString("F5"));
                        writer.WriteObjectEnd();
                        writer.WriteArrayEnd();

                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteArrayEnd();
                writer.WriteObjectEnd();
                writer.WriteArrayEnd();
                writer.WriteObjectEnd();
            }
        }
        writer.WriteArrayEnd();
        writer.WriteObjectEnd();
        sw.WriteLine(sb.ToString());
        sw.Close();
        sw.Dispose();
        AssetDatabase.Refresh();
    }
Beispiel #28
0
 public override string ToString()
 {
     StringBuilder sb = new StringBuilder ();
     JsonWriter writer = new JsonWriter (sb);
     writer.WriteObjectStart ();
     writer.WritePropertyName ("id");
     writer.Write (id);
     if (type == DialogType.Dialog) {
         writer.WritePropertyName ("type");
         writer.Write ("Dialog");
         writer.WritePropertyName ("content");
         writer.Write (content);
         writer.WritePropertyName ("delay");
         writer.Write (delay);
         writer.WritePropertyName ("voice");
         writer.Write (voice);
     } else {
         writer.WritePropertyName ("type");
         writer.Write ("Select");
         writer.WritePropertyName ("select1");
         writer.Write (select[0].ToString());
         writer.WritePropertyName ("select2");
         writer.Write (select[1].ToString());
         writer.WritePropertyName ("delay");
         writer.Write (delay);
     }
     writer.WriteObjectEnd ();
     return sb.ToString ();
 }
Beispiel #29
0
        private void ExportParameterFile()
        {
            // Output the settings to INI for viewing.
            var outParamName = Path.GetFileNameWithoutExtension(m_config.ParameterFile);
            if (outParamName == null)
                return;

            var outParamPath = Path.Combine(m_config.AnalysisPath, outParamName);
            var writer = new JsonWriter<MultiAlignAnalysisOptions>();
            writer.Write(outParamPath + ".json", m_config.Analysis.Options);
        }
Beispiel #30
0
 public void WriteDamageData(JsonWriter writer)
 {
     writer.WritePropertyName("1000");
     writer.WriteObjectStart();
     writer.WritePropertyName("11");
     writer.Write(149);
     writer.WritePropertyName("12");
     writer.Write(0);
     writer.WritePropertyName("13");
     writer.Write(0);
     writer.WritePropertyName("15");
     writer.Write(22644);
     writer.WritePropertyName("17");
     writer.Write(0);
     writer.WritePropertyName("18");
     writer.Write(0);
     writer.WritePropertyName("19");
     writer.Write(0);
     writer.WritePropertyName("20");
     writer.Write(0);
     writer.WritePropertyName("21");
     writer.Write(0);
     writer.WritePropertyName("22");
     writer.Write(0);
     writer.WritePropertyName("23");
     writer.Write(0);
     writer.WritePropertyName("24");
     writer.Write(0);
     writer.WritePropertyName("25");
     writer.Write(0);
     writer.WritePropertyName("26");
     writer.Write(24520);
     writer.WritePropertyName("27");
     writer.Write(3);
     writer.WriteObjectEnd();
     writer.WritePropertyName("1001");
     writer.WriteObjectStart();
     writer.WriteObjectEnd();
     writer.WritePropertyName("1002");
     writer.WriteObjectStart();
     writer.WriteObjectEnd();
     writer.WritePropertyName("1003");
     writer.WriteObjectStart();
     writer.WriteObjectEnd();
 }
        public IRequest Marshall(CreateInstanceRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.OpsWorks");
            string   target  = "OpsWorks_20130218.CreateInstance";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";
            request.HttpMethod = "POST";

            string uriResourcePath = "/";

            request.ResourcePath = uriResourcePath;
            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();
                if (publicRequest.IsSetAmiId())
                {
                    writer.WritePropertyName("AmiId");
                    writer.Write(publicRequest.AmiId);
                }

                if (publicRequest.IsSetArchitecture())
                {
                    writer.WritePropertyName("Architecture");
                    writer.Write(publicRequest.Architecture);
                }

                if (publicRequest.IsSetAutoScalingType())
                {
                    writer.WritePropertyName("AutoScalingType");
                    writer.Write(publicRequest.AutoScalingType);
                }

                if (publicRequest.IsSetAvailabilityZone())
                {
                    writer.WritePropertyName("AvailabilityZone");
                    writer.Write(publicRequest.AvailabilityZone);
                }

                if (publicRequest.IsSetEbsOptimized())
                {
                    writer.WritePropertyName("EbsOptimized");
                    writer.Write(publicRequest.EbsOptimized);
                }

                if (publicRequest.IsSetHostname())
                {
                    writer.WritePropertyName("Hostname");
                    writer.Write(publicRequest.Hostname);
                }

                if (publicRequest.IsSetInstallUpdatesOnBoot())
                {
                    writer.WritePropertyName("InstallUpdatesOnBoot");
                    writer.Write(publicRequest.InstallUpdatesOnBoot);
                }

                if (publicRequest.IsSetInstanceType())
                {
                    writer.WritePropertyName("InstanceType");
                    writer.Write(publicRequest.InstanceType);
                }

                if (publicRequest.IsSetLayerIds())
                {
                    writer.WritePropertyName("LayerIds");
                    writer.WriteArrayStart();
                    foreach (var publicRequestLayerIdsListValue in publicRequest.LayerIds)
                    {
                        writer.Write(publicRequestLayerIdsListValue);
                    }
                    writer.WriteArrayEnd();
                }

                if (publicRequest.IsSetOs())
                {
                    writer.WritePropertyName("Os");
                    writer.Write(publicRequest.Os);
                }

                if (publicRequest.IsSetRootDeviceType())
                {
                    writer.WritePropertyName("RootDeviceType");
                    writer.Write(publicRequest.RootDeviceType);
                }

                if (publicRequest.IsSetSshKeyName())
                {
                    writer.WritePropertyName("SshKeyName");
                    writer.Write(publicRequest.SshKeyName);
                }

                if (publicRequest.IsSetStackId())
                {
                    writer.WritePropertyName("StackId");
                    writer.Write(publicRequest.StackId);
                }

                if (publicRequest.IsSetSubnetId())
                {
                    writer.WritePropertyName("SubnetId");
                    writer.Write(publicRequest.SubnetId);
                }

                if (publicRequest.IsSetVirtualizationType())
                {
                    writer.WritePropertyName("VirtualizationType");
                    writer.Write(publicRequest.VirtualizationType);
                }


                writer.WriteObjectEnd();
                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #32
0
        public IRequest Marshall(CreateConnectionRequest createConnectionRequest)
        {
            IRequest request = new DefaultRequest(createConnectionRequest, "AmazonDirectConnect");
            string   target  = "OvertureService.CreateConnection";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (createConnectionRequest != null && createConnectionRequest.IsSetLocation())
                {
                    writer.WritePropertyName("location");
                    writer.Write(createConnectionRequest.Location);
                }
                if (createConnectionRequest != null && createConnectionRequest.IsSetBandwidth())
                {
                    writer.WritePropertyName("bandwidth");
                    writer.Write(createConnectionRequest.Bandwidth);
                }
                if (createConnectionRequest != null && createConnectionRequest.IsSetConnectionName())
                {
                    writer.WritePropertyName("connectionName");
                    writer.Write(createConnectionRequest.ConnectionName);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
        public IRequest Marshall(GetItemRequest getItemRequest)
        {
            IRequest request = new DefaultRequest(getItemRequest, "AmazonDynamoDB");
            string   target  = "DynamoDB_20111205.GetItem";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";



            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (getItemRequest != null && getItemRequest.IsSetTableName())
                {
                    writer.WritePropertyName("TableName");
                    writer.Write(getItemRequest.TableName);
                }

                if (getItemRequest != null)
                {
                    Key key = getItemRequest.Key;
                    if (key != null)
                    {
                        writer.WritePropertyName("Key");
                        writer.WriteObjectStart();

                        if (key != null)
                        {
                            AttributeValue hashKeyElement = key.HashKeyElement;
                            if (hashKeyElement != null)
                            {
                                writer.WritePropertyName("HashKeyElement");
                                writer.WriteObjectStart();
                                if (hashKeyElement != null && hashKeyElement.IsSetS())
                                {
                                    writer.WritePropertyName("S");
                                    writer.Write(hashKeyElement.S);
                                }
                                if (hashKeyElement != null && hashKeyElement.IsSetN())
                                {
                                    writer.WritePropertyName("N");
                                    writer.Write(hashKeyElement.N);
                                }
                                if (hashKeyElement != null && hashKeyElement.IsSetB())
                                {
                                    writer.WritePropertyName("B");
                                    writer.Write(StringUtils.FromMemoryStream(hashKeyElement.B));
                                }

                                if (hashKeyElement != null && hashKeyElement.SS != null && hashKeyElement.SS.Count > 0)
                                {
                                    List <string> sSList = hashKeyElement.SS;
                                    writer.WritePropertyName("SS");
                                    writer.WriteArrayStart();

                                    foreach (string sSListValue in sSList)
                                    {
                                        writer.Write(StringUtils.FromString(sSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }

                                if (hashKeyElement != null && hashKeyElement.NS != null && hashKeyElement.NS.Count > 0)
                                {
                                    List <string> nSList = hashKeyElement.NS;
                                    writer.WritePropertyName("NS");
                                    writer.WriteArrayStart();

                                    foreach (string nSListValue in nSList)
                                    {
                                        writer.Write(StringUtils.FromString(nSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }

                                if (hashKeyElement != null && hashKeyElement.BS != null && hashKeyElement.BS.Count > 0)
                                {
                                    List <MemoryStream> bSList = hashKeyElement.BS;
                                    writer.WritePropertyName("BS");
                                    writer.WriteArrayStart();

                                    foreach (MemoryStream bSListValue in bSList)
                                    {
                                        writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }
                                writer.WriteObjectEnd();
                            }
                        }

                        if (key != null)
                        {
                            AttributeValue rangeKeyElement = key.RangeKeyElement;
                            if (rangeKeyElement != null)
                            {
                                writer.WritePropertyName("RangeKeyElement");
                                writer.WriteObjectStart();
                                if (rangeKeyElement != null && rangeKeyElement.IsSetS())
                                {
                                    writer.WritePropertyName("S");
                                    writer.Write(rangeKeyElement.S);
                                }
                                if (rangeKeyElement != null && rangeKeyElement.IsSetN())
                                {
                                    writer.WritePropertyName("N");
                                    writer.Write(rangeKeyElement.N);
                                }
                                if (rangeKeyElement != null && rangeKeyElement.IsSetB())
                                {
                                    writer.WritePropertyName("B");
                                    writer.Write(StringUtils.FromMemoryStream(rangeKeyElement.B));
                                }

                                if (rangeKeyElement != null && rangeKeyElement.SS != null && rangeKeyElement.SS.Count > 0)
                                {
                                    List <string> sSList = rangeKeyElement.SS;
                                    writer.WritePropertyName("SS");
                                    writer.WriteArrayStart();

                                    foreach (string sSListValue in sSList)
                                    {
                                        writer.Write(StringUtils.FromString(sSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }

                                if (rangeKeyElement != null && rangeKeyElement.NS != null && rangeKeyElement.NS.Count > 0)
                                {
                                    List <string> nSList = rangeKeyElement.NS;
                                    writer.WritePropertyName("NS");
                                    writer.WriteArrayStart();

                                    foreach (string nSListValue in nSList)
                                    {
                                        writer.Write(StringUtils.FromString(nSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }

                                if (rangeKeyElement != null && rangeKeyElement.BS != null && rangeKeyElement.BS.Count > 0)
                                {
                                    List <MemoryStream> bSList = rangeKeyElement.BS;
                                    writer.WritePropertyName("BS");
                                    writer.WriteArrayStart();

                                    foreach (MemoryStream bSListValue in bSList)
                                    {
                                        writer.Write(StringUtils.FromMemoryStream(bSListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }
                                writer.WriteObjectEnd();
                            }
                        }
                        writer.WriteObjectEnd();
                    }
                }

                if (getItemRequest != null && getItemRequest.AttributesToGet != null && getItemRequest.AttributesToGet.Count > 0)
                {
                    List <string> attributesToGetList = getItemRequest.AttributesToGet;
                    writer.WritePropertyName("AttributesToGet");
                    writer.WriteArrayStart();

                    foreach (string attributesToGetListValue in attributesToGetList)
                    {
                        writer.Write(StringUtils.FromString(attributesToGetListValue));
                    }

                    writer.WriteArrayEnd();
                }
                if (getItemRequest != null && getItemRequest.IsSetConsistentRead())
                {
                    writer.WritePropertyName("ConsistentRead");
                    writer.Write(getItemRequest.ConsistentRead);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #34
0
        /// <summary>
        /// Updates the given workspace.
        /// </summary>
        /// <param name="workspaceId">The workspace ID.</param>
        /// <param name="workspace">The workspace to be updated.</param>
        public void PutWorkspace(long workspaceId, Workspace workspace)
        {
            if (workspace == null)
            {
                throw new ArgumentException("The workspace must not be null.");
            }
            else if (workspaceId <= 0)
            {
                throw new ArgumentException("The workspace ID must be a positive integer.");
            }

            if (MergeFromRemote)
            {
                Workspace remoteWorkspace = GetWorkspace(workspaceId);
                if (remoteWorkspace != null)
                {
                    workspace.Views.CopyLayoutInformationFrom(remoteWorkspace.Views);
                    workspace.Views.Configuration.CopyConfigurationFrom(remoteWorkspace.Views.Configuration);
                }
            }

            workspace.Id = workspaceId;
            workspace.LastModifiedDate  = DateTime.UtcNow;
            workspace.LastModifiedAgent = getAgentName();
            workspace.LastModifiedUser  = getUser();

            using (HttpClient httpClient = createHttpClient())
            {
                try
                {
                    string httpMethod      = "PUT";
                    string path            = WorkspacePath + workspaceId;
                    string workspaceAsJson = "";

                    using (StringWriter stringWriter = new StringWriter())
                    {
                        if (EncryptionStrategy == null)
                        {
                            JsonWriter jsonWriter = new JsonWriter(false);
                            jsonWriter.Write(workspace, stringWriter);
                        }
                        else
                        {
                            EncryptedWorkspace  encryptedWorkspace = new EncryptedWorkspace(workspace, EncryptionStrategy);
                            EncryptedJsonWriter jsonWriter         = new EncryptedJsonWriter(false);
                            jsonWriter.Write(encryptedWorkspace, stringWriter);
                        }
                        stringWriter.Flush();
                        workspaceAsJson = stringWriter.ToString();
                        System.Console.WriteLine(workspaceAsJson);
                    }

                    AddHeaders(httpClient, httpMethod, new Uri(Url + path).AbsolutePath, workspaceAsJson, "application/json; charset=UTF-8");

                    HttpContent content = new StringContent(workspaceAsJson, Encoding.UTF8, "application/json");
                    content.Headers.ContentType.CharSet = "UTF-8";
                    string contentMd5 = new Md5Digest().Generate(workspaceAsJson);
                    string contentMd5Base64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(contentMd5));
                    content.Headers.ContentMD5 = Encoding.UTF8.GetBytes(contentMd5);

                    var    response        = httpClient.PutAsync(this.Url + path, content);
                    string responseContent = response.Result.Content.ReadAsStringAsync().Result;
                    System.Console.WriteLine(responseContent);

                    if (response.Result.StatusCode != HttpStatusCode.OK)
                    {
                        ApiResponse apiResponse = ApiResponse.Parse(responseContent);
                        throw new StructurizrClientException(apiResponse.Message);
                    }
                }
                catch (Exception e)
                {
                    throw new StructurizrClientException("There was an error putting the workspace: " + e.Message, e);
                }
            }
        }
 private static JsonWriter AppendProperty(this JsonWriter self, string propertyName, float propertyValue)
 {
     self.WritePropertyName(propertyName);
     self.Write(propertyValue);
     return(self);
 }
        public static void RunTest(TextWriter writer, string unitTestsFolder, string outputFolder)
        {
            JsonWriterSettings wsettings = new JsonWriterSettings();

            wsettings.HandleCyclicReferences = true;
            wsettings.PrettyPrint            = true;

            A a = new A();

            a.b                      = new B();
            a.b.a                    = a;
            a.a                      = a;
            a.b.a2                   = new A();
            a.b.a2.a                 = a;
            a.b.b2                   = new B();
            a.b.b2.a                 = a.b.a2;
            a.b.b2.b2                = new B();
            a.b.b2.b2.b2             = new B();
            a.b.b2.b2.b2.b2          = new B();
            a.b.b2.b2.b2.b2.b2       = new B();
            a.b.b2.b2.b2.b2.b2.b2    = new B();
            a.b.b2.b2.b2.b2.b2.b2.b2 = a.b.b2.b2;
            a.b.b2.b2.b2.b2.b2.b2.a  = a;

            a.q[2]   = a;
            a.b.a2.q = a.q;

            a.d         = new Dictionary <string, A>();
            a.d["blah"] = a;
            a.d["meh"]  = a.b.a2;

            A[] arr = new A[100];
            arr[0]   = a;
            arr[1]   = a;
            arr[2]   = new A();
            arr[3]   = arr[2];
            arr[2].a = a;
            arr[2].b = a.b;
            for (int i = 4; i < 100; i++)
            {
                arr[i] = new A();
            }

            var filePath = outputFolder + "/out.txt";

#if NETFX_CORE
            using (var wr2 = File.CreateText(filePath))
#else
            using (var wr2 = new StreamWriter(filePath, false, Encoding.UTF8))
#endif
            {
                JsonWriter wr = new JsonWriter(wr2, wsettings);
                wr.Write(a);
                wr.Write(arr);
            }

            using (var re = File.OpenText(filePath))
            {
                JsonReaderSettings rsettings = new JsonReaderSettings();
                rsettings.HandleCyclicReferences = true;

                JsonReader read = new JsonReader(re, rsettings);
                a = (A)read.Deserialize(typeof(A));

                // Do some checking
                if (a == null || a.a != a || a.b.a != a ||
                    a.b.a2.a != a || a.b.b2.a != a.b.a2 ||
                    a.b.b2.b2.b2.b2.b2.b2.b2 != a.b.b2.b2 ||
                    a.d["meh"] != a.b.a2 || a.d["blah"] != a)
                {
                    throw new System.Exception("Invalid, could not deserialize or serialize cyclic classes correctly.");
                }


                object ob = read.Deserialize(typeof(A[]));

                arr = (A[])ob;

                if (arr[0] != a || arr[3] != arr[2])
                {
                    throw new System.Exception("Invalid, Could not serialize or deserialize array correctly");
                }
            }
            //JsonReaderSettings rsettings = new JsonReaderSettings ();
            //rsettings.
            //JsonReader reader = new JsonReader ();
        }
        public IRequest Marshall(AddJobFlowStepsRequest addJobFlowStepsRequest)
        {
            IRequest request = new DefaultRequest(addJobFlowStepsRequest, "AmazonElasticMapReduce");
            string   target  = "ElasticMapReduce.AddJobFlowSteps";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (addJobFlowStepsRequest != null && addJobFlowStepsRequest.IsSetJobFlowId())
                {
                    writer.WritePropertyName("JobFlowId");
                    writer.Write(addJobFlowStepsRequest.JobFlowId);
                }

                if (addJobFlowStepsRequest != null && addJobFlowStepsRequest.Steps != null && addJobFlowStepsRequest.Steps.Count > 0)
                {
                    List <StepConfig> stepsList = addJobFlowStepsRequest.Steps;
                    writer.WritePropertyName("Steps");
                    writer.WriteArrayStart();

                    foreach (StepConfig stepsListValue in stepsList)
                    {
                        writer.WriteObjectStart();
                        if (stepsListValue != null && stepsListValue.IsSetName())
                        {
                            writer.WritePropertyName("Name");
                            writer.Write(stepsListValue.Name);
                        }
                        if (stepsListValue != null && stepsListValue.IsSetActionOnFailure())
                        {
                            writer.WritePropertyName("ActionOnFailure");
                            writer.Write(stepsListValue.ActionOnFailure);
                        }

                        if (stepsListValue != null)
                        {
                            HadoopJarStepConfig hadoopJarStep = stepsListValue.HadoopJarStep;
                            if (hadoopJarStep != null)
                            {
                                writer.WritePropertyName("HadoopJarStep");
                                writer.WriteObjectStart();

                                if (hadoopJarStep != null && hadoopJarStep.Properties != null && hadoopJarStep.Properties.Count > 0)
                                {
                                    List <KeyValue> propertiesList = hadoopJarStep.Properties;
                                    writer.WritePropertyName("Properties");
                                    writer.WriteArrayStart();

                                    foreach (KeyValue propertiesListValue in propertiesList)
                                    {
                                        writer.WriteObjectStart();
                                        if (propertiesListValue != null && propertiesListValue.IsSetKey())
                                        {
                                            writer.WritePropertyName("Key");
                                            writer.Write(propertiesListValue.Key);
                                        }
                                        if (propertiesListValue != null && propertiesListValue.IsSetValue())
                                        {
                                            writer.WritePropertyName("Value");
                                            writer.Write(propertiesListValue.Value);
                                        }
                                        writer.WriteObjectEnd();
                                    }
                                    writer.WriteArrayEnd();
                                }
                                if (hadoopJarStep != null && hadoopJarStep.IsSetJar())
                                {
                                    writer.WritePropertyName("Jar");
                                    writer.Write(hadoopJarStep.Jar);
                                }
                                if (hadoopJarStep != null && hadoopJarStep.IsSetMainClass())
                                {
                                    writer.WritePropertyName("MainClass");
                                    writer.Write(hadoopJarStep.MainClass);
                                }

                                if (hadoopJarStep != null && hadoopJarStep.Args != null && hadoopJarStep.Args.Count > 0)
                                {
                                    List <string> argsList = hadoopJarStep.Args;
                                    writer.WritePropertyName("Args");
                                    writer.WriteArrayStart();

                                    foreach (string argsListValue in argsList)
                                    {
                                        writer.Write(StringUtils.FromString(argsListValue));
                                    }

                                    writer.WriteArrayEnd();
                                }
                                writer.WriteObjectEnd();
                            }
                        }
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #38
0
        public IRequest Marshall(CreateTapesRequest createTapesRequest)
        {
            IRequest request = new DefaultRequest(createTapesRequest, "AmazonStorageGateway");
            string   target  = "StorageGateway_20130630.CreateTapes";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (createTapesRequest != null && createTapesRequest.IsSetGatewayARN())
                {
                    writer.WritePropertyName("GatewayARN");
                    writer.Write(createTapesRequest.GatewayARN);
                }
                if (createTapesRequest != null && createTapesRequest.IsSetTapeSizeInBytes())
                {
                    writer.WritePropertyName("TapeSizeInBytes");
                    writer.Write(createTapesRequest.TapeSizeInBytes);
                }
                if (createTapesRequest != null && createTapesRequest.IsSetClientToken())
                {
                    writer.WritePropertyName("ClientToken");
                    writer.Write(createTapesRequest.ClientToken);
                }
                if (createTapesRequest != null && createTapesRequest.IsSetNumTapesToCreate())
                {
                    writer.WritePropertyName("NumTapesToCreate");
                    writer.Write(createTapesRequest.NumTapesToCreate);
                }
                if (createTapesRequest != null && createTapesRequest.IsSetTapeBarcodePrefix())
                {
                    writer.WritePropertyName("TapeBarcodePrefix");
                    writer.Write(createTapesRequest.TapeBarcodePrefix);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
        public IRequest Marshall(RemoveTagsRequest removeTagsRequest)
        {
            IRequest request = new DefaultRequest(removeTagsRequest, "AmazonElasticMapReduce");
            string   target  = "ElasticMapReduce.RemoveTags";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (removeTagsRequest != null && removeTagsRequest.IsSetResourceId())
                {
                    writer.WritePropertyName("ResourceId");
                    writer.Write(removeTagsRequest.ResourceId);
                }

                if (removeTagsRequest != null && removeTagsRequest.TagKeys != null && removeTagsRequest.TagKeys.Count > 0)
                {
                    List <string> tagKeysList = removeTagsRequest.TagKeys;
                    writer.WritePropertyName("TagKeys");
                    writer.WriteArrayStart();

                    foreach (string tagKeysListValue in tagKeysList)
                    {
                        writer.Write(StringUtils.FromString(tagKeysListValue));
                    }

                    writer.WriteArrayEnd();
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
        public IRequest Marshall(UpdateLayerRequest updateLayerRequest)
        {
            IRequest request = new DefaultRequest(updateLayerRequest, "AmazonOpsWorks");
            string   target  = "OpsWorks_20130218.UpdateLayer";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";

            string uriResourcePath = "";

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (updateLayerRequest != null && updateLayerRequest.IsSetLayerId())
                {
                    writer.WritePropertyName("LayerId");
                    writer.Write(updateLayerRequest.LayerId);
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetName())
                {
                    writer.WritePropertyName("Name");
                    writer.Write(updateLayerRequest.Name);
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetShortname())
                {
                    writer.WritePropertyName("Shortname");
                    writer.Write(updateLayerRequest.Shortname);
                }
                if (updateLayerRequest != null)
                {
                    if (updateLayerRequest.Attributes != null && updateLayerRequest.Attributes.Count > 0)
                    {
                        writer.WritePropertyName("Attributes");
                        writer.WriteObjectStart();
                        foreach (string updateLayerRequestAttributesKey in updateLayerRequest.Attributes.Keys)
                        {
                            string attributesListValue;
                            bool   attributesListValueHasValue = updateLayerRequest.Attributes.TryGetValue(updateLayerRequestAttributesKey, out attributesListValue);
                            writer.WritePropertyName(updateLayerRequestAttributesKey);

                            writer.Write(attributesListValue);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetCustomInstanceProfileArn())
                {
                    writer.WritePropertyName("CustomInstanceProfileArn");
                    writer.Write(updateLayerRequest.CustomInstanceProfileArn);
                }

                if (updateLayerRequest != null && updateLayerRequest.CustomSecurityGroupIds != null && updateLayerRequest.CustomSecurityGroupIds.Count > 0)
                {
                    List <string> customSecurityGroupIdsList = updateLayerRequest.CustomSecurityGroupIds;
                    writer.WritePropertyName("CustomSecurityGroupIds");
                    writer.WriteArrayStart();

                    foreach (string customSecurityGroupIdsListValue in customSecurityGroupIdsList)
                    {
                        writer.Write(StringUtils.FromString(customSecurityGroupIdsListValue));
                    }

                    writer.WriteArrayEnd();
                }

                if (updateLayerRequest != null && updateLayerRequest.Packages != null && updateLayerRequest.Packages.Count > 0)
                {
                    List <string> packagesList = updateLayerRequest.Packages;
                    writer.WritePropertyName("Packages");
                    writer.WriteArrayStart();

                    foreach (string packagesListValue in packagesList)
                    {
                        writer.Write(StringUtils.FromString(packagesListValue));
                    }

                    writer.WriteArrayEnd();
                }

                if (updateLayerRequest != null && updateLayerRequest.VolumeConfigurations != null && updateLayerRequest.VolumeConfigurations.Count > 0)
                {
                    List <VolumeConfiguration> volumeConfigurationsList = updateLayerRequest.VolumeConfigurations;
                    writer.WritePropertyName("VolumeConfigurations");
                    writer.WriteArrayStart();

                    foreach (VolumeConfiguration volumeConfigurationsListValue in volumeConfigurationsList)
                    {
                        writer.WriteObjectStart();
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetMountPoint())
                        {
                            writer.WritePropertyName("MountPoint");
                            writer.Write(volumeConfigurationsListValue.MountPoint);
                        }
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetRaidLevel())
                        {
                            writer.WritePropertyName("RaidLevel");
                            writer.Write(volumeConfigurationsListValue.RaidLevel);
                        }
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetNumberOfDisks())
                        {
                            writer.WritePropertyName("NumberOfDisks");
                            writer.Write(volumeConfigurationsListValue.NumberOfDisks);
                        }
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetSize())
                        {
                            writer.WritePropertyName("Size");
                            writer.Write(volumeConfigurationsListValue.Size);
                        }
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetVolumeType())
                        {
                            writer.WritePropertyName("VolumeType");
                            writer.Write(volumeConfigurationsListValue.VolumeType);
                        }
                        if (volumeConfigurationsListValue != null && volumeConfigurationsListValue.IsSetIops())
                        {
                            writer.WritePropertyName("Iops");
                            writer.Write(volumeConfigurationsListValue.Iops);
                        }
                        writer.WriteObjectEnd();
                    }
                    writer.WriteArrayEnd();
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetEnableAutoHealing())
                {
                    writer.WritePropertyName("EnableAutoHealing");
                    writer.Write(updateLayerRequest.EnableAutoHealing);
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetAutoAssignElasticIps())
                {
                    writer.WritePropertyName("AutoAssignElasticIps");
                    writer.Write(updateLayerRequest.AutoAssignElasticIps);
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetAutoAssignPublicIps())
                {
                    writer.WritePropertyName("AutoAssignPublicIps");
                    writer.Write(updateLayerRequest.AutoAssignPublicIps);
                }

                if (updateLayerRequest != null)
                {
                    Recipes customRecipes = updateLayerRequest.CustomRecipes;
                    if (customRecipes != null)
                    {
                        writer.WritePropertyName("CustomRecipes");
                        writer.WriteObjectStart();

                        if (customRecipes != null && customRecipes.Setup != null && customRecipes.Setup.Count > 0)
                        {
                            List <string> setupList = customRecipes.Setup;
                            writer.WritePropertyName("Setup");
                            writer.WriteArrayStart();

                            foreach (string setupListValue in setupList)
                            {
                                writer.Write(StringUtils.FromString(setupListValue));
                            }

                            writer.WriteArrayEnd();
                        }

                        if (customRecipes != null && customRecipes.Configure != null && customRecipes.Configure.Count > 0)
                        {
                            List <string> configureList = customRecipes.Configure;
                            writer.WritePropertyName("Configure");
                            writer.WriteArrayStart();

                            foreach (string configureListValue in configureList)
                            {
                                writer.Write(StringUtils.FromString(configureListValue));
                            }

                            writer.WriteArrayEnd();
                        }

                        if (customRecipes != null && customRecipes.Deploy != null && customRecipes.Deploy.Count > 0)
                        {
                            List <string> deployList = customRecipes.Deploy;
                            writer.WritePropertyName("Deploy");
                            writer.WriteArrayStart();

                            foreach (string deployListValue in deployList)
                            {
                                writer.Write(StringUtils.FromString(deployListValue));
                            }

                            writer.WriteArrayEnd();
                        }

                        if (customRecipes != null && customRecipes.Undeploy != null && customRecipes.Undeploy.Count > 0)
                        {
                            List <string> undeployList = customRecipes.Undeploy;
                            writer.WritePropertyName("Undeploy");
                            writer.WriteArrayStart();

                            foreach (string undeployListValue in undeployList)
                            {
                                writer.Write(StringUtils.FromString(undeployListValue));
                            }

                            writer.WriteArrayEnd();
                        }

                        if (customRecipes != null && customRecipes.Shutdown != null && customRecipes.Shutdown.Count > 0)
                        {
                            List <string> shutdownList = customRecipes.Shutdown;
                            writer.WritePropertyName("Shutdown");
                            writer.WriteArrayStart();

                            foreach (string shutdownListValue in shutdownList)
                            {
                                writer.Write(StringUtils.FromString(shutdownListValue));
                            }

                            writer.WriteArrayEnd();
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetInstallUpdatesOnBoot())
                {
                    writer.WritePropertyName("InstallUpdatesOnBoot");
                    writer.Write(updateLayerRequest.InstallUpdatesOnBoot);
                }
                if (updateLayerRequest != null && updateLayerRequest.IsSetUseEbsOptimizedInstances())
                {
                    writer.WritePropertyName("UseEbsOptimizedInstances");
                    writer.Write(updateLayerRequest.UseEbsOptimizedInstances);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
        public IRequest Marshall(ListOpenWorkflowExecutionsRequest listOpenWorkflowExecutionsRequest)
        {
            IRequest request = new DefaultRequest(listOpenWorkflowExecutionsRequest, "AmazonSimpleWorkflow");
            string   target  = "SimpleWorkflowService.ListOpenWorkflowExecutions";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (listOpenWorkflowExecutionsRequest != null && listOpenWorkflowExecutionsRequest.IsSetDomain())
                {
                    writer.WritePropertyName("domain");
                    writer.Write(listOpenWorkflowExecutionsRequest.Domain);
                }

                if (listOpenWorkflowExecutionsRequest != null)
                {
                    ExecutionTimeFilter startTimeFilter = listOpenWorkflowExecutionsRequest.StartTimeFilter;
                    if (startTimeFilter != null)
                    {
                        writer.WritePropertyName("startTimeFilter");
                        writer.WriteObjectStart();
                        if (startTimeFilter != null && startTimeFilter.IsSetOldestDate())
                        {
                            writer.WritePropertyName("oldestDate");
                            writer.Write(startTimeFilter.OldestDate);
                        }
                        if (startTimeFilter != null && startTimeFilter.IsSetLatestDate())
                        {
                            writer.WritePropertyName("latestDate");
                            writer.Write(startTimeFilter.LatestDate);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                if (listOpenWorkflowExecutionsRequest != null)
                {
                    WorkflowTypeFilter typeFilter = listOpenWorkflowExecutionsRequest.TypeFilter;
                    if (typeFilter != null)
                    {
                        writer.WritePropertyName("typeFilter");
                        writer.WriteObjectStart();
                        if (typeFilter != null && typeFilter.IsSetName())
                        {
                            writer.WritePropertyName("name");
                            writer.Write(typeFilter.Name);
                        }
                        if (typeFilter != null && typeFilter.IsSetVersion())
                        {
                            writer.WritePropertyName("version");
                            writer.Write(typeFilter.Version);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                if (listOpenWorkflowExecutionsRequest != null)
                {
                    TagFilter tagFilter = listOpenWorkflowExecutionsRequest.TagFilter;
                    if (tagFilter != null)
                    {
                        writer.WritePropertyName("tagFilter");
                        writer.WriteObjectStart();
                        if (tagFilter != null && tagFilter.IsSetTag())
                        {
                            writer.WritePropertyName("tag");
                            writer.Write(tagFilter.Tag);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (listOpenWorkflowExecutionsRequest != null && listOpenWorkflowExecutionsRequest.IsSetNextPageToken())
                {
                    writer.WritePropertyName("nextPageToken");
                    writer.Write(listOpenWorkflowExecutionsRequest.NextPageToken);
                }
                if (listOpenWorkflowExecutionsRequest != null && listOpenWorkflowExecutionsRequest.IsSetMaximumPageSize())
                {
                    writer.WritePropertyName("maximumPageSize");
                    writer.Write(listOpenWorkflowExecutionsRequest.MaximumPageSize);
                }
                if (listOpenWorkflowExecutionsRequest != null && listOpenWorkflowExecutionsRequest.IsSetReverseOrder())
                {
                    writer.WritePropertyName("reverseOrder");
                    writer.Write(listOpenWorkflowExecutionsRequest.ReverseOrder);
                }

                if (listOpenWorkflowExecutionsRequest != null)
                {
                    WorkflowExecutionFilter executionFilter = listOpenWorkflowExecutionsRequest.ExecutionFilter;
                    if (executionFilter != null)
                    {
                        writer.WritePropertyName("executionFilter");
                        writer.WriteObjectStart();
                        if (executionFilter != null && executionFilter.IsSetWorkflowId())
                        {
                            writer.WritePropertyName("workflowId");
                            writer.Write(executionFilter.WorkflowId);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
                return(request);
            }
        }
Beispiel #42
0
    void PrintResults(string rawJson)
    {
        // Raw output:

        /*DB.Log(DC.Log("******** raw string from Twitter ********"));
         * DB.Log(DC.Log(rawJson));
         *
         *
         * // Turn the JSON into C# objects
         * var search = JsonReader.Deserialize<TwitterSearchResults>(rawJson);
         *
         *
         * // iterate through the array of results;
         * DB.Log(DC.Log("******** search results ********"));
         *
         *
         * foreach (var tweet in search.results) {
         *      DB.Log(DC.Log(tweet.from_user_name + " : " + tweet.text));
         * }
         *
         * DB.Log(DC.Log("******** serialize an entity ********"));
         *
         * JsonWriterSettings settings = new JsonWriterSettings();
         * settings.PrettyPrint = true;
         *
         * System.Text.StringBuilder output = new System.Text.StringBuilder();
         *
         * JsonWriter writer = new JsonWriter (output,settings);
         * writer.Write (search.results[0]);
         *
         * // this turns a C# object into a JSON string.
         * string json = output.ToString();//JsonWriter.Serialize();
         *
         * DB.Log(DC.Log(json));*/

        for (int i = 0; i < 10; i++)
        {
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            System.Text.StringBuilder output = new System.Text.StringBuilder();

            Debug.Log("+++ Serializing +++");
            JsonWriterSettings settings = new JsonWriterSettings();
            settings.PrettyPrint = false;
            settings.AddTypeConverter(new VectorConverter());

            TestClass test = new TestClass();
            test.vec.y = 128.513589999F;
            JsonWriter writer = new JsonWriter(output, settings);

            Debug.Log("+++ Writing +++");
            writer.Write(test);

            if (i == 0)
            {
                Debug.Log(output.ToString());
            }

            Debug.Log("+++ Deserializing - Init +++");
            JsonReaderSettings settings2 = new JsonReaderSettings();
            settings2.AddTypeConverter(new VectorConverter());
            JsonReader reader = new JsonReader(output.ToString(), settings2);

            Debug.Log("+++ Deserializing +++");
            TestClass deserialized = reader.Deserialize <TestClass>();

            watch.Stop();
            Debug.Log((watch.ElapsedTicks * 0.0001).ToString("0.00"));
            Debug.Log(deserialized.vec.y.ToString("r"));
        }
    }
Beispiel #43
0
        public IRequest Marshall(GetWorkflowExecutionHistoryRequest getWorkflowExecutionHistoryRequest)
        {
            IRequest request = new DefaultRequest(getWorkflowExecutionHistoryRequest, "AmazonSimpleWorkflow");
            string   target  = "SimpleWorkflowService.GetWorkflowExecutionHistory";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.0";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetDomain())
                {
                    writer.WritePropertyName("domain");
                    writer.Write(getWorkflowExecutionHistoryRequest.Domain);
                }

                if (getWorkflowExecutionHistoryRequest != null)
                {
                    WorkflowExecution execution = getWorkflowExecutionHistoryRequest.Execution;
                    if (execution != null)
                    {
                        writer.WritePropertyName("execution");
                        writer.WriteObjectStart();
                        if (execution != null && execution.IsSetWorkflowId())
                        {
                            writer.WritePropertyName("workflowId");
                            writer.Write(execution.WorkflowId);
                        }
                        if (execution != null && execution.IsSetRunId())
                        {
                            writer.WritePropertyName("runId");
                            writer.Write(execution.RunId);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetNextPageToken())
                {
                    writer.WritePropertyName("nextPageToken");
                    writer.Write(getWorkflowExecutionHistoryRequest.NextPageToken);
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetMaximumPageSize())
                {
                    writer.WritePropertyName("maximumPageSize");
                    writer.Write(getWorkflowExecutionHistoryRequest.MaximumPageSize);
                }
                if (getWorkflowExecutionHistoryRequest != null && getWorkflowExecutionHistoryRequest.IsSetReverseOrder())
                {
                    writer.WritePropertyName("reverseOrder");
                    writer.Write(getWorkflowExecutionHistoryRequest.ReverseOrder);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #44
0
        public IRequest Marshall(UpdateInstanceRequest updateInstanceRequest)
        {
            IRequest request = new DefaultRequest(updateInstanceRequest, "AmazonOpsWorks");
            string   target  = "OpsWorks_20130218.UpdateInstance";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";

            string uriResourcePath = "";

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (updateInstanceRequest != null && updateInstanceRequest.IsSetInstanceId())
                {
                    writer.WritePropertyName("InstanceId");
                    writer.Write(updateInstanceRequest.InstanceId);
                }

                if (updateInstanceRequest != null && updateInstanceRequest.LayerIds != null && updateInstanceRequest.LayerIds.Count > 0)
                {
                    List <string> layerIdsList = updateInstanceRequest.LayerIds;
                    writer.WritePropertyName("LayerIds");
                    writer.WriteArrayStart();

                    foreach (string layerIdsListValue in layerIdsList)
                    {
                        writer.Write(StringUtils.FromString(layerIdsListValue));
                    }

                    writer.WriteArrayEnd();
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetInstanceType())
                {
                    writer.WritePropertyName("InstanceType");
                    writer.Write(updateInstanceRequest.InstanceType);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetAutoScalingType())
                {
                    writer.WritePropertyName("AutoScalingType");
                    writer.Write(updateInstanceRequest.AutoScalingType);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetHostname())
                {
                    writer.WritePropertyName("Hostname");
                    writer.Write(updateInstanceRequest.Hostname);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetOs())
                {
                    writer.WritePropertyName("Os");
                    writer.Write(updateInstanceRequest.Os);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetAmiId())
                {
                    writer.WritePropertyName("AmiId");
                    writer.Write(updateInstanceRequest.AmiId);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetSshKeyName())
                {
                    writer.WritePropertyName("SshKeyName");
                    writer.Write(updateInstanceRequest.SshKeyName);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetArchitecture())
                {
                    writer.WritePropertyName("Architecture");
                    writer.Write(updateInstanceRequest.Architecture);
                }
                if (updateInstanceRequest != null && updateInstanceRequest.IsSetInstallUpdatesOnBoot())
                {
                    writer.WritePropertyName("InstallUpdatesOnBoot");
                    writer.Write(updateInstanceRequest.InstallUpdatesOnBoot);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
 public void WriteJson(JsonWriter writer)
 {
     writer.WriteObjectStart();
     if (this.eventId != null)
     {
         writer.WritePropertyName("eventId");
         writer.Write(this.eventId);
     }
     if (this.name != null)
     {
         writer.WritePropertyName("name");
         writer.Write(this.name);
     }
     if (this.metadata != null)
     {
         writer.WritePropertyName("metadata");
         writer.Write(this.metadata);
     }
     if (this.scheduleType != null)
     {
         writer.WritePropertyName("scheduleType");
         writer.Write(this.scheduleType);
     }
     if (this.repeatType != null)
     {
         writer.WritePropertyName("repeatType");
         writer.Write(this.repeatType);
     }
     if (this.absoluteBegin.HasValue)
     {
         writer.WritePropertyName("absoluteBegin");
         writer.Write(this.absoluteBegin.Value);
     }
     if (this.absoluteEnd.HasValue)
     {
         writer.WritePropertyName("absoluteEnd");
         writer.Write(this.absoluteEnd.Value);
     }
     if (this.repeatBeginDayOfMonth.HasValue)
     {
         writer.WritePropertyName("repeatBeginDayOfMonth");
         writer.Write(this.repeatBeginDayOfMonth.Value);
     }
     if (this.repeatEndDayOfMonth.HasValue)
     {
         writer.WritePropertyName("repeatEndDayOfMonth");
         writer.Write(this.repeatEndDayOfMonth.Value);
     }
     if (this.repeatBeginDayOfWeek != null)
     {
         writer.WritePropertyName("repeatBeginDayOfWeek");
         writer.Write(this.repeatBeginDayOfWeek);
     }
     if (this.repeatEndDayOfWeek != null)
     {
         writer.WritePropertyName("repeatEndDayOfWeek");
         writer.Write(this.repeatEndDayOfWeek);
     }
     if (this.repeatBeginHour.HasValue)
     {
         writer.WritePropertyName("repeatBeginHour");
         writer.Write(this.repeatBeginHour.Value);
     }
     if (this.repeatEndHour.HasValue)
     {
         writer.WritePropertyName("repeatEndHour");
         writer.Write(this.repeatEndHour.Value);
     }
     if (this.relativeTriggerName != null)
     {
         writer.WritePropertyName("relativeTriggerName");
         writer.Write(this.relativeTriggerName);
     }
     if (this.relativeDuration.HasValue)
     {
         writer.WritePropertyName("relativeDuration");
         writer.Write(this.relativeDuration.Value);
     }
     writer.WriteObjectEnd();
 }
Beispiel #46
0
        /// <summary>
        /// Return a JSON represenation of the current metrics
        /// </summary>
        /// <returns></returns>
        public string ToJSON()
        {
            if (!this.IsEnabled)
            {
                return("{ }");
            }

            var sb = new StringBuilder();
            var jw = new JsonWriter(sb);

            jw.WriteObjectStart();
            jw.WritePropertyName("properties");
            jw.WriteObjectStart();
            foreach (var kvp in this.Properties)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                var properties = kvp.Value;
                if (properties.Count > 1)
                {
                    jw.WriteArrayStart();
                }
                foreach (var obj in properties)
                {
                    if (obj == null)
                    {
                        jw.Write(null);
                    }
                    else
                    {
                        jw.Write(obj.ToString());
                    }
                }
                if (properties.Count > 1)
                {
                    jw.WriteArrayEnd();
                }
            }
            jw.WriteObjectEnd();
            jw.WritePropertyName("timings");
            jw.WriteObjectStart();
            foreach (var kvp in this.Timings)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                var timings = kvp.Value;
                if (timings.Count > 1)
                {
                    jw.WriteArrayStart();
                }
                foreach (var timing in kvp.Value)
                {
                    if (timing.IsFinished)
                    {
                        jw.Write(timing.ElapsedTime.TotalMilliseconds);
                    }
                }
                if (timings.Count > 1)
                {
                    jw.WriteArrayEnd();
                }
            }
            jw.WriteObjectEnd();
            jw.WritePropertyName("counters");
            jw.WriteObjectStart();
            foreach (var kvp in this.Counters)
            {
                jw.WritePropertyName(kvp.Key.ToString());
                jw.Write(kvp.Value);
            }
            jw.WriteObjectEnd();
            jw.WriteObjectEnd();
            return(sb.ToString());
        }
Beispiel #47
0
        public IRequest Marshall(DescribeActivityTypeRequest describeActivityTypeRequest)
        {
            IRequest request = new DefaultRequest(describeActivityTypeRequest, "AmazonSimpleWorkflow");
            string   target  = "SimpleWorkflowService.DescribeActivityType";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.0";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (describeActivityTypeRequest != null && describeActivityTypeRequest.IsSetDomain())
                {
                    writer.WritePropertyName("domain");
                    writer.Write(describeActivityTypeRequest.Domain);
                }

                if (describeActivityTypeRequest != null)
                {
                    ActivityType activityType = describeActivityTypeRequest.ActivityType;
                    if (activityType != null)
                    {
                        writer.WritePropertyName("activityType");
                        writer.WriteObjectStart();
                        if (activityType != null && activityType.IsSetName())
                        {
                            writer.WritePropertyName("name");
                            writer.Write(activityType.Name);
                        }
                        if (activityType != null && activityType.IsSetVersion())
                        {
                            writer.WritePropertyName("version");
                            writer.Write(activityType.Version);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #48
0
 private static void exportBiUserIdAsString(BiUserId value, JsonWriter writer)
 {
     writer.Write(value.biUserId);
 }
 public override String toJson()
 {
     var writer = new JsonWriter();
     return writer.Write(this);
 }
Beispiel #50
0
        public IRequest Marshall(UpdateChapCredentialsRequest updateChapCredentialsRequest)
        {
            IRequest request = new DefaultRequest(updateChapCredentialsRequest, "AmazonStorageGateway");
            string   target  = "StorageGateway_20120630.UpdateChapCredentials";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";



            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (updateChapCredentialsRequest != null && updateChapCredentialsRequest.IsSetTargetARN())
                {
                    writer.WritePropertyName("TargetARN");
                    writer.Write(updateChapCredentialsRequest.TargetARN);
                }
                if (updateChapCredentialsRequest != null && updateChapCredentialsRequest.IsSetSecretToAuthenticateInitiator())
                {
                    writer.WritePropertyName("SecretToAuthenticateInitiator");
                    writer.Write(updateChapCredentialsRequest.SecretToAuthenticateInitiator);
                }
                if (updateChapCredentialsRequest != null && updateChapCredentialsRequest.IsSetInitiatorName())
                {
                    writer.WritePropertyName("InitiatorName");
                    writer.Write(updateChapCredentialsRequest.InitiatorName);
                }
                if (updateChapCredentialsRequest != null && updateChapCredentialsRequest.IsSetSecretToAuthenticateTarget())
                {
                    writer.WritePropertyName("SecretToAuthenticateTarget");
                    writer.Write(updateChapCredentialsRequest.SecretToAuthenticateTarget);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
 private void SaveCurrentParameters()
 {
     try
     {
         var result = m_saveDialog.ShowDialog();
         if (result != null && result.Value)
         {
             var writer = new JsonWriter<MultiAlignAnalysisOptions>();
             writer.Write(m_saveDialog.FileName, m_options);
         }
     }
     catch (Exception)
     {
         //TODO: Display the error
     }
 }
    void WriteJsonToFile(string path, string fileName)
    {
        System.Text.StringBuilder strB = new System.Text.StringBuilder();
        JsonWriter jsWrite = new JsonWriter(strB);
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("Monster");

        jsWrite.WriteArrayStart();

        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("MonsterName");
        jsWrite.Write("Person");
        jsWrite.WritePropertyName("attack");
        jsWrite.Write(10);
        jsWrite.WritePropertyName("defense");
        jsWrite.Write(10);
        jsWrite.WritePropertyName("weapon");
        jsWrite.Write("Sword");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("MonsterName");
        jsWrite.Write("Animal");
        jsWrite.WritePropertyName("attack");
        jsWrite.Write(8);
        jsWrite.WritePropertyName("defense");
        jsWrite.Write(15);
        jsWrite.WritePropertyName("weapon");
        jsWrite.Write("tooth");
        jsWrite.WriteObjectEnd();
        jsWrite.WriteObjectStart();
        jsWrite.WritePropertyName("MonsterName");
        jsWrite.Write("Dragon");
        jsWrite.WritePropertyName("attack");
        jsWrite.Write(100);
        jsWrite.WritePropertyName("defense");
        jsWrite.Write(200);
        jsWrite.WritePropertyName("weapon");
        jsWrite.Write("fire breath");
        jsWrite.WriteObjectEnd();

        jsWrite.WriteArrayEnd();
        jsWrite.WriteObjectEnd();
        Debug.Log(strB);
        //创建文件目录
        DirectoryInfo dir = new DirectoryInfo(path);
        if (dir.Exists)
        {
            Debug.Log("This file is already exists");
        }
        else
        {
            Directory.CreateDirectory(path);
            Debug.Log("CreateFile");
        #if UNITY_EDITOR
            AssetDatabase.Refresh();
        #endif
        }
        //把json数据写到txt里
        StreamWriter sw;
        if (File.Exists(fileName))
        {
            //如果文件存在,那么就向文件继续附加(为了下次写内容不会覆盖上次的内容)
            sw = File.AppendText(fileName);
            Debug.Log("appendText");
        }
        else
        {
            //如果文件不存在则创建文件
            sw = File.CreateText(fileName);
            Debug.Log("createText");
        }
        sw.WriteLine(strB);
        sw.Close();
        #if UNITY_EDITOR
        AssetDatabase.Refresh();
        #endif
    }
        /// <summary>
        /// Creates a body that has JSON post data for the server to parse.
        /// </summary>
        /// <param name="request">The request that is to be altered with the post data.</param>
        /// <param name="postdata">Data to send to the server.  Must be parsable by JsonWriter.Write</param>
        private void writePostData(HttpWebRequest request, params object[] postdata)
        {
            if(postdata == null)
                return;
            createPostBoundry(request);
            StringBuilder body = new StringBuilder();
            JsonWriter json_writer = new JsonWriter(body);
            Stream write_stream;
            byte[] body_bytes;

            body.Append(boundry.boundry_start);
            body.Append("Content-Disposition: form-data; name=\"args\"\r\n\r\n");
            json_writer.Write(postdata);
            body.Append(boundry.boundry_end);

            body_bytes = Encoding.UTF8.GetBytes(body.ToString());

            request.ContentLength = body_bytes.Length;
            request.AllowWriteStreamBuffering = false;

            write_stream = request.GetRequestStream();
            write_stream.Write(body_bytes, 0, body_bytes.Length);
            write_stream.Close();
        }
Beispiel #54
0
    public void MergerJson()
    {
        StringBuilder sb = new StringBuilder ();
        JsonWriter writer = new JsonWriter (sb);

        writer.WriteObjectStart ();

        writer.WritePropertyName ("Name");
        writer.Write ("yusong");

        writer.WritePropertyName ("Age");
        writer.Write (26);

        writer.WritePropertyName ("Girl");

        writer.WriteArrayStart ();

        writer.WriteObjectStart();
        writer.WritePropertyName("name");
        writer.Write("ruoruo");
        writer.WritePropertyName("age");
        writer.Write(24);
        writer.WriteObjectEnd ();

        writer.WriteObjectStart();
        writer.WritePropertyName("name");
        writer.Write("momo");
        writer.WritePropertyName("age");
        writer.Write(26);
        writer.WriteObjectEnd ();

        writer.WriteArrayEnd();

        writer.WriteObjectEnd ();
        Debug.Log(sb.ToString ());

        JsonData jd = JsonMapper.ToObject(sb.ToString ());
        Debug.Log("name = " + (string)jd["Name"]);
        Debug.Log("Age = " + (int)jd["Age"]);
        JsonData jdItems = jd["Girl"];
        for (int i = 0; i < jdItems.Count; i++)
        {
            Debug.Log("Girl name = " + jdItems[i]["name"]);
            Debug.Log("Girl age = " + (int)jdItems[i]["age"]);
        }
    }
        public IRequest Marshall(CreateAppRequest createAppRequest)
        {
            IRequest request = new DefaultRequest(createAppRequest, "AmazonOpsWorks");
            string   target  = "OpsWorks_20130218.CreateApp";

            request.Headers["X-Amz-Target"] = target;

            request.Headers["Content-Type"] = "application/x-amz-json-1.1";


            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                int    queryPosition = uriResourcePath.IndexOf("?", StringComparison.OrdinalIgnoreCase);
                string queryString   = uriResourcePath.Substring(queryPosition + 1);
                uriResourcePath = uriResourcePath.Substring(0, queryPosition);

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;


            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (createAppRequest != null && createAppRequest.IsSetStackId())
                {
                    writer.WritePropertyName("StackId");
                    writer.Write(createAppRequest.StackId);
                }
                if (createAppRequest != null && createAppRequest.IsSetShortname())
                {
                    writer.WritePropertyName("Shortname");
                    writer.Write(createAppRequest.Shortname);
                }
                if (createAppRequest != null && createAppRequest.IsSetName())
                {
                    writer.WritePropertyName("Name");
                    writer.Write(createAppRequest.Name);
                }
                if (createAppRequest != null && createAppRequest.IsSetDescription())
                {
                    writer.WritePropertyName("Description");
                    writer.Write(createAppRequest.Description);
                }
                if (createAppRequest != null && createAppRequest.IsSetType())
                {
                    writer.WritePropertyName("Type");
                    writer.Write(createAppRequest.Type);
                }

                if (createAppRequest != null)
                {
                    Source appSource = createAppRequest.AppSource;
                    if (appSource != null)
                    {
                        writer.WritePropertyName("AppSource");
                        writer.WriteObjectStart();
                        if (appSource != null && appSource.IsSetType())
                        {
                            writer.WritePropertyName("Type");
                            writer.Write(appSource.Type);
                        }
                        if (appSource != null && appSource.IsSetUrl())
                        {
                            writer.WritePropertyName("Url");
                            writer.Write(appSource.Url);
                        }
                        if (appSource != null && appSource.IsSetUsername())
                        {
                            writer.WritePropertyName("Username");
                            writer.Write(appSource.Username);
                        }
                        if (appSource != null && appSource.IsSetPassword())
                        {
                            writer.WritePropertyName("Password");
                            writer.Write(appSource.Password);
                        }
                        if (appSource != null && appSource.IsSetSshKey())
                        {
                            writer.WritePropertyName("SshKey");
                            writer.Write(appSource.SshKey);
                        }
                        if (appSource != null && appSource.IsSetRevision())
                        {
                            writer.WritePropertyName("Revision");
                            writer.Write(appSource.Revision);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                if (createAppRequest != null && createAppRequest.Domains != null && createAppRequest.Domains.Count > 0)
                {
                    List <string> domainsList = createAppRequest.Domains;
                    writer.WritePropertyName("Domains");
                    writer.WriteArrayStart();

                    foreach (string domainsListValue in domainsList)
                    {
                        writer.Write(StringUtils.FromString(domainsListValue));
                    }

                    writer.WriteArrayEnd();
                }
                if (createAppRequest != null && createAppRequest.IsSetEnableSsl())
                {
                    writer.WritePropertyName("EnableSsl");
                    writer.Write(createAppRequest.EnableSsl);
                }

                if (createAppRequest != null)
                {
                    SslConfiguration sslConfiguration = createAppRequest.SslConfiguration;
                    if (sslConfiguration != null)
                    {
                        writer.WritePropertyName("SslConfiguration");
                        writer.WriteObjectStart();
                        if (sslConfiguration != null && sslConfiguration.IsSetCertificate())
                        {
                            writer.WritePropertyName("Certificate");
                            writer.Write(sslConfiguration.Certificate);
                        }
                        if (sslConfiguration != null && sslConfiguration.IsSetPrivateKey())
                        {
                            writer.WritePropertyName("PrivateKey");
                            writer.Write(sslConfiguration.PrivateKey);
                        }
                        if (sslConfiguration != null && sslConfiguration.IsSetChain())
                        {
                            writer.WritePropertyName("Chain");
                            writer.Write(sslConfiguration.Chain);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (createAppRequest != null)
                {
                    if (createAppRequest.Attributes != null && createAppRequest.Attributes.Count > 0)
                    {
                        writer.WritePropertyName("Attributes");
                        writer.WriteObjectStart();
                        foreach (string createAppRequestAttributesKey in createAppRequest.Attributes.Keys)
                        {
                            string attributesListValue;
                            bool   attributesListValueHasValue = createAppRequest.Attributes.TryGetValue(createAppRequestAttributesKey, out attributesListValue);
                            writer.WritePropertyName(createAppRequestAttributesKey);

                            writer.Write(attributesListValue);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }


            return(request);
        }
Beispiel #56
0
 public override string ToString()
 {
     StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
     using (JsonWriter writer = new JsonWriter(sw))
     {
         writer.SkipNullValue = true;
         writer.Write(this);
     }
     return sw.ToString();
 }
	void PrintResults(string rawJson) {
		// Raw output:
		/*DB.Log(DC.Log("******** raw string from Twitter ********"));
		DB.Log(DC.Log(rawJson));
		
		
		// Turn the JSON into C# objects
		var search = JsonReader.Deserialize<TwitterSearchResults>(rawJson);
		
		
		// iterate through the array of results;
		DB.Log(DC.Log("******** search results ********"));

	
		foreach (var tweet in search.results) {
			DB.Log(DC.Log(tweet.from_user_name + " : " + tweet.text));
		}

		DB.Log(DC.Log("******** serialize an entity ********"));

		JsonWriterSettings settings = new JsonWriterSettings();
		settings.PrettyPrint = true;
		
		System.Text.StringBuilder output = new System.Text.StringBuilder();
		
		JsonWriter writer = new JsonWriter (output,settings);
		writer.Write (search.results[0]);
		
		// this turns a C# object into a JSON string.
		string json = output.ToString();//JsonWriter.Serialize();

		DB.Log(DC.Log(json));*/
		
		for (int i=0;i<10;i++) {
		System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
		watch.Start();
		System.Text.StringBuilder output = new System.Text.StringBuilder();
		
		Debug.Log ("+++ Serializing +++");
		JsonWriterSettings settings = new JsonWriterSettings();
		settings.PrettyPrint = false;
		settings.AddTypeConverter (new VectorConverter());
		
		TestClass test = new TestClass();
		test.vec.y = 128.513589999F;
		JsonWriter writer = new JsonWriter (output,settings);
			
		Debug.Log ("+++ Writing +++");
		writer.Write (test);
		
		if (i==0)
			Debug.Log (output.ToString());
		
		Debug.Log ("+++ Deserializing - Init +++");
		JsonReaderSettings settings2 = new JsonReaderSettings();
		settings2.AddTypeConverter (new VectorConverter());
		JsonReader reader = new JsonReader(output.ToString(),settings2);
			
		Debug.Log ("+++ Deserializing +++");
		TestClass deserialized = reader.Deserialize<TestClass>();
		
		watch.Stop();
		Debug.Log ((watch.ElapsedTicks*0.0001).ToString("0.00"));
		Debug.Log (deserialized.vec.y.ToString("r"));
		}
	}
Beispiel #58
0
    public static void StoreHeroes()
    {
        //Globals.Heroes->player.heroes(string)(json path)
        //json
        string context = "[";

        for (int i = 0; i < Globals.heroes.Count; i++)
        {
            Hero       h  = Globals.heroes[i];
            JsonWriter jw = new JsonWriter();
            jw.WriteObjectStart();
            jw.WritePropertyName("id");
            jw.Write(h.id);
            jw.WritePropertyName("ename");
            jw.Write(h.ename);
            jw.WritePropertyName("imagePath");
            jw.Write(h.imagePath);
            jw.WritePropertyName("ele");
            jw.Write(h.ele);
            jw.WritePropertyName("isNearAttack");
            jw.Write(h.isNearAttack ? 1 : 0);
            jw.WritePropertyName("hp");
            jw.Write(h.infos[0]);
            jw.WritePropertyName("mp");
            jw.Write(h.infos[1]);
            jw.WritePropertyName("atk");
            jw.Write(h.infos[2]);
            jw.WritePropertyName("def");
            jw.Write(h.infos[3]);
            jw.WritePropertyName("ats");
            jw.Write(h.infos[4]);
            jw.WritePropertyName("spd");
            jw.Write(h.infos[5]);
            jw.WritePropertyName("lv");
            jw.Write(h.exps[0]);
            jw.WritePropertyName("exp");
            jw.Write(h.exps[1]);
            jw.WritePropertyName("maxExp");
            jw.Write(h.exps[2]);
            jw.WritePropertyName("loveLv");
            jw.Write(h.li.lv);
            jw.WritePropertyName("loveExp");
            jw.Write(h.li.love);
            jw.WriteObjectEnd();
            context += jw.ToString();
            if (i != Globals.heroes.Count - 1)
            {
                context += ",";
            }
        }
        context = ParseJsonData(context) + "]";
        JsonHelper.WriteJson("hero", context, "player");
    }
    public static void BuildTable()
    {
        /*
        IDictionary<string, FiniteStateMachine> npcFSM = new Dictionary<string, FiniteStateMachine>();
        GameObject npcsGameObject = GameObject.Find("NPCs");
        Transform[] npcs = npcsGameObject.GetComponentsInChildren<Transform>();
        foreach (Transform npc in npcs) {
            try {
                // All the NPCs names start with "My"
                if(npc.gameObject.name.StartsWith("My")) {
                    npcsList.Add(npc.gameObject.name, npc.gameObject.GetComponent<FiniteStateMachine>());
                    //Debug.Log(node.gameObject.name + " found.");
                }
            } catch {
                // Hashtable launches an exception when we try to add an object that is already in the Hashtable
                // If the node we are trying to insert is already in the hashtable, we simply don't add it again
            }
        }
        */

        Debug.Log ("Building the Action Lookup Table...");

        StringBuilder sb = new StringBuilder();
        JsonWriter writer = new JsonWriter(sb);

        FiniteStateMachine mechFSM = GameObject.Find("MyEnemyMech").GetComponent<FiniteStateMachine>();
        FiniteStateMachine mineBotFSM = GameObject.Find("MyEnemyMineBot").GetComponent<FiniteStateMachine>();
        FiniteStateMachine mineBot1FSM = GameObject.Find("MyEnemyMineBot1").GetComponent<FiniteStateMachine>();

        //Debug.Log ("Trying to fetch FSM...");
        IList<FSMNodeWithTransitions> mechStates = mechFSM.ReadNodes;
        IList<FSMNodeWithTransitions> mineBotStates = mineBotFSM.ReadNodes;
        IList<FSMNodeWithTransitions> mineBot1States = mineBot1FSM.ReadNodes;
        //Debug.Log ("Trying to fetch FSM... DONE!");

        writer.WriteObjectStart();
        writer.WritePropertyName("table");
        writer.WriteArrayStart();

        foreach (FSMNodeWithTransitions mechState in mechStates) {
            mechFSM.CurrentState = mechState.NodeName;
            IList<FSMTransition> mechNextActions = mechFSM.NextActions;

            foreach (FSMNodeWithTransitions mineBotState in mineBotStates) {
                mineBotFSM.CurrentState = mineBotState.NodeName;
                IList<FSMTransition> mineBotNextActions = mineBotFSM.NextActions;

                foreach (FSMNodeWithTransitions mineBot1State in mineBot1States) {
                    mineBot1FSM.CurrentState = mineBot1State.NodeName;
                    IList<FSMTransition> mineBot1NextActions = mineBot1FSM.NextActions;

                    writer.WriteObjectStart();
                    writer.WritePropertyName("currentState");
                    writer.WriteArrayStart(); //Modified
                    writer.WriteObjectStart();
                    writer.WritePropertyName("npc");
                    writer.Write(mechFSM.gameObject.name);
                    writer.WritePropertyName("state");
                    writer.Write(mechFSM.CurrentState);
                    writer.WriteObjectEnd();
                    writer.WriteObjectStart();
                    writer.WritePropertyName("npc");
                    writer.Write(mineBotFSM.gameObject.name);
                    writer.WritePropertyName("state");
                    writer.Write(mineBotFSM.CurrentState);
                    writer.WriteObjectEnd();
                    writer.WriteObjectStart();
                    writer.WritePropertyName("npc");
                    writer.Write(mineBot1FSM.gameObject.name);
                    writer.WritePropertyName("state");
                    writer.Write(mineBot1FSM.CurrentState);
                    writer.WriteObjectEnd();
                    writer.WriteArrayEnd(); //Modified
                    writer.WritePropertyName("nextActions");
                    writer.WriteArrayStart();

                    foreach (FSMTransition nextAction in mechNextActions) {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("actionName");
                        writer.Write(nextAction.ActionName);
                        writer.WritePropertyName("argument");
                        writer.Write(nextAction.Argument);
                        writer.WritePropertyName("npc");
                        writer.Write (mechFSM.gameObject.name);
                        writer.WriteObjectEnd();
                    }

                    foreach (FSMTransition nextAction in mineBotNextActions) {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("actionName");
                        writer.Write(nextAction.ActionName);
                        writer.WritePropertyName("argument");
                        writer.Write(nextAction.Argument);
                        writer.WritePropertyName("npc");
                        writer.Write (mineBotFSM.gameObject.name);
                        writer.WriteObjectEnd();
                    }

                    foreach (FSMTransition nextAction in mineBot1NextActions) {
                        writer.WriteObjectStart();
                        writer.WritePropertyName("actionName");
                        writer.Write(nextAction.ActionName);
                        writer.WritePropertyName("argument");
                        writer.Write(nextAction.Argument);
                        writer.WritePropertyName("npc");
                        writer.Write (mineBot1FSM.gameObject.name);
                        writer.WriteObjectEnd();
                    }

                    writer.WriteArrayEnd();
                    writer.WriteObjectEnd();

                }
            }
        }

        writer.WriteArrayEnd();
        writer.WriteObjectEnd();
        StreamWriter sw = new StreamWriter(@"Assets/Composition/ActionLookupTable.json");
        Debug.Log ("Writing the JSON file...");
        sw.Write(sb.ToString());
        Debug.Log ("Writing the JSON file... DONE!");
        sw.Close();
    }
        public IRequest Marshall(RegisterWorkflowTypeRequest registerWorkflowTypeRequest)
        {
            IRequest request = new DefaultRequest(registerWorkflowTypeRequest, "AmazonSimpleWorkflow");
            string   target  = "SimpleWorkflowService.RegisterWorkflowType";

            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.0";

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetDomain())
                {
                    writer.WritePropertyName("domain");
                    writer.Write(registerWorkflowTypeRequest.Domain);
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetName())
                {
                    writer.WritePropertyName("name");
                    writer.Write(registerWorkflowTypeRequest.Name);
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetVersion())
                {
                    writer.WritePropertyName("version");
                    writer.Write(registerWorkflowTypeRequest.Version);
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetDescription())
                {
                    writer.WritePropertyName("description");
                    writer.Write(registerWorkflowTypeRequest.Description);
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetDefaultTaskStartToCloseTimeout())
                {
                    writer.WritePropertyName("defaultTaskStartToCloseTimeout");
                    writer.Write(registerWorkflowTypeRequest.DefaultTaskStartToCloseTimeout);
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetDefaultExecutionStartToCloseTimeout())
                {
                    writer.WritePropertyName("defaultExecutionStartToCloseTimeout");
                    writer.Write(registerWorkflowTypeRequest.DefaultExecutionStartToCloseTimeout);
                }

                if (registerWorkflowTypeRequest != null)
                {
                    TaskList defaultTaskList = registerWorkflowTypeRequest.DefaultTaskList;
                    if (defaultTaskList != null)
                    {
                        writer.WritePropertyName("defaultTaskList");
                        writer.WriteObjectStart();
                        if (defaultTaskList != null && defaultTaskList.IsSetName())
                        {
                            writer.WritePropertyName("name");
                            writer.Write(defaultTaskList.Name);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (registerWorkflowTypeRequest != null && registerWorkflowTypeRequest.IsSetDefaultChildPolicy())
                {
                    writer.WritePropertyName("defaultChildPolicy");
                    writer.Write(registerWorkflowTypeRequest.DefaultChildPolicy);
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
                return(request);
            }
        }