Example #1
0
    public void Save(BattleStateData battleStateData)
    {
        battleStateData.ticketId = DataMng.Instance().GetResultUtilData().last_dng_req.userDungeonTicketId;
        PropertyInfo[] propertyInfos = this.GetPropertyInfos(typeof(BattleStateData), false);
        List <string>  list          = new List <string>();
        string         propInfoName  = string.Empty;
        Type           propInfoType  = null;

        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            propInfoName = propertyInfo.Name;
            propInfoType = propertyInfo.PropertyType;
            if (!this.typeNameBlackList.Any((Type c) => c == propInfoType))
            {
                if (!this.variableNameBlackList.Any((string c) => c == propInfoName))
                {
                    if (propertyInfo.PropertyType == typeof(CharacterStateControl))
                    {
                        if (propInfoName == "leaderCharacter")
                        {
                        }
                    }
                    else if (propInfoType == typeof(CharacterStateControl[]))
                    {
                        if (propInfoName == "playerCharacters")
                        {
                            List <string>           list2  = new List <string>();
                            CharacterStateControl[] array2 = propertyInfo.GetValue(battleStateData, null) as CharacterStateControl[];
                            foreach (CharacterStateControl csc in array2)
                            {
                                string item = this.ManageCharacterStateControlForValueToJson(csc);
                                list2.Add(item);
                            }
                            string item2 = JsonWriter.Serialize(list2.ToArray());
                            list.Add(item2);
                        }
                        else if (!(propInfoName == "enemies"))
                        {
                            global::Debug.LogFormat("ありえない変数名:{0}です。", new object[]
                            {
                                propInfoName
                            });
                        }
                    }
                    else if (propInfoType == typeof(CharacterStateControl[][]))
                    {
                        List <string[]>           list3  = new List <string[]>();
                        CharacterStateControl[][] array4 = propertyInfo.GetValue(battleStateData, null) as CharacterStateControl[][];
                        foreach (CharacterStateControl array6 in array4)
                        {
                            List <string> list4 = new List <string>();
                            foreach (CharacterStateControl csc2 in array6)
                            {
                                string item3 = this.ManageCharacterStateControlForValueToJson(csc2);
                                list4.Add(item3);
                            }
                            list3.Add(list4.ToArray());
                        }
                        string item4 = JsonWriter.Serialize(list3.ToArray());
                        list.Add(item4);
                    }
                    else if (propInfoType == typeof(List <ItemDropResult>))
                    {
                        List <ItemDropResult> idrs = propertyInfo.GetValue(battleStateData, null) as List <ItemDropResult>;
                        string item5 = this.ManageItemDropResultForValueToJson(idrs);
                        list.Add(item5);
                    }
                    else
                    {
                        object value = propertyInfo.GetValue(battleStateData, null);
                        string item6 = JsonWriter.Serialize(value);
                        list.Add(item6);
                    }
                }
            }
        }
        this.AppendStandardInfo(list);
        this.cachedJsonForSave = list;
        this.SaveForSystem();
    }
Example #2
0
 /// <summary>
 /// 将一个对象class转换成json字符串
 /// </summary>
 static public string ClassToJson <T>(T t) where T : class
 {
     return(JsonWriter.Serialize(t));
 }
Example #3
0
 public string Serialize(object value)
 {
     return(JsonWriter.Serialize(value));
 }
Example #4
0
        static internal IEnumerator POST(string url, Dictionary <string, string> headers, Dictionary <string, string> parameters, int timeOut, System.Action <string> completed)
        {
            UploadHandler uploadHandler = null;
            WWWForm       form          = new WWWForm();

            if (headers.ContainsKey("Content-Type"))
            {
                if (headers["Content-Type"] == "application/json")
                {
                    string jsonData = JsonWriter.Serialize(parameters);
                    byte[] bodyRaw  = Encoding.UTF8.GetBytes(jsonData);
                    uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
                }
                else
                {
                    form = new WWWForm();
                    foreach (KeyValuePair <string, string> parameter in parameters)
                    {
                        form.AddField(parameter.Key, parameter.Value);
                    }
                }
            }

            UnityWebRequest www = UnityWebRequest.Post(url, form);

            www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            www.uploadHandler   = uploadHandler;

            foreach (KeyValuePair <string, string> header in headers)
            {
                string headerKey   = Escape(header.Key);
                string headerValue = Escape(header.Value);
                www.SetRequestHeader(headerKey, headerValue);
            }

#if UNITY_2017_3_OR_NEWER
            if (timeOut > 0)
            {
                www.timeout = timeOut;
            }

            yield return(www.SendWebRequest());

            if (www.isNetworkError)
            {
                completed(www.error);
            }
            else
            {
                completed(www.downloadHandler.text);
            }
#else
            yield return(www.Send());

            if (www.isError)
            {
                completed(www.error);
            }
            else
            {
                completed(www.downloadHandler.text);
            }
#endif
        }
Example #5
0
 public void Write()
 {
     json = JsonWriter.Serialize(this);
 }
Example #6
0
    public void ReplyPlayerCharaterInfo(string json)
    {
        // JsonReader.Deserialize() : 원하는 자료형의 json을 만들 수 있다
        Dictionary <string, object> dataDic = (Dictionary <string, object>)JsonReader.Deserialize(json, typeof(Dictionary <string, object>));

        if (dataDic == null)
        {
            return;
        }

        foreach (KeyValuePair <string, object> info in dataDic)
        {
            RecvPlayerCharaterInfo data = JsonReader.Deserialize <RecvPlayerCharaterInfo>(JsonWriter.Serialize(info.Value));

            GetCharaters.Add(data.id);
            Charater_Equipment.Add(data.id, data.equipment_id);
        }
    }
    void Start()
    {
        var Students = new Student[5];

        Students [0] = new Student();
        Students [1] = new Student();
        Students [2] = new Student();
        Students [3] = new Student();
        Students [4] = new Student();

        Students [0].Name    = "Vasia";
        Students [0].Surname = "Vasiliev";
        Students [0].Sex     = Student.Orientation.Male;

        Students [1].Name    = "Olia";
        Students [1].Surname = "Oliinavina";
        Students [1].Sex     = Student.Orientation.Famale;

        Students [2].Name    = "Vanya";
        Students [2].Surname = "Vaniinin";
        Students [2].Sex     = Student.Orientation.Male;

        Students [3].Name    = "Jenin";
        Students [3].Surname = "Gabrielovas";
        Students [3].Sex     = Student.Orientation.Famale;

        Students [4].Name    = "Franklin";
        Students [4].Surname = "Bangamin";
        Students [4].Sex     = Student.Orientation.Male;



        string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Students";

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        for (int i = 0; i < Students.Length; i++)
        {
            string pathTemp = path + @"\" + Students[i].Name + " " + Students[i].Surname + @"\";
            if (!Directory.Exists(pathTemp))
            {
                Directory.CreateDirectory(pathTemp);
            }
            string pathFile = pathTemp + Students[i].Name + " " + Students[i].Surname + ".txt";
            var    data     = JsonWriter.Serialize(Students[i]);
            var    stream   = new StreamWriter(pathFile);
            stream.Write(data);
            stream.Close();
            //Debug.LogFormat("{0}", data.ToString());
        }



//		path += @"test.txt";
//
//		if(File.Exists(path)) Debug.LogFormat("{0} exist", path);
//
//
//				var stream = new StreamWriter (path);
//
//				var tempVal = new TestDataIO{ Name = "Katia", Age = 19, Flag = true, Cash = 2.5f };
//
//				string jsonViev = JsonWriter.Serialize (tempVal);
//
//				stream.Write (jsonViev);
//				stream.Close ();

//		var stream = new StreamReader (path);
//		var result = stream.ReadToEnd();
//		stream.Close ();
        //Debug.LogFormat("{0}", result);

//		Debug.LogFormat("{0}", data.ToString());



        // Update is called once per frame
    }
    public void RunCallbacks()
    {
        if (activeRequest.request == null) //if there is no active request, make the first in the queue the active request.
        {
            if (_requestQueue.Count != 0) //make sure the queue isn't empty
            {
                activeRequest = (S2SRequest)_requestQueue[0];
            }
        }
        else //on an update, if we have an active request we need to process it. This is VITAL for WEB_REQUEST becasue it handles requests differently than DOT_NET
        {

#if DOT_NET
            HttpWebResponse csharpResponse = null;

            try
            {
                LogString("Sending Request: " + activeRequest.requestData);
                csharpResponse = (HttpWebResponse)activeRequest.request.GetResponse();
            }
            catch (Exception e)
            {
                LogString("S2S Failed: " + e.ToString());
                activeRequest.request.Abort();
                activeRequest.request = null;
                _requestQueue.RemoveAt(0);
                return;
            }
#endif
#if USE_WEB_REQUEST
            string unityResponse = null;
            if(activeRequest.request.downloadHandler.isDone)
            {
                LogString("Sending Request: " + activeRequest.request);
                unityResponse = activeRequest.request.downloadHandler.text;
            }
            if(!string.IsNullOrEmpty(activeRequest.request.error))
            {
                LogString("S2S Failed: " + activeRequest.request.error);
                activeRequest.callback(activeRequest.request.error);
                activeRequest.request.Abort();
                activeRequest.request = null;
                _requestQueue.RemoveAt(0);
            }
#endif

#if DOT_NET
            if (csharpResponse != null)
            {
                //get the response body
                string responseString = ReadResponseBody(csharpResponse);
#endif
#if USE_WEB_REQUEST
            if (unityResponse != null)
            {
            //get the response body
            string responseString = unityResponse;
#endif
                Dictionary<string, object> responseBody = (Dictionary<string, object>)JsonReader.Deserialize(responseString);

                if (responseBody.ContainsKey("messageResponses"))
                {
                    //extract the map array
                    Dictionary<string, object>[] messageArray = (Dictionary<string, object>[])responseBody["messageResponses"];
                    //extract the map from the map array
                    Dictionary<string, object> messageResponses = (Dictionary<string, object>)messageArray.GetValue(0);
                    if ((int)messageResponses["status"] == 200) //success 200
                    {
                        LogString("S2S Response: " + responseString);

                        //callback
                        if (activeRequest.callback != null)
                        {
                            activeRequest.callback(JsonWriter.Serialize((Dictionary<string, object>)messageResponses));
                        }

                        //remove the request finished request form the queue
                        _requestQueue.RemoveAt(0);
                    }
                    else //failed
                    {
                        //check if its a session expiry
                        if (responseBody.ContainsKey("reason_code"))
                        {
                            if ((int)responseBody["reason_code"] == SERVER_SESSION_EXPIRED)
                            {
                                LogString("S2S session expired");
                                activeRequest.request.Abort();
                                Disconnect();
                                return;
                            }
                        }

                        LogString("S2S Failed: " + responseString);

                        //callback
                        if (activeRequest.callback != null)
                        {
                            activeRequest.callback(JsonWriter.Serialize((Dictionary<string, object>)messageResponses));
                        }

                        activeRequest.request.Abort();

                        //remove the finished request from the queue
                        _requestQueue.RemoveAt(0);
                    }
                }
                activeRequest.request = null; //reset the active request so that it can move onto the next request. 
            }
        }
        //do a heartbeat if necessary.
        if (_state == State.Authenticated)
        {
            if (DateTime.Now.Subtract(_lastHeartbeat) >= _heartbeatTimer)
            {
                SendHeartbeat(OnHeartbeatCallback);
                ResetHeartbeat();
            }
        }
    }
Example #9
0
    /// <summary>
    /// Duplicate a file in a specified folder.
    /// </summary>
    /// <param name="file">File to duplicate.</param>
    /// <param name="newTitle">New filename.</param>
    /// <param name="newParentFolder">
    ///	New parent folder. If it is null then the new file will place in root folder.
    /// </param>
    /// <returns>AsyncSuccess with File or Exception for error.</returns>
    /// <example>
    /// Copy a file to the root folder.
    /// <code>
    /// StartCoroutine(drive.DuplicateFile(someFile, someFile.Title, null));
    /// </code>
    /// </example>
    public IEnumerator DuplicateFile(File file, string newTitle, File newParentFolder)
    {
        File newFile = new File(file.ToJSON());

        newFile.Title = newTitle;

        // Set the new parent id.
        if (newParentFolder != null)
        {
            newFile.Parents = new List <string> {
                newParentFolder.ID
            }
        }
        ;
        else
        {
            newFile.Parents = new List <string> {
            }
        };

        var duplicate = DuplicateFile(file, newFile);

        while (duplicate.MoveNext())
        {
            yield return(duplicate.Current);
        }
    }

    /// <summary>
    /// Duplicate a file.
    /// </summary>
    /// <param name="file">File to duplicate.</param>
    /// <param name="newFile">New file data.</param>
    /// <returns>AsyncSuccess with File or Exception for error.</returns>
    /// <example>
    /// Copy 'someFile' to 'newFile'.
    /// <code>
    /// var newFile = new GoogleDrive.File(new Dictionary<string, object>
    ///	{
    ///		{ "title", someFile.Title + "(2)" },
    ///		{ "mimeType", someFile.MimeType },
    ///	});
    ///	newFile.Parents = new List<string> { newParentFolder.ID };
    ///
    /// StartCoroutine(drive.DuplicateFile(someFile, newFile));
    /// </code>
    /// </example>
    IEnumerator DuplicateFile(File file, File newFile)
    {
        #region Check the access token is expired
        var check = CheckExpiration();
        while (check.MoveNext())
        {
            yield return(null);
        }

        if (check.Current is Exception)
        {
            yield return(check.Current);

            yield break;
        }
        #endregion

        var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files/" +
                                          file.ID + "/copy");
        request.method = "POST";
        request.headers["Authorization"] = "Bearer " + AccessToken;
        request.headers["Content-Type"]  = "application/json";

        string metadata = JsonWriter.Serialize(newFile.ToJSON());
        request.body = Encoding.UTF8.GetBytes(metadata);

        var response = new UnityWebResponse(request);
        while (!response.isDone)
        {
            yield return(null);
        }

        JsonReader reader = new JsonReader(response.text);
        var        json   = reader.Deserialize <Dictionary <string, object> >();

        if (json == null)
        {
            yield return(new Exception(-1, "DuplicateFile response parsing failed."));

            yield break;
        }
        else if (json.ContainsKey("error"))
        {
            yield return(GetError(json));

            yield break;
        }

        yield return(new AsyncSuccess(new File(json)));
    }
Example #10
0
    /// <summary>
    /// Upload a file.
    /// </summary>
    /// <param name="file">File metadata.</param>
    /// <param name="data">Data.</param>
    /// <returns>AsyncSuccess with File or Exception for error.</returns>
    /// <example>
    /// Upload a file to the root folder.
    /// <code>
    /// var bytes = Encoding.UTF8.GetBytes("world!");
    ///
    /// var file = new GoogleDrive.File(new Dictionary<string, object>
    ///	{
    ///		{ "title", "hello.txt" },
    ///		{ "mimeType", "text/plain" },
    ///	});
    ///
    /// StartCoroutine(drive.UploadFile(file, bytes));
    /// </code>
    /// Update the file content.
    /// <code>
    /// var listFiles = drive.ListFilesByQueary("title = 'a.txt'");
    /// yield return StartCoroutine(listFiles);
    ///
    /// var files = GoogleDrive.GetResult<List<GoogleDrive.File>>(listFiles);
    /// if (files != null && files.Count > 0)
    /// {
    ///		var bytes = Encoding.UTF8.GetBytes("new content.");
    ///		StartCoroutine(drive.UploadFile(files[0], bytes));
    /// }
    /// </code>
    /// </example>
    public IEnumerator UploadFile(File file, byte[] data)
    {
        #region Check the access token is expired
        var check = CheckExpiration();
        while (check.MoveNext())
        {
            yield return(null);
        }

        if (check.Current is Exception)
        {
            yield return(check.Current);

            yield break;
        }
        #endregion

        string uploadUrl = null;

        // Start a resumable session.
        if (file.ID == null || file.ID == string.Empty)
        {
            var request = new UnityWebRequest(
                "https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable");
            request.method = "POST";
            request.headers["Authorization"]           = "Bearer " + AccessToken;
            request.headers["Content-Type"]            = "application/json";
            request.headers["X-Upload-Content-Type"]   = file.MimeType;
            request.headers["X-Upload-Content-Length"] = data.Length;

            string metadata = JsonWriter.Serialize(file.ToJSON());
            request.body = Encoding.UTF8.GetBytes(metadata);

            var response = new UnityWebResponse(request);
            while (!response.isDone)
            {
                yield return(null);
            }

            if (response.statusCode != 200)
            {
                JsonReader reader = new JsonReader(response.text);
                var        json   = reader.Deserialize <Dictionary <string, object> >();

                if (json == null)
                {
                    yield return(new Exception(-1, "UploadFile response parsing failed."));

                    yield break;
                }
                else if (json.ContainsKey("error"))
                {
                    yield return(GetError(json));

                    yield break;
                }
            }

            // Save the resumable session URI.
            uploadUrl = response.headers["Location"] as string;
        }
        else
        {
            uploadUrl = "https://www.googleapis.com/upload/drive/v2/files/" + file.ID;
        }

        // Upload the file.
        {
            var request = new UnityWebRequest(uploadUrl);
            request.method = "PUT";
            request.headers["Authorization"] = "Bearer " + AccessToken;
            request.headers["Content-Type"]  = "application/octet-stream";            // file.MimeType;
            request.body = data;

            var response = new UnityWebResponse(request);
            while (!response.isDone)
            {
                yield return(null);
            }

            JsonReader reader = new JsonReader(response.text);
            var        json   = reader.Deserialize <Dictionary <string, object> >();

            if (json == null)
            {
                yield return(new Exception(-1, "UploadFile response parsing failed."));

                yield break;
            }
            else if (json.ContainsKey("error"))
            {
                yield return(GetError(json));

                yield break;
            }

            yield return(new AsyncSuccess(new File(json)));
        }
    }
Example #11
0
    /// <summary>
    /// Insert a folder to otehr folder.
    /// </summary>
    /// <param name="parentFolder">Parent folder.</param>
    /// <returns>AsyncSuccess with File or Exception for error.</returns>
    /// <example>
    /// <code>
    /// var insert = drive.InsertFolder("new_folder_in_appdata", drive.AppData);
    /// yield return StartCoroutine(insert);
    /// </code>
    /// </example>
    public IEnumerator InsertFolder(string title, File parentFolder)
    {
        #region Check the access token is expired
        var check = CheckExpiration();
        while (check.MoveNext())
        {
            yield return(null);
        }

        if (check.Current is Exception)
        {
            yield return(check.Current);

            yield break;
        }
        #endregion

        var request = new UnityWebRequest("https://www.googleapis.com/drive/v2/files");
        request.method = "POST";
        request.headers["Authorization"] = "Bearer " + AccessToken;
        request.headers["Content-Type"]  = "application/json";

        Dictionary <string, object> data = new Dictionary <string, object>();
        data["title"]    = title;
        data["mimeType"] = "application/vnd.google-apps.folder";
        if (parentFolder != null)
        {
            data["parents"] = new List <Dictionary <string, string> >
            {
                new Dictionary <string, string>
                {
                    { "id", parentFolder.ID }
                },
            };
        }
        request.body = Encoding.UTF8.GetBytes(JsonWriter.Serialize(data));

        var response = new UnityWebResponse(request);
        while (!response.isDone)
        {
            yield return(null);
        }

        JsonReader reader = new JsonReader(response.text);
        var        json   = reader.Deserialize <Dictionary <string, object> >();

        if (json == null)
        {
            yield return(new Exception(-1, "InsertFolder response parsing failed."));

            yield break;
        }
        else if (json.ContainsKey("error"))
        {
            yield return(GetError(json));

            yield break;
        }

        yield return(new AsyncSuccess(new File(json)));
    }
        public void TestWriteObject()
        {
            var obj = new JsonObject
            {
                ["a"] = "valueA",
                ["b"] = new JsonObject
                {
                    ["x"] = 0,
                    ["y"] = JsonValue.Null,
                    ["z"] = new JsonObject(),
                },
                ["c"] = 3,
            };

            var writer = new JsonWriter {
                SortObjects = true
            };

            Assert.Equal("{\"a\":\"valueA\",\"b\":{\"x\":0,\"y\":null,\"z\":{}},\"c\":3}", writer.Serialize(obj));
        }
Example #13
0
 /// <summary>
 /// Serialize the object as JSON
 /// </summary>
 /// <param name="obj">Object to serialize</param>
 /// <returns>JSON as String</returns>
 public string Serialize(object obj)
 {
     //  return SimpleJson.SerializeObject(obj);
     return(JsonWriter.Serialize(obj));
 }
Example #14
0
            public CSharpTest(LanguageVersion?languageVersion)
            {
                this.OptionsTransforms.Add(options =>
                                           options
                                           .WithChangedOption(FormattingOptions.IndentationSize, this.Language, this.IndentationSize)
                                           .WithChangedOption(FormattingOptions.TabSize, this.Language, this.TabSize)
                                           .WithChangedOption(FormattingOptions.UseTabs, this.Language, this.UseTabs));

                this.TestState.AdditionalReferences.Add(GenericAnalyzerTest.CSharpSymbolsReference);
                this.TestState.AdditionalReferences.Add(Netstandard20Reference);
                this.TestState.AdditionalFilesFactories.Add(GenerateSettingsFile);
                this.CodeFixValidationMode = CodeFixValidationMode.None;

                if (languageVersion != null)
                {
                    this.SolutionTransforms.Add((solution, projectId) =>
                    {
                        var parseOptions = (CSharpParseOptions)solution.GetProject(projectId).ParseOptions;
                        return(solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion.Value)));
                    });
                }

                return;

                // Local function
                IEnumerable <(string filename, SourceText content)> GenerateSettingsFile()
                {
                    var settings = this.Settings;

                    StyleCopSettings defaultSettings = new StyleCopSettings();

                    if (this.IndentationSize != defaultSettings.Indentation.IndentationSize ||
                        this.UseTabs != defaultSettings.Indentation.UseTabs ||
                        this.TabSize != defaultSettings.Indentation.TabSize)
                    {
                        var indentationSettings = $@"
{{
  ""settings"": {{
    ""indentation"": {{
      ""indentationSize"": {this.IndentationSize},
      ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
      ""tabSize"": {this.TabSize}
    }}
  }}
}}
";

                        if (string.IsNullOrEmpty(settings))
                        {
                            settings = indentationSettings;
                        }
                        else
                        {
                            JsonObject indentationObject = JsonReader.Parse(indentationSettings).AsJsonObject;
                            JsonObject settingsObject    = JsonReader.Parse(settings).AsJsonObject;
                            JsonObject mergedSettings    = MergeJsonObjects(settingsObject, indentationObject);
                            using (var writer = new JsonWriter(pretty: true))
                            {
                                settings = writer.Serialize(mergedSettings);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(settings))
                    {
                        yield return(this.SettingsFileName, SourceText.From(settings));
                    }
                }
            }
    /// <summary>
    /// Save the properties of the instance.
    /// </summary>
    /// <returns>The data.</returns>
    public string SaveData()
    {
        string data = JsonWriter.Serialize(this);

        return(data);
    }
Example #16
0
    /// <summary>
    /// 拷贝更新资源包
    /// </summary>
    public static void CopyUpdateAssetBundles(string output, string dest, string version, string cdn = null)
    {
        ManifestConfig remote = new ManifestConfig();

        if (!string.IsNullOrEmpty(cdn))
        {
            string url = cdn + "/data/conf/updatefile.json";
            WWW    www = new WWW(url);
            while (!www.isDone)
            {
                ;
            }
            if (string.IsNullOrEmpty(www.error) && www.progress == 1f)
            {
                TextAsset text = www.assetBundle.LoadAsset(Path.GetFileNameWithoutExtension(url)) as TextAsset;
                remote = JsonReader.Deserialize <ManifestConfig>(text.text);
                www.assetBundle.Unload(true);
            }
            www.Dispose();
        }

        ManifestConfig local = JsonReader.Deserialize <ManifestConfig>(File.ReadAllText(assetPath + "/data/conf/updatefile.json"));

        if (local != null)
        {
            ManifestConfig manifestConfig = new ManifestConfig();
            foreach (var data in local.data.Values)
            {
                if (remote.Contains(data.name) && remote.Get(data.name).MD5 == data.MD5)
                {
                    continue;
                }
                manifestConfig.Add(data);
            }
            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }
            string updateFilePath  = dest + "/updatefile.json";
            string updateFileValue = JsonWriter.Serialize(manifestConfig);
            File.WriteAllText(updateFilePath, updateFileValue);
            AssetDatabase.Refresh();

            manifestConfig.Add(new Manifest()
            {
                name = "data/conf/manifestfile.json"
            });
            manifestConfig.Add(new Manifest()
            {
                name = "data/conf/updatefile.json"
            });

            using (MemoryStream stream = new MemoryStream())
            {
                using (ZipOutputStream zip = new ZipOutputStream(stream))
                {
                    zip.SetComment(version);
                    foreach (var data in manifestConfig.data.Values)
                    {
                        ZipEntry entry = new ZipEntry(data.name);
                        entry.DateTime = new DateTime();
                        entry.DosTime  = 0;
                        zip.PutNextEntry(entry);

                        string filepPth = output + "/" + data.name;
                        var    bytes    = File.ReadAllBytes(filepPth);
                        zip.Write(bytes, 0, bytes.Length);
                    }

                    zip.Finish();
                    zip.Flush();

                    var fileBytes = new byte[stream.Length];
                    Array.Copy(stream.GetBuffer(), fileBytes, fileBytes.Length);

                    string platform = "PC";
#if UNITY_ANDROID
                    platform = "Android";
#elif UNITY_IOS
                    platform = "iOS";
#endif
                    DateTime dt   = DateTime.Now;
                    string   date = string.Format("{0}.{1}.{2}_{3}.{4}.{5}", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
                    string   md5  = Util.GetMD5(fileBytes);
                    File.WriteAllBytes(string.Format("{0}/{1}_{2}_{3}_{4}.zip", dest, platform, version, date, md5), fileBytes);
                }
            }
            File.Delete(updateFilePath);
            AssetDatabase.Refresh();
        }
    }
Example #17
0
    private void ProcessRequest(CukunityRequest req)
    {
        Hashtable res = new Hashtable();

        try
        {
            // read data from client as a JSON dictionary
            Hashtable jsonReq = JsonReader.Deserialize <Hashtable>(req.Request);

            string cmdName = GetJsonString(jsonReq, "command");

            if ((cmdName == null) || (cmdName.Length == 0))
            {
                Debug.LogError("Cukunity: missing command in client's request (" + req.Request + ")");
                res["error"] = "MissingCommandError";
                req.OnProcessed(JsonWriter.Serialize(res));
                return;
            }

            CukunityCommand cmd;

            switch (cmdName)
            {
            case "get_screen":
                cmd = new CukunityGetScreenCommand();
                break;

            case "get_scene":
                cmd = new CukunityGetSceneCommand();
                break;

            case "get_level":
                cmd = new CukunityGetLevelCommand();
                break;

            case "load_level":
                cmd = new CukunityLoadLevelCommand();
                break;

#if UNITY_IPHONE
            case "touch_screen":
                cmd = new CukunityTouchScreenCommand();
                break;
#endif

            default:
                Debug.LogError("Cukunity: unknown command in client's request (" + req.Request + ")");
                res["error"] = "UnknownCommandError";
                req.OnProcessed(JsonWriter.Serialize(res));
                return;
            }

            cmd.Process(jsonReq, res);
        }
        catch (Exception e)
        {
            Debug.LogError("Cukunity: exception while processing client's request (" + e + ")");
            res["error"] = "ServerError";
        }
        // reply to client
        req.OnProcessed(JsonWriter.Serialize(res));
    }
            public CSharpTest(LanguageVersion?languageVersion)
            {
                this.ReferenceAssemblies = GenericAnalyzerTest.ReferenceAssemblies;

                this.OptionsTransforms.Add(options =>
                                           options
                                           .WithChangedOption(FormattingOptions.IndentationSize, this.Language, this.IndentationSize)
                                           .WithChangedOption(FormattingOptions.TabSize, this.Language, this.TabSize)
                                           .WithChangedOption(FormattingOptions.UseTabs, this.Language, this.UseTabs));

                this.TestState.AdditionalFilesFactories.Add(GenerateSettingsFile);
                this.CodeActionValidationMode = CodeActionValidationMode.None;

                if (languageVersion != null)
                {
                    this.SolutionTransforms.Add((solution, projectId) =>
                    {
                        var parseOptions = (CSharpParseOptions)solution.GetProject(projectId).ParseOptions;
                        return(solution.WithProjectParseOptions(projectId, parseOptions.WithLanguageVersion(languageVersion.Value)));
                    });
                }

                this.SolutionTransforms.Add((solution, projectId) =>
                {
                    var corlib = solution.GetProject(projectId).MetadataReferences.OfType <PortableExecutableReference>()
                                 .Single(reference => Path.GetFileName(reference.FilePath) == "mscorlib.dll");
                    var system = solution.GetProject(projectId).MetadataReferences.OfType <PortableExecutableReference>()
                                 .Single(reference => Path.GetFileName(reference.FilePath) == "System.dll");

                    return(solution
                           .RemoveMetadataReference(projectId, corlib)
                           .RemoveMetadataReference(projectId, system)
                           .AddMetadataReference(projectId, corlib.WithAliases(new[] { "global", "corlib" }))
                           .AddMetadataReference(projectId, system.WithAliases(new[] { "global", "system" })));
                });

                return;

                // Local function
                IEnumerable <(string filename, SourceText content)> GenerateSettingsFile()
                {
                    var settings = this.Settings;

                    StyleCopSettings defaultSettings = new StyleCopSettings();

                    if (this.IndentationSize != defaultSettings.Indentation.IndentationSize ||
                        this.UseTabs != defaultSettings.Indentation.UseTabs ||
                        this.TabSize != defaultSettings.Indentation.TabSize)
                    {
                        var indentationSettings = $@"
{{
  ""settings"": {{
    ""indentation"": {{
      ""indentationSize"": {this.IndentationSize},
      ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
      ""tabSize"": {this.TabSize}
    }}
  }}
}}
";

                        if (string.IsNullOrEmpty(settings))
                        {
                            settings = indentationSettings;
                        }
                        else
                        {
                            JsonObject indentationObject = JsonReader.Parse(indentationSettings).AsJsonObject;
                            JsonObject settingsObject    = JsonReader.Parse(settings).AsJsonObject;
                            JsonObject mergedSettings    = MergeJsonObjects(settingsObject, indentationObject);
                            using (var writer = new JsonWriter(pretty: true))
                            {
                                settings = writer.Serialize(mergedSettings);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(settings))
                    {
                        yield return(this.SettingsFileName, SourceText.From(settings));
                    }
                }
            }
Example #19
0
 public static string SerializeToString(object objectInstance)
 {
     return(JsonWriter.Serialize(objectInstance));
 }
        public string SerializeToJsonString(object objectToSerialize)
        {
            string json = JsonWriter.Serialize(objectToSerialize);

            return(PubnubCryptoBase.ConvertHexToUnicodeChars(json));
        }
Example #21
0
    void FixedUpdate()
    {
        timeLeft          -= Time.deltaTime;
        timeBar.fillAmount = timeLeft / 60.0f;
        if (timeBar.fillAmount >= 0.5f)
        {
            timeBar.color = _color [0];
        }
        else if (timeBar.fillAmount >= 0.2f)
        {
            timeBar.color = _color [1];
        }
        else if (timeBar.fillAmount > 0)
        {
            timeBar.color   = _color [2];
            camEdge.enabled = true;
        }

        if (timeBar.fillAmount <= 0)
        {
            theEnd.SetActive(true);
            camEdge._edge.enabled = false;
            camEdge.enabled       = false;
            //SceneManager.LoadSceneAsync ("scLobby");
            //Debug.Log ("Game Over!!");
        }

        userInfo.currentScore = score;
        if (userInfo.maxScore < score)
        {
            userInfo.maxScore = score;
        }
        string jsonUserInfo = JsonWriter.Serialize(userInfo);

        PlayerPrefs.SetString("JsonUserInfo", jsonUserInfo);

        txtScore.text = score.ToString();

        if (delayTime < 0.25f)
        {
            delayTime += Time.deltaTime;
            return;
        }
        else
        {
            bool isPuzzle = GetPuzzle();
            if (change == true && !isPuzzle)
            {
                change = false;
                int temp = arrayPuzzle [beforeNum];
                arrayPuzzle [beforeNum] = arrayPuzzle [afterNum];
                arrayPuzzle [afterNum]  = temp;

                GameObject tempObj = objPuzzle [beforeNum];
                Vector3    before  = objPuzzle [beforeNum].transform.position;
                Vector3    after   = objPuzzle [afterNum].transform.position;
                objPuzzle [beforeNum] = objPuzzle [afterNum];
                objPuzzle [afterNum]  = tempObj;
                objPuzzle [beforeNum].GetComponent <PuzzleCtrl> ().nextPos = before;
                objPuzzle [afterNum].GetComponent <PuzzleCtrl> ().nextPos  = after;
                delayTime = 0;
                return;
            }
            else if (isPuzzle)
            {
                change    = false;
                delayTime = 0;
                return;
            }
            else
            {
                change = false;
            }
        }

        Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                if (hit.collider.CompareTag("Puzzle"))
                {
                    selectPuzzle = true;
                    int y = (int)hit.collider.transform.position.y + 3;
                    int x = (int)hit.collider.transform.position.x + (int)((width - 1) * 0.5f);
                    beforeNum = y * width + x;
                }
                if (hit.collider.CompareTag("Item"))
                {
                    selectPuzzle = false;
                    int y = (int)hit.collider.transform.position.y + 3;
                    int x = (int)hit.collider.transform.position.x + (int)((width - 1) * 0.5f);
                    for (int i = 0; i < width; i++)
                    {
                        if (arrayPuzzle [y * width + i] == 7)
                        {
                            for (int j = 0; j < 14; j++)
                            {
                                if (arrayPuzzle [j * width + i] == 6)
                                {
                                    for (int k = 0; k < width; k++)
                                    {
                                        objPuzzle [j * width + k].GetComponent <RotationItems> ().enabled = true;
                                        score += 1;
                                    }
                                }
                                objPuzzle [j * width + i].GetComponent <RotationItems> ().enabled = true;
                                score += 1;
                            }
                        }
                        objPuzzle [y * width + i].GetComponent <RotationItems> ().enabled = true;
                        score += 1;
                    }
                    beforeNum = y * width + x;
                }
                if (hit.collider.CompareTag("Item2"))
                {
                    selectPuzzle = false;
                    int y = (int)hit.collider.transform.position.y + 3;
                    int x = (int)hit.collider.transform.position.x + (int)((width - 1) * 0.5f);
                    for (int i = 0; i < 14; i++)
                    {
                        if (arrayPuzzle [i * width + x] == 6)
                        {
                            for (int j = 0; j < width; j++)
                            {
                                if (arrayPuzzle [j * width + i] == 7)
                                {
                                    for (int k = 0; k < 14; k++)
                                    {
                                        objPuzzle [k * width + j].GetComponent <RotationItems> ().enabled = true;
                                        score += 1;
                                    }
                                }
                                objPuzzle [i * width + j].GetComponent <RotationItems> ().enabled = true;
                                score += 1;
                            }
                        }
                        objPuzzle [i * width + x].GetComponent <RotationItems> ().enabled = true;
                        score += 1;
                    }
                    beforeNum = y * width + x;
                }
            }
        }
        if (Input.GetMouseButton(0))
        {
            if (Physics.Raycast(ray, out hit, Mathf.Infinity))
            {
                if (hit.collider.CompareTag("Puzzle") || hit.collider.CompareTag("Item") || hit.collider.CompareTag("Item2"))
                {
                    int y = (int)hit.collider.transform.position.y + 3;
                    int x = (int)hit.collider.transform.position.x + (int)((width - 1) * 0.5f);
                    afterNum = y * width + x;
                    if (beforeNum != afterNum && change == false && selectPuzzle == true &&
                        (beforeNum == afterNum + 1 || beforeNum == afterNum - 1 || beforeNum == afterNum + width || beforeNum == afterNum - width))
                    {
                        change       = true;
                        selectPuzzle = false;
                        int temp = arrayPuzzle [beforeNum];
                        arrayPuzzle [beforeNum] = arrayPuzzle [afterNum];
                        arrayPuzzle [afterNum]  = temp;

                        GameObject tempObj = objPuzzle [beforeNum];
                        Vector3    before  = objPuzzle [beforeNum].transform.position;
                        Vector3    after   = objPuzzle [afterNum].transform.position;
                        objPuzzle [beforeNum] = objPuzzle [afterNum];
                        objPuzzle [afterNum]  = tempObj;
                        objPuzzle [beforeNum].GetComponent <PuzzleCtrl> ().nextPos = before;
                        objPuzzle [afterNum].GetComponent <PuzzleCtrl> ().nextPos  = after;
                        delayTime = 0;
                    }
                }
            }
        }
    }
        private void DuplicateItemGridView()
        {
            var selectedIdList = m_GridView.GetSelection();

            if (selectedIdList.Length == 0)
            {
                return;
            }

            List <int> idList = new List <int>();

            try
            {
                m_TreeView.EndNameEditing(true);
                m_GridView.EndRename(false);
                foreach (var id in selectedIdList)
                {
                    var item = m_GridViewDataSource.GetItemByIndex(m_GridViewDataSource.GetItemIndexByItemId(id)) as FolderGridItem;
                    FolderTreeViewItem treeItem       = null;
                    FolderTreeViewItem parentTreeItem = null;
                    if (item.IsFolder)
                    {
                        treeItem       = m_TreeView.FindItem(item.Id) as FolderTreeViewItem;
                        parentTreeItem = treeItem.parent as FolderTreeViewItem;
                    }
                    else
                    {
                        parentTreeItem = m_TreeView.FindItem(item.ParentId) as FolderTreeViewItem;
                        foreach (var child in parentTreeItem.FileList)
                        {
                            if (child.id == item.Id)
                            {
                                treeItem = child;
                                break;
                            }
                        }
                    }

                    if (item.IsFolder)
                    {
                        var newPath = EditorFileUtility.GetNewFolder(item.Path);
                        FileUtil.CopyFileOrDirectory(item.Path, newPath);
                        var newItem = JsonReader.Deserialize(JsonWriter.Serialize(treeItem, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), true) as FolderTreeViewItem;

                        newItem.id       = m_FolderTreeViewGroup.GetDataContainer().GetAutoID();
                        newItem.FileList = null;
                        newItem.children = null;
                        idList.Add(newItem.id);

                        newItem.Path        = newPath;
                        newItem.displayName = new DirectoryInfo(newPath).Name;

                        var newGridItem = JsonReader.Deserialize(JsonWriter.Serialize(item, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), item.GetType(), true) as FolderGridItem;
                        newGridItem.Id          = newItem.id;
                        newGridItem.Path        = newItem.Path;
                        newGridItem.DisplayName = newItem.displayName;
                        m_GridViewDataSource.ItemList.Add(newGridItem);

                        parentTreeItem.AddChild(newItem);
                        var comparator = new AlphanumComparator.AlphanumComparator();
                        parentTreeItem.children.Sort((viewItem, treeViewItem) =>
                        {
                            return(comparator.Compare(viewItem.displayName, treeViewItem.displayName));
                        });
                    }
                    else
                    {
                        var newPath = EditorFileUtility.GetNewFile(item.Path);
                        FileUtil.CopyFileOrDirectory(item.Path, newPath);
                        var newItem = JsonReader.Deserialize(JsonWriter.Serialize(treeItem, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), true) as FolderTreeViewItem;
                        newItem.id = m_FolderTreeViewGroup.GetDataContainer().GetAutoID();
                        idList.Add(newItem.id);
                        newItem.Path        = newPath;
                        newItem.displayName = Path.GetFileNameWithoutExtension(newPath);
                        parentTreeItem.FileList.Add(newItem);

                        var newGridItem = JsonReader.Deserialize(JsonWriter.Serialize(item, new JsonWriterSettings()
                        {
                            MaxDepth = Int32.MaxValue
                        }), item.GetType(), true) as FolderGridItem;
                        newGridItem.Id          = newItem.id;
                        newGridItem.Path        = newItem.Path;
                        newGridItem.DisplayName = newItem.displayName;
                        m_GridViewDataSource.ItemList.Add(newGridItem);
                    }
                }

                m_GridView.SetSelection(idList.ToArray(), false);
            }
            catch (Exception e)
            {
                Debug.LogError("复制item出错:" + e);
            }
            finally
            {
                m_FolderTreeViewGroup.GetDataContainer().UpdateValidItems();
                m_TreeView.data.RefreshData();
                UpdateGridViewContent();
                if (m_ConfigSource != null)
                {
                    m_ConfigSource.SetConfigDirty();
                }
            }
        }
Example #23
0
 public void OnClickMakeGameButton()
 {
     this.gameObject.SetActive(false);
     sendToServerSignal.Dispatch(JsonWriter.Serialize(new JoinGame(gamename.text)));
 }
Example #24
0
 public string Serialize(object obj)
 {
     return(JsonWriter.Serialize(obj));
 }
Example #25
0
        /// <summary>
        /// Handles the response bundle and calls registered callbacks.
        /// </summary>
        /// <param name="in_jsonData">The received message bundle.</param>
        private void HandleResponseBundle(string in_jsonData)
        {
            m_brainCloudClientRef.Log("INCOMING: " + in_jsonData);

            JsonResponseBundleV2 bundleObj = JsonReader.Deserialize <JsonResponseBundleV2>(in_jsonData);
            long receivedPacketId          = (long)bundleObj.packetId;

            if (m_expectedIncomingPacketId == NO_PACKET_EXPECTED || m_expectedIncomingPacketId != receivedPacketId)
            {
                m_brainCloudClientRef.Log("Dropping duplicate packet");
                return;
            }
            m_expectedIncomingPacketId = NO_PACKET_EXPECTED;

            Dictionary <string, object>[] responseBundle = bundleObj.responses;
            Dictionary <string, object>   response       = null;
            Exception firstThrownException = null;
            int       numExceptionsThrown  = 0;

            for (int j = 0; j < responseBundle.Length; ++j)
            {
                response = responseBundle[j];
                int    statusCode = (int)response["status"];
                string data       = "";

                //
                // It's important to note here that a user error callback *might* call
                // ResetCommunications() based on the error being returned.
                // ResetCommunications will clear the m_serviceCallsInProgress List
                // effectively removing all registered callbacks for this message bundle.
                // It's also likely that the developer will want to call authenticate next.
                // We need to ensure that this is supported as it's the best way to
                // reset the brainCloud communications after a session invalid or network
                // error is triggered.
                //
                // This is safe to do from the main thread but just in case someone
                // calls this method from another thread, we lock on m_serviceCallsWaiting
                //
                ServerCall sc = null;
                lock (m_serviceCallsWaiting)
                {
                    if (m_serviceCallsInProgress.Count > 0)
                    {
                        sc = m_serviceCallsInProgress[0] as ServerCall;
                        m_serviceCallsInProgress.RemoveAt(0);
                    }
                }

                // its a success response
                if (statusCode == 200)
                {
                    if (response[OperationParam.ServiceMessageData.Value] != null)
                    {
                        Dictionary <string, object> responseData = (Dictionary <string, object>)response[OperationParam.ServiceMessageData.Value];

                        // send the data back as not formatted
                        data = JsonWriter.Serialize(response);

                        // save the session ID
                        try
                        {
                            if (getJsonString(responseData, OperationParam.ServiceMessageSessionId.Value, null) != null)
                            {
                                m_sessionID       = (string)responseData[OperationParam.ServiceMessageSessionId.Value];
                                m_isAuthenticated = true;  // TODO confirm authentication
                            }

                            // save the profile ID
                            if (getJsonString(responseData, OperationParam.ServiceMessageProfileId.Value, null) != null)
                            {
                                m_brainCloudClientRef.AuthenticationService.ProfileId = (string)responseData[OperationParam.ServiceMessageProfileId.Value];
                            }
                        }
                        catch (Exception e)
                        {
                            m_brainCloudClientRef.Log("SessionId or ProfileId do not exist " + e.ToString());
                        }
                    }

                    // now try to execute the callback
                    if (sc != null)
                    {
                        if (sc.GetService().Equals(ServiceName.PlayerState.Value) &&
                            (sc.GetOperation().Equals(ServiceOperation.FullReset.Value) ||
                             sc.GetOperation().Equals(ServiceOperation.Reset.Value) ||
                             sc.GetOperation().Equals(ServiceOperation.Logout.Value)))

                        {
                            // we reset the current player or logged out
                            // we are no longer authenticated
                            m_isAuthenticated = false;
                            m_brainCloudClientRef.AuthenticationService.ProfileId = null;
                        }
                        else if (sc.GetService().Equals(ServiceName.Authenticate.Value) &&
                                 sc.GetOperation().Equals(ServiceOperation.Authenticate.Value))
                        {
                            ProcessAuthenticate(data);
                        }

                        // // only process callbacks that are real
                        if (sc.GetCallback() != null)
                        {
                            try
                            {
                                sc.GetCallback().OnSuccessCallback(data);
                            }
                            catch (Exception e)
                            {
                                m_brainCloudClientRef.Log(e.StackTrace);
                                ++numExceptionsThrown;
                                if (firstThrownException == null)
                                {
                                    firstThrownException = e;
                                }
                            }
                        }
                    }
                }
                else if (statusCode >= 400 || statusCode == 202)
                {
                    object reasonCodeObj = null, statusMessageObj = null;
                    int    reasonCode    = 0;
                    string statusMessage = "";

                    if (response.TryGetValue("reason_code", out reasonCodeObj))
                    {
                        reasonCode = (int)reasonCodeObj;
                    }
                    if (response.TryGetValue("status_message", out statusMessageObj))
                    {
                        statusMessage = (string)statusMessageObj;
                    }

                    if (reasonCode == ReasonCodes.SESSION_EXPIRED ||
                        reasonCode == ReasonCodes.SESSION_NOT_FOUND_ERROR)
                    {
                        m_isAuthenticated = false;
                        m_brainCloudClientRef.Log("Received session expired or not found, need to re-authenticate");
                    }

                    // now try to execute the callback
                    if (sc != null && sc.GetCallback() != null)
                    {
                        try
                        {
                            sc.GetCallback().OnErrorCallback(statusCode, reasonCode, statusMessage);
                        }
                        catch (Exception e)
                        {
                            m_brainCloudClientRef.Log(e.StackTrace);
                            ++numExceptionsThrown;
                            if (firstThrownException == null)
                            {
                                firstThrownException = e;
                            }
                        }
                    }
                }
            }

            if (firstThrownException != null)
            {
                m_activeRequest = null; // to make sure we don't reprocess this message

                throw new Exception("User callback handlers threw " + numExceptionsThrown + " exception(s)."
                                    + " See the Unity log for callstacks or inner exception for first exception thrown.",
                                    firstThrownException);
            }
        }
Example #26
0
    static public string JsonByObject(object value)
    {
        string t = JsonWriter.Serialize(value);

        return(t);
    }
Example #27
0
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            Solution solution = new AdhocWorkspace()
                                .CurrentSolution
                                .AddProject(projectId, TestProjectName, TestProjectName, language)
                                .WithProjectCompilationOptions(projectId, compilationOptions)
                                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            if (MetadataReferences.SystemRuntimeReference != null)
            {
                solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemRuntimeReference);
            }

            if (MetadataReferences.SystemValueTupleReference != null)
            {
                solution = solution.AddMetadataReference(projectId, MetadataReferences.SystemValueTupleReference);
            }

            solution.Workspace.Options =
                solution.Workspace.Options
                .WithChangedOption(FormattingOptions.IndentationSize, language, this.IndentationSize)
                .WithChangedOption(FormattingOptions.TabSize, language, this.TabSize)
                .WithChangedOption(FormattingOptions.UseTabs, language, this.UseTabs);

            var settings = this.GetSettings();

            StyleCopSettings defaultSettings = new StyleCopSettings();

            if (this.IndentationSize != defaultSettings.Indentation.IndentationSize ||
                this.UseTabs != defaultSettings.Indentation.UseTabs ||
                this.TabSize != defaultSettings.Indentation.TabSize)
            {
                var indentationSettings = $@"
{{
  ""settings"": {{
    ""indentation"": {{
      ""indentationSize"": {this.IndentationSize},
      ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
      ""tabSize"": {this.TabSize}
    }}
  }}
}}
";

                if (string.IsNullOrEmpty(settings))
                {
                    settings = indentationSettings;
                }
                else
                {
                    JsonObject indentationObject = JsonReader.Parse(indentationSettings).AsJsonObject;
                    JsonObject settingsObject    = JsonReader.Parse(settings).AsJsonObject;
                    JsonObject mergedSettings    = MergeJsonObjects(settingsObject, indentationObject);
                    using (var writer = new JsonWriter(pretty: true))
                    {
                        settings = writer.Serialize(mergedSettings);
                    }
                }
            }

            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, this.GetSettingsFileName(), settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;

            return(solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose)));
        }
Example #28
0
        public static void SerializeStatic(ref JsonWriter writer, ImmutableDictionary <string, TValue> value, JsonSerializerOptions options)
#endif
        {
            if (value is null)
            {
                writer.WriteNull();
                return;
            }

            if (writer.Depth >= options.MaxDepth)
            {
                writer.Writer.WriteEmptyObject();
                return;
            }

            ++writer.Depth;
            writer.WriteBeginObject();

            var e = value.GetEnumerator();

            try
            {
                if (!e.MoveNext())
                {
                    goto END;
                }

                var tuple        = e.Current;
                var propertyName = tuple.Key;
                Debug.Assert(propertyName != null, nameof(propertyName) + " != null");
                writer.WritePropertyName(propertyName);
#if !ENABLE_IL2CPP
                var valueSerializer = options.Resolver.GetSerializeStatic <TValue>();
                if (valueSerializer.ToPointer() != null)
                {
                    writer.Serialize(tuple.Value, options, valueSerializer);
                    while (e.MoveNext())
                    {
                        writer.WriteValueSeparator();
                        tuple        = e.Current;
                        propertyName = tuple.Key;
                        Debug.Assert(propertyName != null, nameof(propertyName) + " != null");
                        writer.WritePropertyName(propertyName);
                        writer.Serialize(tuple.Value, options, valueSerializer);
                    }
                    goto END;
                }
#endif
                var valueFormatter = options.Resolver.GetFormatterWithVerify <TValue>();
                valueFormatter.Serialize(ref writer, tuple.Value, options);
                while (e.MoveNext())
                {
                    writer.WriteValueSeparator();
                    tuple        = e.Current;
                    propertyName = tuple.Key;
                    Debug.Assert(propertyName != null, nameof(propertyName) + " != null");
                    writer.WritePropertyName(propertyName);
                    valueFormatter.Serialize(ref writer, tuple.Value, options);
                }
            }
            finally
            {
                e.Dispose();
            }

END:
            writer.WriteEndObject();
            --writer.Depth;
        }
Example #29
0
    /// <summary>
    /// 更新文件
    /// </summary>
    /// <param name="output"></param>
    public static void BuildUpdateFile(string output, string cdn = null)
    {
        ManifestConfig newManifestConfig = GetManifest(output);

        ManifestConfig oldManifestConfig = newManifestConfig;

        if (!string.IsNullOrEmpty(cdn))
        {
            string url = cdn + "/data/conf/manifestfile.json";
            WWW    www = new WWW(url);
            while (!www.isDone)
            {
                ;
            }
            if (string.IsNullOrEmpty(www.error) && www.progress == 1f)
            {
                TextAsset text = www.assetBundle.LoadAsset(Path.GetFileNameWithoutExtension(url)) as TextAsset;
                oldManifestConfig = JsonReader.Deserialize <ManifestConfig>(text.text);
                www.assetBundle.Unload(false);
            }
            www.Dispose();
        }

        ManifestConfig manifestConfig = new ManifestConfig();

        if (!string.IsNullOrEmpty(cdn))
        {
            string url = cdn + "/data/conf/updatefile.json";
            WWW    www = new WWW(url);
            while (!www.isDone)
            {
                ;
            }
            if (string.IsNullOrEmpty(www.error) && www.progress == 1f)
            {
                TextAsset text = www.assetBundle.LoadAsset(Path.GetFileNameWithoutExtension(url)) as TextAsset;
                manifestConfig = JsonReader.Deserialize <ManifestConfig>(text.text);
                www.assetBundle.Unload(false);
            }
            www.Dispose();
        }

        // 写入Manifest
        if (newManifestConfig != null && oldManifestConfig != null)
        {
            foreach (var data in newManifestConfig.data.Values)
            {
                if (oldManifestConfig.Contains(data.name) && oldManifestConfig.Get(data.name).MD5 == data.MD5)
                {
                    continue;
                }
                manifestConfig.Add(data);
            }

            // 写入到文件
            File.WriteAllText(assetPath + "/data/conf/updatefile.json", JsonWriter.Serialize(manifestConfig));
            // 刷新
            AssetDatabase.Refresh();
            // Build清单文件
            AssetBundleBuild[] builds = new AssetBundleBuild[1];
            builds[0].assetBundleName    = "data/conf/updatefile";
            builds[0].assetBundleVariant = null;
            builds[0].assetNames         = new string[1] {
                assetPath + "/data/conf/updatefile.json"
            };
            BuildPipeline.BuildAssetBundles(output, builds, BuildAssetBundleOptions.ChunkBasedCompression, buildTarget);
        }
    }
Example #30
0
 /// <summary>
 /// Returns a JSON string representing the state of the object.
 /// </summary>
 /// <remarks>
 /// The resulting string is safe to be inserted as is into dynamically
 /// generated JavaScript or JSON code.
 /// </remarks>
 /// <param name="pretty">
 /// Indicates whether the resulting string should be formatted for human-readability.
 /// </param>
 public string ToString(bool pretty)
 {
     return(JsonWriter.Serialize(this, pretty));
 }
Example #31
0
        void IJsonSerializable.Serialize(JsonWriter writer)
        {
            // Types
            if (Types != null && Types.Any())
            {
                writer.WritePropertyName("types");
                writer.WriteStartObject();
                foreach (var type in Types)
                {
                    writer.WritePropertyName(type);
                    writer.WriteRawValue(GetTypeJson(type));
                }
                writer.WriteEndObject();
            }

            if (Instances != null && Instances.Any())
            {
                writer.WritePropertyName("instances");
                writer.WriteStartObject();

                foreach (var typeItem in Instances)
                {
                    writer.WritePropertyName(typeItem.Key);
                    writer.WriteStartObject();

                    // Serialize static property values
                    if (typeItem.Value.StaticProperties.Count > 0)
                    {
                        writer.WritePropertyName("static");
                        writer.Serialize(
                            typeItem.Value.StaticProperties.ToDictionary(
                            property => property.Name,
                            property => JsonConverter.GetPropertyValue(property, property.DeclaringType)));
                    }

                    // Serialize instances
                    foreach (var instanceItem in typeItem.Value.Instances)
                    {
                        writer.WritePropertyName(instanceItem.Key);
                        writer.Serialize(instanceItem.Value);
                    }

                    writer.WriteEndObject();
                }

                writer.WriteEndObject();
            }

            if (Conditions != null && Conditions.Any())
            {
                writer.WritePropertyName("conditions");
                writer.Serialize(Conditions);
            }

            if (Events != null && Events.Any())
            {
                writer.WritePropertyName("events");
                writer.Serialize(Events);
            }

            if (Model != null && Model.Any())
            {
                writer.WritePropertyName("model");
                writer.Serialize(Model);
            }

            if (ServerInfo != null)
            {
                writer.WritePropertyName("serverInfo");
                writer.Serialize(ServerInfo);
            }

            if (Changes != null && Changes.Any())
            {
                writer.WritePropertyName("changes");
                writer.Serialize(Changes.Where(modelEvent => !(modelEvent is ModelValueChangeEvent) || ExoWeb.IncludeInClientModel(((ModelValueChangeEvent)modelEvent).Property)));
            }
        }