Newtonsoft.Json.Linq.JObject.Parse(string)

Here are the examples of the csharp api Newtonsoft.Json.Linq.JObject.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

745 Examples 7

19 View Source File : MangaDexDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            string jsonUrl = MangaDexHelper.MANGADEX_URL + "/api/chapter/" + chapter.GetID();
            string jsonString;

            using (var wc = new WebClient())
            {
                jsonString = wc.DownloadString(jsonUrl);
            }

            JObject jobj = JObject.Parse(jsonString);

            string server = (string)jobj["server"];
            string hash = (string)jobj["hash"];

            // string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
            List<string> page_array = new List<string>();
            IJEnumerable<JToken> jtokens = jobj["page_array"].Values();
            foreach(JToken t in jtokens)
            {
                page_array.Add((string)t);
            }

            foreach (string file in page_array)
            {
                if (server == "/data/")
                    server = MangaDexHelper.MANGADEX_URL + "/data/";

                string imgUrl = server + hash + "/" + file;

                FileInfo imgFile = new FileInfo(
                    Path.Combine(
                        chapter.GetChapterRoot().FullName, 
                        ConvertToNumericFileName(file)
                ));

                if (File.Exists(imgFile.FullName))
                    if (imgFile.Length <= 0)
                        File.Delete(imgFile.FullName);

                DownloadAsync(new Uri(imgUrl), imgFile.FullName);
            }
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override void _Create(string mangaUrl)
        {
            id = mangaUrl;
            string jsonText = MangaDexHelper.GetMangaJSON(mangaUrl);

            JObject jobj = JObject.Parse(jsonText);
            string replacedle = (string)jobj["manga"]["replacedle"];

            string lang_code = "gb";

            FileHelper.CreateFolder(FileHelper.APP_ROOT, MangaDexHelper.GetMangaID(mangaUrl));

            MangaInfo info = new MangaInfo()
            {
                Type = "manga",
                Source = "mangadex",
                Id = MangaDexHelper.GetMangaID(mangaUrl),
                Name = replacedle,
                LangCode = lang_code,
                Group = "^any-group",
                UserName = replacedle,
                Chapter = "1",
                Page = "1",
                Latest = "1"
            };

            string output = JsonConvert.SerializeObject(info);
            File.WriteAllText(Path.Combine(mangaRoot.FullName, "manga.json"), output);            

            _Load(false);
            GetSetPrunedChapters(true);
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override Chapter[] GetSetPrunedChapters(bool overrideDlc)
        {
            chapters.Clear();
            List<Chapter> result = new List<Chapter>();
            string jsonText = MangaDexHelper.GetMangaJSON(id);
            JObject jobj = JObject.Parse(jsonText);

            String[] dlc = GetDLChapters();
            bool doFullSetup;

            if (!overrideDlc)
            {
                doFullSetup = true;
            }
            else // override
            {
                doFullSetup = false;
            }

            foreach (JProperty p in jobj["chapter"])
            {
                JToken value = p.Value;
                if (value.Type == JTokenType.Object)
                {
                    JObject o = (JObject)value;
                    string chapNum = (String)o["chapter"];
                    if (usergroup == "^any-group")
                    {
                        if (((string)o["lang_code"]).Equals(userlang))
                        {
                            if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
                            {
                                string chapID = ((JProperty)value.Parent).Name;
                                DirectoryInfo chapDir = null; // Only create folder if doing full setup
                                if (doFullSetup)
                                    chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
                                Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
                                chapters.Add(newchapter);
                                result.Add(newchapter);
                            }
                        }
                    }
                    else
                    {
                        if (((string)o["lang_code"]).Equals(userlang) && ((string)o["group_name"]).Equals(usergroup))
                        {
                            if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
                            {
                                string chapID = ((JProperty)value.Parent).Name;
                                DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
                                Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
                                chapters.Add(newchapter);
                                result.Add(newchapter);
                            }
                        }
                    }

                }
            }
            chapters = result;
            return result.ToArray(); 
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override Chapter[] GetUpdates()
        {
            List<Chapter> result = new List<Chapter>();
            string jsonText = MangaDexHelper.GetMangaJSON(MangaDexHelper.GetMangaUrl(GetID()));
            JObject jobj = JObject.Parse(jsonText);

            String[] dlc = GetDLChapters();
            bool doFullSetup = true;

            foreach (JProperty p in jobj["chapter"])
            {
                JToken value = p.Value;
                if (value.Type == JTokenType.Object)
                {
                    JObject o = (JObject)value;
                    string chapNum = (String)o["chapter"];
                    if (usergroup == "^any-group")
                    {
                        if (((string)o["lang_code"]).Equals(userlang))
                        {
                            if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
                            {
                                string chapID = ((JProperty)value.Parent).Name;
                                if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
                                {
                                    DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
                                    Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
                                    chapters.Add(newchapter);
                                    result.Add(newchapter);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (((string)o["lang_code"]).Equals(userlang) && ((string)o["group_name"]).Equals(usergroup))
                        {
                            // Console.WriteLine(chapNum);
                            string chapID = ((JProperty)value.Parent).Name;
                            if (!Directory.Exists(Path.Combine(mangaRoot.FullName, chapID)))
                            {
                                if ((!doFullSetup) || (doFullSetup && dlc == null) || (doFullSetup && dlc[0].Equals("-1")) || (doFullSetup && dlc.Contains(chapNum)))
                                {
                                    DirectoryInfo chapDir = FileHelper.CreateFolder(mangaRoot, chapID);
                                    Chapter newchapter = new Chapter(chapDir, chapID, chapNum, doFullSetup);
                                    chapters.Add(newchapter);
                                    result.Add(newchapter);
                                }
                            }
                        }
                    }
                    
                }
            }
            return result.ToArray();
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override string[] GetGroups(string langCode)
        {
            List<string> result = new List<string>();
            string jsonText = MangaDexHelper.GetMangaJSON(MangaDexHelper.GetMangaUrl(GetID()));
            JObject jobj = JObject.Parse(jsonText);

            foreach (JProperty p in jobj["chapter"])
            {
                JToken value = p.Value;
                if (value.Type == JTokenType.Object)
                {
                    JObject o = (JObject)value;
                    if (((string)o["lang_code"]).Equals(langCode))
                    {
                        string groupName = (String)o["group_name"];
                        if (!result.Contains(groupName))
                        {
                            result.Add(groupName);
                        }
                    }
                }
            }
            return result.ToArray();
        }

19 View Source File : MangaDex.cs
License : GNU General Public License v3.0
Project Creator : 9vult

public override string[] GetLangs()
        {
            List<string> result = new List<string>();
            string jsonText = MangaDexHelper.GetMangaJSON(MangaDexHelper.GetMangaUrl(GetID()));
            JObject jobj = JObject.Parse(jsonText);

            foreach (JProperty p in jobj["chapter"])
            {
                JToken value = p.Value;
                if (value.Type == JTokenType.Object)
                {
                    JObject o = (JObject)value;
                    string langCode = (string)o["lang_code"];
                    if (!result.Contains(langCode))
                    {
                        result.Add(langCode);
                    }
                }
            }
            return result.ToArray();
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

private static Dictionary<WexPair, T> MakeRequest<T>(string method, IEnumerable<WexPair> pairlist, Func<JContainer, T> valueReader, Dictionary<string, string> args = null)
        {
/*
	        bool ignoreInvalid = true;
	        var queryresult = ignoreInvalid 
				? QueryIgnoreInvalid(method, pairlist, args) 
				: Query(method, pairlist, args);
*/
			var queryresult = Query(method, pairlist, args);
            var resobj = JObject.Parse(queryresult);

            if (resobj["success"] != null && resobj.Value<int>("success") == 0)
				throw new WexApiException(resobj.Value<string>("error"));

            var r = ReadPairDict(resobj, valueReader);
            return r;
        }

19 View Source File : BitstampApi.cs
License : MIT License
Project Creator : aabiryukov

private static void CheckBitstampError(string json)
	    {
			if(!json.Contains("error"))
				return;

			var jsonObject = JObject.Parse(json);
			var errorText = jsonObject["error"];
			
			if (errorText != null)
				throw new BitstampException("Bitstamp error: " + errorText);
	    }

19 View Source File : BitstampApi.cs
License : MIT License
Project Creator : aabiryukov

public static Ticker GetTicker()
        {
			const string queryStr = "https://www.bitstamp.net/api/ticker/";
			var response = WebApi.Query(queryStr);
	        var jobj = JObject.Parse(response);
			return Ticker.ReadFromJObject(jobj);
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public static decimal GetFee(WexPair pair)
        {
            string queryStr = string.Format(CultureInfo.InvariantCulture, WebApi.RootUrl + "/api/2/{0}/fee", WexPairHelper.ToString(pair));
	        var json = WebApi.Query(queryStr);
            return JObject.Parse(json).Value<decimal>("trade");
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public static Ticker GetTicker()
		{
			const string queryStr = "https://" + apiHost + "/data/ticker?market=btccny";
			var response = WebApi.Query(queryStr);
			var jobj = JObject.Parse( response );
			return Ticker.ReadFromJObject(jobj["ticker"]);
		}

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool CancelOrder(int orderId)
        {
	        var args = new NameValueCollection
	        {
                {"coin_type", ((int)CoinType.Btc).ToString(CultureInfo.InvariantCulture)},
                {"id", orderId.ToString(CultureInfo.InvariantCulture)}
	        };

	        var response = DoMethod2("cancel_order", args);
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public TradeAnswer Trade(WexPair pair, TradeType type, decimal rate, decimal amount)
        {
			var args = new NameValueDictionary
            {
                { "pair", WexPairHelper.ToString(pair) },
                { "type", TradeTypeHelper.ToString(type) },
                { "rate", DecimalToString(rate) },
                { "amount", DecimalToString(amount) }
            };
            var result = JObject.Parse(Query("Trade", args));
            if (result.Value<int>("success") == 0)
				throw new WexApiException(result.Value<string>("error"));
            return TradeAnswer.ReadFromJObject(result["return"] as JObject);
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public CancelOrderAnswer CancelOrder(int orderId)
        {
			var args = new NameValueDictionary
            {
                { "order_id", orderId.ToString(CultureInfo.InvariantCulture) }
            };
            var result = JObject.Parse(Query("CancelOrder", args));

            if (result.Value<int>("success") == 0)
				throw new WexApiException(result.Value<string>("error"));

            return CancelOrderAnswer.ReadFromJObject(result["return"] as JObject);
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public int PlaceOrder(double price, double amount, MarketType market)
        {
            string regPrice = "", regAmount = "", method = "", mParams = "";
            switch (market)
            {
                case MarketType.BTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F4", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCCNY:
					regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                case MarketType.LTCBTC:
					regPrice = price.ToString("F4", CultureInfo.InvariantCulture);
					regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
                    break;
                default://"ALL" is not supported
                    throw new BTCChinaException("PlaceOrder", "N/A", "Market not supported.");
            }
            if (regPrice.StartsWith("-", StringComparison.Ordinal))
                regPrice = "null";
			if (regAmount.StartsWith("-", StringComparison.Ordinal))
            {
                regAmount = regAmount.TrimStart('-');
                method = "sellOrder2";
            }
            else
            {
                method = "buyOrder2";
            }

//          mParams = regPrice + "," + regAmount;
            mParams = "\"" + regPrice + "\",\"" + regAmount + "\"";
            //not default market
            if (market != MarketType.BTCCNY)
                mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";

            var response = DoMethod(BuildParams(method, mParams));
	        var jsonObject = JObject.Parse(response);
	        var orderId = jsonObject.Value<int>("result");

	        return orderId;
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool cancelOrder(int orderID, MarketType market=MarketType.BTCCNY)
        {
            const string method = "cancelOrder";
            string mParams = orderID.ToString(CultureInfo.InvariantCulture);
            //all is not supported
            if (market == MarketType.ALL)
                throw new BTCChinaException(method, "N/A", "Market:ALL is not supported.");
            //not default market
            if (market != MarketType.BTCCNY)
                mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";

            var response = DoMethod(BuildParams(method, mParams));
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

19 View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov

public IEnumerable<Order> getOrders(bool openonly = true, MarketType markets = MarketType.BTCCNY, uint limit = 1000, uint offset = 0, bool withdetails = false)
        {
            //due to the complexity of parameters, all default values are explicitly set.
            const string method = "getOrders";
			string mParams = openonly.ToString(CultureInfo.InvariantCulture).ToLowerInvariant() +
                ",\"" + System.Enum.GetName(typeof(MarketType), markets) + "\"," +
				limit.ToString(CultureInfo.InvariantCulture) + "," +
				offset.ToString(CultureInfo.InvariantCulture) + "," +
				withdetails.ToString(CultureInfo.InvariantCulture).ToLowerInvariant();
            var response = DoMethod(BuildParams(method, mParams));

			var jobj = JObject.Parse(response);
			if (jobj["result"] != null)
			{
				var orders = jobj["result"]["order"];
				foreach (var orderItem in orders)
				{
					var order = Order.ReadFromJObject(orderItem);
					yield return order;
				}
			};
        }

19 View Source File : HuobiAPI.cs
License : MIT License
Project Creator : aabiryukov

public static Ticker GetTicker()
		{
			const string queryStr = "staticmarket/ticker_btc_json.js";
			var response = WebApi.Query(queryStr);
			var jobj = JObject.Parse( response );
			return Ticker.ReadFromJObject(jobj);
		}

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

public static Ticker GetTicker()
		{
			const string queryStr = "ticker.do?ticker.do?symbol=btc_usd";
			var response = WebApi.Query(queryStr);
			var jobj = JObject.Parse( response );
			return Ticker.ReadFromJObject(jobj);
		}

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

private int InternalTrade(decimal price, decimal amount, bool isSell)
	    {
			var args = new NameValueCollection
	        {
		        {"symbol", "btc_usd"},
		        {"type", isSell ? "sell" : "buy"},
				{"price", price.ToString(CultureInfo.InvariantCulture)},
				{"amount", amount.ToString(CultureInfo.InvariantCulture)}
	        };

			var response = DoMethod2("trade", args);
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");
		    if (!success)
		    {
			    var errorCode = jsonObject.Value<string>("error_code");
				throw new OKCoinException("InternalTrade", "Failed to create order: " + (isSell ? "Sell" : "Buy") + ". ErrorCode=" + errorCode);
		    }

		    var orderId = jsonObject.Value<int>("order_id");

			return orderId;
		}

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

private static JObject CheckResult(string response)
	    {
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");
			if (!success)
			{
				var errorCode = jsonObject.Value<string>("error_code");
				throw new OKCoinException("CheckResult", "Failed OKCoin request. ErrorCode=" + errorCode);
			}

		    return jsonObject;
	    }

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

public bool CancelOrder(int orderId)
        {
	        var args = new NameValueCollection
	        {
		        {"symbol", "btc_usd"},
		        {"order_id", orderId.ToString(CultureInfo.InvariantCulture)}
	        };

	        var response = DoMethod2("cancel_order", args);
			var jsonObject = JObject.Parse(response);
			var success = jsonObject.Value<bool>("result");

	        return success;
        }

19 View Source File : OKCoinAPI.cs
License : MIT License
Project Creator : aabiryukov

public UserInfo GetUserInfo()
        {
			var response = DoMethod2("userinfo", null);
			var jobj = JObject.Parse(response);

	        var result = jobj.Value<bool>("result");
			if(!result)
				throw new OKCoinException("GetUserInfo", "Request failed");

			var userInfo = UserInfo.ReadFromJObject(jobj["info"]);
	        return userInfo;
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

public static Ticker GetTicker(WexPair pair)
        {
			string queryStr = string.Format(CultureInfo.InvariantCulture, WebApi.RootUrl + "/api/2/{0}/ticker", WexPairHelper.ToString(pair));
	        var json = WebApi.Query(queryStr);
			return Ticker.ReadFromJObject(JObject.Parse(json)["ticker"] as JObject);
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : adamtiger

static public Data2D ReadDataFromFile(string filePath)
        {
            JObject model = JObject.Parse(File.ReadAllText(filePath));

            List<List<List<List<double>>>> weight = model.SelectToken("data").Select(
                            batch => batch.Select(
                                    row => row.Select(
                                            col => col.Select(
                                                    channel => (double)channel
                                                ).ToList()
                                        ).ToList()
                                ).ToList()
                        ).ToList();

            int batchNum = weight.Count;
            int rowNum = weight[0].Count;
            int colNum = weight[0][0].Count;
            int chNum = weight[0][0][0].Count;

            Data2D data = new Data2D(rowNum, colNum, chNum, batchNum);

            for (int row = 0; row < rowNum; ++row)
            {
                for (int col = 0; col < colNum; ++col)
                {
                    for (int chnl = 0; chnl < chNum; ++chnl)
                    {
                        for (int batch = 0; batch < batchNum; ++batch)
                        {
                            data[row, col, chnl, batch] = weight[batch][row][col][chnl];
                        }
                    }
                }
            }

            return data;
        }

19 View Source File : AppSettingsValidator.cs
License : MIT License
Project Creator : afaniuolo

public bool Validate()
		{
			bool isValid = true;

			// Load Schema
			JsonSchema appSettingsSchema = LoadAppSettingsSchema();

			// Validate
			// Read json file
			var appSettingsFileContent = System.IO.File.ReadAllText(AppSettingsFilePath);
			var appSettingsFileJson = JObject.Parse(appSettingsFileContent);

			// Break with message in Console if a json file is not valid
			if (!appSettingsFileJson.IsValid(appSettingsSchema))
			{
				Console.WriteLine();
				Console.WriteLine("  Execution aborted!");
				Console.WriteLine(string.Format("  The following file doesn't contain a valid JSON object: {0}", AppSettingsFilePath));
				Console.WriteLine();
				return false;
			}

			return isValid;
		}

19 View Source File : GuiderImpl.cs
License : MIT License
Project Creator : agalasso

private void _Worker()
        {
            try
            {
                while (!m_terminate)
                {
                    string line = m_conn.ReadLine();
                    if (line == null)
                    {
                        // phd2 disconnected
                        // todo: re-connect (?)
                        break;
                    }

                    Debug.WriteLine(String.Format("L: {0}", line));

                    JObject j;
                    try
                    {
                        j = JObject.Parse(line);
                    }
                    catch (JsonReaderException ex)
                    {
                        Debug.WriteLine(String.Format("ignoring invalid json from server: {0}: {1}", ex.Message, line));
                        continue;
                    }

                    if (j.ContainsKey("jsonrpc"))
                    {
                        // a response
                        Debug.WriteLine(String.Format("R: {0}", line));
                        lock (m_sync)
                        {
                            m_response = j;
                            System.Threading.Monitor.Pulse(m_sync);
                        }
                    }
                    else
                    {
                        handle_event(j);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("caught exception in worker thread: {0}", ex.ToString()));
            }
            finally
            {
                m_conn.Terminate();
            }
        }

19 View Source File : MetadataValidator.cs
License : MIT License
Project Creator : afaniuolo

public bool Validate()
		{
			bool isValid = true;

			// Load Schema
			JsonSchema metadataSchema = LoadMetadataSchema();

			// Load all metadata files
			var metadataFiles = _metadataProvider.GetAllMetadataFiles();

			// Validate each file
			foreach (string metadataFile in metadataFiles)
			{
				// Read json file
				var metadataFileContent = System.IO.File.ReadAllText(metadataFile);
				var metadataFileJson = JObject.Parse(metadataFileContent);

				// Break with message in Console if a json file is not valid
				if (!metadataFileJson.IsValid(metadataSchema))
				{
					Console.WriteLine();
					Console.WriteLine("  Execution aborted!");
					Console.WriteLine(string.Format("  The following metadata file doesn't contain a valid JSON object: {0}", metadataFile));
					Console.WriteLine();
					return false;
				}
			}

			return isValid;
		}

19 View Source File : SyncManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

void netPollHandler(object sender, DownloadDataCompletedEventArgs args)
        {
            if (isClosed || !listenNet)
                return;

            NetDataMtx.WaitOne();
            try
            {
                string jsonString = Encoding.UTF8.GetString(args.Result);

                JObject o = JObject.Parse(jsonString);
                if (o.TryGetValue("timeout", out JToken value))
                {
                    //timeout occured
                }

                if (o.TryGetValue("error", out value))
                {
                    Console.WriteLine(String.Format("Error occured: {0}", value));
                }

                if (o.TryGetValue("events", out value))
                {
                    foreach (var ev in value)
                    {
                        try
                        {
                            var dataStr = ev["data"];

                            var data = JObject.Parse(dataStr.Value<string>());

                            var player = data["player"].Value<string>();
                            var state = data["state"].Value<string>();
                            var location = data["location"].Value<string>();

                            UInt64.TryParse(ev["timestamp"].Value<string>(), out UInt64 timestamp);
                            if (timestamp > netTimestamp)
                                netTimestamp = timestamp;

                            if (NetData.ContainsKey(player))
                            {
                                var playerData = NetData[player];
                                if (playerData.timestamp < timestamp)
                                    NetData[player] = new NetPlayer(Convert.FromBase64String(state), location, timestamp);
                            }
                            else
                            {
                                NetData[player] = new NetPlayer(Convert.FromBase64String(state), location, timestamp);
                            }

                            isInvalidated = true;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(String.Format("Error!: {0}", e));
                        }
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Error!: {0}", e));
            }
            finally
            {
                NetDataMtx.ReleaseMutex();
            }

            RegisterNetListener(netTimestamp);
        }

19 View Source File : SyncManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

void starsPollHandler(object sender, DownloadDataCompletedEventArgs args)
        {
            if (isClosed)
                return;

            try
            {
                string jsonString = Encoding.UTF8.GetString(args.Result);

                JObject o = JObject.Parse(jsonString);
                if (o.TryGetValue("timeout", out JToken value))
                {
                    //timeout occured
                }

                if (o.TryGetValue("error", out value))
                {
                    Console.WriteLine(String.Format("Error occured: {0}", value));
                }

                if (o.TryGetValue("events", out value))
                {
                    Console.WriteLine(String.Format("Data: {0}", value));

                    foreach (var ev in value)
                    {
                        try
                        {
                            var data = ev["data"];
                            AcquiredData = Convert.FromBase64String(data.Value<string>());

                            UInt64 timestamp;
                            UInt64.TryParse(ev["timestamp"].Value<string>(), out timestamp);
                            if (timestamp > starsTimestamp)
                                starsTimestamp = timestamp;

                            isInvalidated = true;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(String.Format("Error!: {0}", e));
                        }
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Error!: {0}", e));
            }

            RegisterStarsListener(starsTimestamp);
        }

19 View Source File : KrakenSocket.cs
License : Apache License 2.0
Project Creator : AlexWan

private async Task StartListening(CancellationToken cancellationToken = default)
#pragma warning restore S3241 // Methods should not return values that are never used
        {
            try
            {
                while (webSocket.State == WebSocketState.Open)
                {
                   // logger?.LogDebug("Waiting for new message");
                    var message = await ReadNextMessage(cancellationToken);

                   // logger?.LogDebug("Received new message from websocket");
                   // logger?.LogTrace("Received: '{message}'", message);

                    string eventString = null;
                    int? channelId = null;

                    if (!string.IsNullOrEmpty(message))
                    {
                        var token = JToken.Parse(message);
                        switch (token)
                        {
                            case JObject _:
                                var messageObj = JObject.Parse(message);
                                eventString = (string)messageObj.GetValue("event");
                                break;

                            case JArray arrayToken:
                                // Data / private messages
                                if (int.TryParse(arrayToken.First.ToString(), out var localChannelId))
                                {
                                    channelId = localChannelId;
                                }

                                eventString = channelId != null ? "data" : "private";
                                break;
                        }

                        InvokeDataReceived(new KrakenMessageEventArgs(eventString, message, channelId));
                    }
                }
            }
            catch (Exception ex)
            {
               // logger?.LogError(ex, "Error while listening or reading new messages from WebSocket");
                // TODO: Disconnected-Event
                throw;
            }
            finally
            {
              //  logger?.LogInformation("Closing WebSocket");
                webSocket.Dispose();
            }
        }

19 View Source File : GateMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan

public MarketDepth Create(string data)
        {
            var jt = JObject.Parse(data);

            var quotes = (JArray)jt["params"];

            if (quotes[0].ToString() == "True")
            {
                return CreateNew(quotes);
            }

            return Update(quotes);
        }

19 View Source File : GatePortfolioCreator.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<Portfolio> UpdatePortfolio(string data)
        {
            var jt = JObject.Parse(data)["params"].Children<JObject>().Properties();

            foreach (var jtPosition in jt)
            {
                PositionOnBoard pos = new PositionOnBoard();

                pos.PortfolioName = _headPortfolio.Number;
                pos.SecurityNameCode = jtPosition.Name;
                pos.ValueCurrent = jtPosition.Value["available"].Value<decimal>();
                pos.ValueBlocked = jtPosition.Value["freeze"].Value<decimal>();

                if (pos.ValueCurrent > 0 || pos.ValueBlocked > 0)
                {
                    _portfolios[0].SetNewPosition(pos);
                }
            }
            return _portfolios;
        }

19 View Source File : GateTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan

public List<Trade> Create(string data)
        {
            var trades = new List<Trade>();

            var jt = JObject.Parse(data);

            var tradesData = (JArray)jt["params"];
            
            foreach (var trade in tradesData[1])
            {
                var security = tradesData[0].ToString();

                var time = trade["time"].Value<long>();

                var newTrade = new Trade();

                newTrade.Time = TimeManager.GetDateTimeFromTimeStampSeconds(time);
                newTrade.SecurityNameCode = security;
                newTrade.Price = trade["price"].Value<decimal>();
                newTrade.Id = trade["id"].ToString();
                newTrade.Side = trade["type"].ToString() == "sell" ? Side.Sell : Side.Buy;
                newTrade.Volume = trade["amount"].Value<decimal>();

                trades.Add(newTrade);
            }

            return trades;
        }

19 View Source File : SecretsReader.cs
License : GNU General Public License v3.0
Project Creator : AnaghSharma

public static string GetSecrets()
        {
            secrets = JObject.Parse(GetSecretKey());
            return secrets["API_key"].Value<String>();
        }

19 View Source File : NgProxyMiddleware.cs
License : MIT License
Project Creator : andfomin

private static Version GetNgVersion(string currentDirectory)
        {
            var packageJsonFilePath = Path.Combine(currentDirectory, NgMiddlewareHelper.PackageJsonFileName);
            if (File.Exists(packageJsonFilePath))
            {
                /*
                var lines = File.ReadAllLines(packageJsonFilePath);
                var line = lines
                  .Where(i => i.Contains("@angular/cli"))
                  // Although the JSON standard demands double quotes, let's be paranoid.
                  .Select(i => i.Replace("'", "\""))
                  .Where(i => i.Contains("\"@angular/cli\""))
                  .FirstOrDefault()
                  ;
                var match = Regex.Match(line, PackageJsonVersionPattern);
                if (match.Success)
                {
                  var value = match.Value;
                  return new Version(value);
                }
                */
                var rootObj = JObject.Parse(File.ReadAllText(packageJsonFilePath));
                var devDependencies = (JObject)rootObj["devDependencies"];
                if (devDependencies != null)
                {
                    var semVer = (string)devDependencies["@angular/cli"];
                    var match = Regex.Match(semVer, SemVerShortVersionPattern);
                    if (match.Success)
                    {
                        var value = match.Groups[1].Value;
                        return new Version(value);
                    }
                }
            }
            return null;
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

private static bool? MergePackageJsonFiles(string projectDirectory)
        {
            const string ScriptsName = "scripts";
            const string DependenciesName = "dependencies";
            const string DevDependenciesName = "devDependencies";
            const string OldNameSuffix = "_old";

            var filePath = Path.Combine(projectDirectory, NgWizardHelper.PackageJsonFileName);
            var oldFilePath = Path.Combine(projectDirectory, NgWizardHelper.PackageJsonOldFileName);

            if (File.Exists(oldFilePath))
            {
                if (!File.Exists(filePath))
                {
                    return false;
                }
            }
            else
            {
                return (bool?)null;
            }

            try
            {
                var oldObj = JObject.Parse(File.ReadAllText(oldFilePath));
                var newObj = JObject.Parse(File.ReadAllText(filePath));

                // We will give a higher priority in the three main sections to Ng, but keep the metadata properties from the old file.
                var resultObj = new JObject(oldObj);
                // The argument's content (i.e. newObj) wins over the "this" file (i.e. result).
                resultObj.Merge(newObj);

                // Clone the old content and delete the three main sections. Leave the metadata properties intact.
                var oObj = new JObject(oldObj);

                var propScr = oObj.Property(ScriptsName);
                if (propScr != null)
                {
                    propScr.Remove();
                }
                var propDep = oObj.Property(DependenciesName);
                if (propDep != null)
                {
                    propDep.Remove();
                }
                var propDev = oObj.Property(DevDependenciesName);
                if (propDev != null)
                {
                    propDev.Remove();
                }

                // Restore the old metadata properties.
                resultObj.Merge(oObj);

                // Add the three main sections from the old file for reference.
                var oScr = oldObj[ScriptsName];
                var oDep = oldObj[DependenciesName];
                var oDev = oldObj[DevDependenciesName];

                resultObj.Property(ScriptsName).AddAfterSelf(new JProperty(ScriptsName + OldNameSuffix, oScr ?? new JObject()));
                resultObj.Property(DependenciesName).AddAfterSelf(new JProperty(DependenciesName + OldNameSuffix, oDep ?? new JObject()));
                resultObj.Property(DevDependenciesName).AddAfterSelf(new JProperty(DevDependenciesName + OldNameSuffix, oDev ?? new JObject()));

                NgWizardHelper.RewriteFile(filePath, resultObj.ToString());
                return true;
            }
            catch (Exception)
            {
            }
            return false;
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

private bool ModifyAngularJsonFile(string projectDirectory, string jsonFileName, string projectName)
        {
            const string BaseHrefPropertyName = "baseHref";
            const string BaseHrefApi = "/";
            const string BaseHrefMvc = "/ng/";

            var projectIsMvc = Directory.Exists(Path.Combine(projectDirectory, "Views"));
            var projectIsRazorPages = Directory.Exists(Path.Combine(projectDirectory, "Pages"));
            var baseHrefPropertyValue = (projectIsMvc || projectIsRazorPages) ? BaseHrefMvc : BaseHrefApi;

            var filePath = Path.Combine(projectDirectory, jsonFileName);
            if (File.Exists(filePath))
            {
                var rootObj = JObject.Parse(File.ReadAllText(filePath));

                var parentObj = FindInsertPlace2(rootObj, projectName);
                if (parentObj != null)
                {
                    if (parentObj[BaseHrefPropertyName] == null)
                    {
                        var baseHrefProperty = new JProperty(BaseHrefPropertyName, baseHrefPropertyValue);
                        parentObj.Add(baseHrefProperty);

                        NgWizardHelper.RewriteFile(filePath, rootObj.ToString());
                        return true;
                    }
                }

            }
            return false;
        }

19 View Source File : NgMiddlewareHelper.cs
License : MIT License
Project Creator : andfomin

internal static IEnumerable<NgAppSettings> GetAllNgAppSettings(string directory)
        {
            var angularCliJsonFilePath = Path.Combine(directory, NgMiddlewareHelper.AngularCliJsonFileName);
            var angularJsonFilePath = Path.Combine(directory, NgMiddlewareHelper.AngularJsonFileName);

            var ver1FileExists = File.Exists(angularCliJsonFilePath);
            var ver6FileExists = File.Exists(angularJsonFilePath);

            if (!ver1FileExists && !ver6FileExists)
            {
                throw new Exception(String.Format(ErrorAngularCliJsonNotFound, directory));
            }

            var fileText = File.ReadAllText(ver6FileExists ? angularJsonFilePath : angularCliJsonFilePath);
            var rootObj = JObject.Parse(fileText);

            IEnumerable<NgAppSettings> ngAppSettings = null;

            if (ver6FileExists)
            {
                var projectsObj = (JObject)rootObj["projects"];
                if (projectsObj == null)
                {
                    throw new Exception(ErrorProjectsNotFound);
                }

                ngAppSettings = projectsObj.Properties()
                    .Where(i => (i.Value is JObject) && i.HasValues)
                    .Select((i, index) => new
                    {
                        ProjectIndex = index,
                        ProjectName = i.Name,
                        OptionsObj = i.Value.SelectToken("architect.build.options"),
                    })
                    .Where(i => i.OptionsObj != null)
                    .Select(i => new NgAppSettings
                    {
                        AppIndex = i.ProjectIndex,
                        AppName = i.ProjectName,
                        BaseHref = (string)i.OptionsObj["baseHref"],
                        IndexFileName = (string)i.OptionsObj["index"],
                    })
                    .Where(i => i.BaseHref != null)
                    .ToList()
                    ;
            }
            else if (ver1FileExists)
            {
                var apps = (JArray)rootObj["apps"];
                if (apps == null)
                {
                    throw new Exception(ErrorAppsNotFound);
                }

                ngAppSettings = apps
                  .Select((i, index) => new NgAppSettings
                  {
                      AppIndex = index,
                      AppName = (string)i["name"],
                      BaseHref = (string)i["baseHref"],
                      IndexFileName = Path.GetFileName((string)i["index"]),
                  })
                  .ToList()
                  ;
            }

            if (ngAppSettings == null || !ngAppSettings.Any())
            {
                throw new Exception(ErrorNgSettingsNotFound);
            }
            return ngAppSettings;
        }

19 View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin

private bool ModifyAngularCliJsonFile(string projectDirectory)
        {
            const string BaseHrefPropertyName = "baseHref";
            const string BaseHrefApi = "/";
            const string BaseHrefMvc = "/ng/";

            var projectIsMvc = Directory.Exists(Path.Combine(projectDirectory, "Views"));
            var projectIsRazorPages = Directory.Exists(Path.Combine(projectDirectory, "Pages"));
            var baseHrefPropertyValue = (projectIsMvc || projectIsRazorPages) ? BaseHrefMvc : BaseHrefApi;

            var filePath = Path.Combine(projectDirectory, NgWizardHelper.AngularCliJsonFileName);
            if (File.Exists(filePath))
            {
                var rootObj = JObject.Parse(File.ReadAllText(filePath));
                var apps = (JArray)rootObj["apps"];
                if ((apps != null) && apps.Any())
                {
                    var app = (JObject)apps[0];
                    if (app[BaseHrefPropertyName] == null)
                    {
                        var knownProperty = app.Property("outDir") ?? app.Property("root");
                        if (knownProperty != null)
                        {
                            var baseHrefProperty = new JProperty(BaseHrefPropertyName, baseHrefPropertyValue);
                            knownProperty.AddAfterSelf(baseHrefProperty);

                            NgWizardHelper.RewriteFile(filePath, rootObj.ToString());
                            return true;
                        }
                    }
                }
            }
            return false;
        }

19 View Source File : Main.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber

public static Location getLocation(string url)
        {
            ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            string URL = url;
            System.Net.WebClient myWebClient = new System.Net.WebClient();
            myWebClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)");
            byte[] myDataBuffer = myWebClient.DownloadData(URL);
            string SourceCode = Encoding.GetEncoding("utf-8").GetString(myDataBuffer);
            Debug.WriteLine("返回值:" + SourceCode);
            Location Location = new Location();
            var rb = JObject.Parse(SourceCode);
            var result = JObject.Parse(rb["result"].ToString().Replace("[", "").Replace("]", ""));
            Location.Lareplacedude = Convert.ToDouble(result["lat"].ToString());
            Location.Longitude = Convert.ToDouble(result["lng"].ToString());
            Debug.WriteLine("经度:" + result["lat"].ToString());

            return Location;
        }

19 View Source File : RefreshCurrencyExchangeRates.cs
License : MIT License
Project Creator : AndrewButenko

protected override void ExecuteWorkflowLogic()
        {
            #region Get All Currencies From Endpoint and check that call was successfull

            string jsonResult = null;

            var url = "http://apilayer.net/api/live?access_key=" + Context.Settings.CurrencylayerKey;
            var request = (HttpWebRequest)WebRequest.Create(url);
            using (var resStream = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                jsonResult = resStream.ReadToEnd();
            }

            var jobject = JObject.Parse(jsonResult);

            var success = jobject.SelectToken("$.success").Value<bool>();

            if (!success)
            {
                var errorToken = jobject.SelectToken("$.error");
                var errorMessage = [email protected]"Can't obtain currency exchange rates:
Code: {errorToken.SelectToken("code").Value<int>()}
Type: {errorToken.SelectToken("type").Value<string>()}
Info: {errorToken.SelectToken("info").Value<string>()}";

                throw new InvalidPluginExecutionException(errorMessage);
            }

            #endregion Get All Currencies From Endpoint and check that call was successfull

            #region Get Base Currency

            QueryExpression query = new QueryExpression("transactioncurrency")
            {
                ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
            };
            query.AddLink("organization", "transactioncurrencyid", "basecurrencyid", JoinOperator.Inner);

            var baseCurrency = Context.SystemService.RetrieveMultiple(query).Enreplacedies.FirstOrDefault();

            if (baseCurrency == null)
                return;

            var baseCurrencyCode = baseCurrency.GetAttributeValue<string>("isocurrencycode").ToUpper();
            var baseCurrencyId = baseCurrency.Id;
            var baseCurrencyName = baseCurrency.GetAttributeValue<string>("currencyname");

            var baseCurrencyNode = jobject.SelectToken($"$.quotes.USD{baseCurrencyCode}");

            if (baseCurrencyNode == null)
            {
                throw new InvalidPluginExecutionException($"Exchange Rates for your Base Currency ({baseCurrencyName}) are not available");
            }

            var usdToBaseCurrencyRate = baseCurrencyNode.Value<decimal>();

            #endregion Get Base Currency

            #region Getting All Currencies Except Base Currency

            query = new QueryExpression("transactioncurrency")
            {
                ColumnSet = new ColumnSet("isocurrencycode", "currencyname")
            };
            query.Criteria.AddCondition("transactioncurrencyid", ConditionOperator.NotEqual, baseCurrencyId);

            List<Enreplacedy> allCurrencies = Context.SystemService.RetrieveMultiple(query).Enreplacedies.ToList();

            #endregion Getting All Currencies Except Base Currency

            #region Looping through currencies and updating Exhange Rates

            foreach (Enreplacedy currency in allCurrencies)
            {
                var currencyCode = currency.GetAttributeValue<string>("isocurrencycode").ToUpper();
                var currencyName = currency.GetAttributeValue<string>("currencyname");

                var currencyNode = jobject.SelectToken($"$.quotes.USD{currencyCode}");

                if (currencyNode == null)
                {
                    Context.TracingService.Trace($"Can't refresh exchange rate for {currencyName} currency");
                    continue;
                }

                var usdToCurrencyRate = currencyNode.Value<decimal>();


                decimal rate = usdToCurrencyRate / usdToBaseCurrencyRate;

                currency.Attributes.Clear();
                currency["exchangerate"] = rate;

                Context.SystemService.Update(currency);
            }

            #endregion Looping through currencies and updating Exhange Rates
        }

19 View Source File : SmartHomeProtocolMessage.cs
License : Apache License 2.0
Project Creator : anthturner

internal dynamic Execute(string hostname, int port)
        {
            var messageToSend = SmartHomeProtocolEncoder.Encrypt(JSON);

            var client = new TcpClient(hostname, port);
            byte[] packet = new byte[0];
            using (var stream = client.GetStream())
            {
                stream.Write(messageToSend, 0, messageToSend.Length);

                int targetSize = 0;
                var buffer = new List<byte>();
                while (true)
                {
                    var chunk = new byte[1024];
                    var bytesReceived = stream.Read(chunk, 0, chunk.Length);

                    if (!buffer.Any())
                    {
                        var lengthBytes = chunk.Take(4).ToArray();
                        if (BitConverter.IsLittleEndian) // this value needs to be in big-endian
                            lengthBytes = lengthBytes.Reverse().ToArray();
                        targetSize = (int)BitConverter.ToUInt32(lengthBytes, 0);
                    }
                    buffer.AddRange(chunk.Take(bytesReceived));

                    if (buffer.Count == targetSize + 4)
                        break;
                }

                packet = buffer.Skip(4).Take(targetSize).ToArray();
            }
            client.Close();

            var decrypted = Encoding.UTF8.GetString(SmartHomeProtocolEncoder.Decrypt(packet)).Trim('\0');

            var subResult = (dynamic)((JObject)JObject.Parse(decrypted)[System])[Command];
            if (subResult["err_code"] != null && subResult.err_code != 0)
                throw new Exception($"Protocol error {subResult.err_code} ({subResult.err_msg})");

            return subResult;
        }

19 View Source File : TPLinkDiscovery.cs
License : Apache License 2.0
Project Creator : anthturner

private void Receive(IAsyncResult ar)
        {
            if (discoveryComplete) //Prevent ObjectDisposedException/NullReferenceException when the Close() function is called
                return;

            IPEndPoint ip = new IPEndPoint(IPAddress.Any, PORT_NUMBER);
            byte[] bytes = udp.EndReceive(ar, ref ip);
            var message = Encoding.UTF8.GetString(Messaging.SmartHomeProtocolEncoder.Decrypt(bytes));
            var sys_info = ((dynamic)JObject.Parse(message)).system.get_sysinfo;

            TPLinkSmartDevice device = null;
            if (((JObject) sys_info).Count != 0 && sys_info.model != null)
            {
                string model = (string) sys_info.model;

                if (model.StartsWith("HS110"))
                    device = new TPLinkSmartMeterPlug(ip.Address.ToString());
                else if (model.StartsWith("HS"))
                    device = new TPLinkSmartPlug(ip.Address.ToString());
                else if (model.StartsWith("LB"))
                    device = new TPLinkSmartBulb(ip.Address.ToString());
                else if (model.StartsWith("KP303"))
                    device = new TPLinkSmartStrip(ip.Address.ToString());
            }

            if (device != null)
            {
                DiscoveredDevices.Add(device);
                OnDeviceFound(device);

                // If the caller has specified a maximum number of devices to discover, stop waiting after we've
                // reached this count
                if (maxNumberOfDevicesToDiscover > 0 && DiscoveredDevices.Count >= maxNumberOfDevicesToDiscover)
                {
                    delayCancellationToken.Cancel();
                }
            }
            if (udp != null)
                StartListening();
        }

19 View Source File : ToJsonEx.cs
License : MIT License
Project Creator : aprilyush

public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", ""));
        }

19 View Source File : C2AddonParser.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public C2Addon ReadEdittimeJs(string source)
        {
            c2addon = new C2Addon();
            var parser = new JavaScriptParser(source);
            var program = parser.ParseProgram();
            var json = program.ToJsonString();
            dynamic ast = JObject.Parse(json);

            return TraverseJavascriptTree(ast);
        }

19 View Source File : C2ParsingService.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public C2Addon Parse(string json)
        {
            var c2addon = new C2Addon();
            dynamic data = JObject.Parse(json);

            //settings
            var settings = data["settings"];
            foreach (JProperty prop in settings)
            {
                //handle array
                if (prop.Name == "flags")
                {
                    var sb = new StringBuilder();
                    foreach (var val in prop.Value)
                    {
                        sb.Append($" {val} ");
                    }
                    c2addon.Properties.Add(prop.Name,sb.ToString());
                    continue;
                }

                c2addon.Properties.Add(prop.Name, prop.Value.ToString());
            }

            //properties
            var props = data["properties"];
            foreach (var p in props)
            {
                var property = new C2Property();

                property.Type = p["flags"].ToString();
                property.Name = p["key"].ToString();
                property.Value = p["initial_str"]?.ToString() ?? string.Empty;
                property.Description = p["description"].ToString();
                var flags = p["params"];
                var fList = new List<string>();
                foreach (var flag in flags)
                {
                    fList.Add(flag);
                }
                property.Params = string.Join("|", fList);
                property.Readonly = p["read_only"] != null ? p["read_only"].ToString().ToLower() : "false";
            }

            //actions
            var actions = data["actions"];
            c2addon.Actions = new List<C2Ace>();
            foreach (JObject act in actions)
            {
                var ace = new C2Ace
                {
                    Id = act["id"].ToString(),
                    ListName = act["list_name"].ToString(),
                    Category = act["category"].ToString(),
                    DisplayString = act["display_string"].ToString(),
                    Description = act["description"].ToString(),
                    ScriptName = act["script_name"].ToString()
                };

                //get flags
                var sb = new StringBuilder();
                foreach (var val in act["flags"])
                {
                    sb.Append($" {val} ");
                }
                ace.Flags = sb.ToString();

                //params
                foreach (var param in act["params"])
                {
                    var aceParam = new C2AceParam
                    {
                        Text = param["name"]?.ToString(),
                        Description = param["description"]?.ToString(),
                        DefaultValue = param["initial"]?.ToString(),
                        Script = param["caller"]?.ToString()
                    };

                    if (param["caller"]?.ToString() == "AddComboParam")
                    {
                        aceParam.ComboItems = new List<string>();
                        foreach (var val in param["options"])
                        {
                            aceParam.ComboItems.Add(val["text"].ToString());
                        }
                    }

                    ace.Params.Add(aceParam);
                    c2addon.Actions.Add(ace);
                }

            }

            //conditions
            var conditions = data["conditions"];
            c2addon.Conditions = new List<C2Ace>();
            foreach (JObject cnd in conditions)
            {
                var ace = new C2Ace
                {
                    Id = cnd["id"].ToString(),
                    ListName = cnd["list_name"].ToString(),
                    Category = cnd["category"].ToString(),
                    DisplayString = cnd["display_string"].ToString(),
                    Description = cnd["description"].ToString(),
                    ScriptName = cnd["script_name"].ToString()
                };

                //get flags
                var sb = new StringBuilder();
                foreach (var val in cnd["flags"])
                {
                    sb.Append($" {val} ");
                }
                ace.Flags = sb.ToString();

                //params
                foreach (var param in cnd["params"])
                {
                    var aceParam = new C2AceParam
                    {
                        Text = param["name"]?.ToString(),
                        Description = param["description"]?.ToString(),
                        DefaultValue = param["initial"]?.ToString(),
                        Script = param["caller"]?.ToString()
                    };

                    if (param["caller"]?.ToString() == "AddComboParam")
                    {
                        aceParam.ComboItems = new List<string>();
                        foreach (var val in param["options"])
                        {
                            aceParam.ComboItems.Add(val["text"].ToString());
                        }
                    }

                    ace.Params.Add(aceParam);
                }
                c2addon.Conditions.Add(ace);
            }

            //expressions
            var expressions = data["expressions"];
            c2addon.Expressions = new List<C2Ace>();
            foreach (JObject exp in expressions)
            {
                var ace = new C2Ace
                {
                    Id = exp["id"].ToString(),
                    ListName = exp["list_name"].ToString(),
                    Category = exp["category"].ToString(),
                    Description = exp["description"].ToString(),
                    ScriptName = exp["expression_name"].ToString(),                 
                };

                //get flags
                var sb = new StringBuilder();
                foreach (var val in exp["flags"])
                {
                    sb.Append($" {val} ");
                }
                ace.Flags = sb.ToString();

                //params
                foreach (var param in exp["params"])
                {
                    var aceParam = new C2AceParam
                    {
                        Text = param["name"]?.ToString(),
                        Description = param["description"]?.ToString(),
                        DefaultValue = param["initial"]?.ToString(),
                        Script = param["caller"]?.ToString()
                    };

                    if (param["caller"]?.ToString() == "AddComboParam")
                    {
                        aceParam.ComboItems = new List<string>();
                        foreach (var val in param["options"])
                        {
                            aceParam.ComboItems.Add(val["text"].ToString());
                        }
                    }

                    ace.Params.Add(aceParam);
                }

                c2addon.Expressions.Add(ace);
            }

            return c2addon;
        }

19 View Source File : C3AddonImporter.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public async Task<C3Addon> Import(string path)
        {
            WindowManager.ShowLoadingOverlay(true);
            try
            {
                return await Task.Run(() =>
                {
                    var fi = new FileInfo(path);
                    var tmpPath = OptionsManager.CurrentOptions.DataPath + "\\tmp_c3";
                    if (Directory.Exists(tmpPath)) Directory.Delete(tmpPath, true);

                    //unzip c3addon to temp location
                    ZipFile.ExtractToDirectory(path, tmpPath);

                    var addon = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "addon.json")));
                    string type = addon["type"].ToString();
                    string id = addon["id"].ToString();

                    //todo: handle mixed c3addon with only c2runtime
                    bool c2Only = !File.Exists(Path.Combine(tmpPath, "c3runtime", $"{type}.js"));


                    if (type != "effect" && !c2Only)
                    {
                        string pluginEdit, pluginRun;

                        pluginEdit = File.ReadAllText(Path.Combine(tmpPath, $"{type}.js"));
                        pluginRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"{type}.js"));
                        string typeEdit = File.ReadAllText(Path.Combine(tmpPath, $"type.js"));
                        string typeRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"type.js"));
                        string instanceEdit = File.ReadAllText(Path.Combine(tmpPath, $"instance.js"));
                        string instanceRun = File.ReadAllText(Path.Combine(tmpPath, "c3runtime", $"instance.js"));
                        string c2runtime = null;

                        if (Directory.Exists(Path.Combine(tmpPath, "c2runtime")))
                        {
                            c2runtime = File.ReadAllText(Path.Combine(tmpPath, "c2runtime", "runtime.js"));
                        }

                        PluginType pluginType = PluginType.SingleGlobalPlugin;
                        string pluginCat = "other";
                        switch (type)
                        {
                            case "plugin":
                                pluginType = pluginEdit.Contains("SetPluginType(\"world\")")
                                    ? PluginType.DrawingPlugin
                                    : PluginType.SingleGlobalPlugin;
                                pluginCat = Regex.Match(pluginEdit, @"PLUGIN_CATEGORY = ""(?<cat>).*""").Groups["cat"]
                                    .Value;
                                break;
                            case "behavior":
                                pluginType = PluginType.Behavior;
                                pluginCat = Regex.Match(pluginEdit, @"BEHAVIOR_CATEGORY = ""(?<cat>.*)""").Groups["cat"]
                                    .Value;
                                break;
                        }

                        if (string.IsNullOrWhiteSpace(pluginCat)) pluginCat = "other";

                        var ace = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "aces.json")));
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var prop = "\"properties\": " + (string.IsNullOrWhiteSpace(lang["properties"]?.ToString()) ? "{ }" : lang["properties"]);
                        var cats = "\"aceCategories\": " + (string.IsNullOrWhiteSpace(lang["aceCategories"]?.ToString()) ? "{ }" : lang["aceCategories"]);

                        //pasre ace implementations
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / ACTIONS");
                        var actFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "actions.js")));
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / CONDITION");
                        var cndFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "conditions.js")));
                        LogManager.AddImportLogMessage("EXTRACTING C3RUNTIME / EXPRESSIONS");
                        var expFuncs = JavascriptManager.GetAllFunction(File.ReadAllText(Path.Combine(tmpPath, "c3runtime", "expressions.js")));

                        var actionList = new List<Models.Action>();
                        var conditionList = new List<Models.Condition>();
                        var expressionList = new List<Models.Expression>();

                        foreach (JProperty category in ace.Properties())
                        {
                            //parse actions
                            var ationJson = ace[category.Name]["actions"]?.ToString();
                            var actions = ationJson != null ? JArray.Parse(ationJson) : null;
                            if (actions != null)
                            {
                                foreach (var action in actions.Children<JObject>())
                                {
                                    var actionId = action["id"].ToString();
                                    var actionAce = action.ToString();
                                    var actionLang = $"\"{actionId}\":" + lang["actions"][actionId];
                                    var actionScript = action["scriptName"].ToString();
                                    var actionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (action["params"] != null && action["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = action["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    actionParams = string.Join(",", ep);
                                    //}

                                    actFuncs.TryGetValue(actionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"ACTION FUNCTION DEFINITION DOES NOT EXISTS => {actionScript.Trim()}");
                                        continue;
                                    }

                                    var act = new Models.Action
                                    {
                                        Id = actionId,
                                        Category = category.Name,
                                        Ace = actionAce,
                                        Language = actionLang,
                                        //Code = $"{actionScript}({string.Join(",", actionParams)}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(code) ?? string.Empty
                                    };

                                    actionList.Add(act);
                                }
                            }

                            //parse conditions
                            var conditionJson = ace[category.Name]["conditions"]?.ToString();
                            var conditions = conditionJson != null ? JArray.Parse(conditionJson) : null;
                            if (conditions != null)
                            {
                                foreach (var condition in conditions.Children<JObject>())
                                {
                                    var conditionId = condition["id"].ToString();
                                    var conditionAce = condition.ToString();
                                    var conditionLang = $"\"{conditionId}\":" + lang["conditions"][conditionId];
                                    var conditionScript = condition["scriptName"].ToString();
                                    var conditionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (condition["params"] != null && condition["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = condition["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    conditionParams = string.Join(",", ep);
                                    //}

                                    cndFuncs.TryGetValue(conditionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"CONDITION FUNCTION DEFINITION DOES NOT EXISTS => {conditionScript.Trim()}");
                                        continue;
                                    }
                                    var cnd = new Models.Condition()
                                    {
                                        Id = conditionId,
                                        Category = category.Name,
                                        Ace = conditionAce,
                                        Language = conditionLang,
                                        //Code = $"{conditionScript}({string.Join(",", conditionParams)}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(code) ?? string.Empty
                                    };

                                    conditionList.Add(cnd);
                                }
                            }

                            //parse expression
                            var expressionJson = ace[category.Name]["expressions"]?.ToString();
                            var expressions = expressionJson != null ? JArray.Parse(expressionJson) : null;
                            if (expressions != null)
                            {
                                foreach (var expression in expressions.Children<JObject>())
                                {
                                    var expressionId = expression["id"].ToString();
                                    var expressionAce = expression.ToString();
                                    var expressionLang = $"\"{expressionId}\":" + lang["expressions"][expressionId];
                                    var expressionScript = expression["expressionName"].ToString();
                                    var expressionParams = string.Empty;

                                    //only needed for stub methods
                                    //if (expression["params"] != null && expression["params"].Children<JObject>().Any())
                                    //{
                                    //    var ep = expression["params"].Children<JObject>().Select(x => x["id"].ToString());
                                    //    expressionParams = string.Join(",", ep);
                                    //}

                                    expFuncs.TryGetValue(expressionScript.Trim(), out var code);
                                    if (code == null)
                                    {
                                        LogManager.AddImportLogMessage($"EXPRESSION FUNCTION DEFINITION DOES NOT EXISTS => {expressionScript.Trim()}");
                                        continue;
                                    }
                                    var exp = new Models.Expression()
                                    {
                                        Id = expressionId,
                                        Category = category.Name,
                                        Ace = expressionAce,
                                        Language = expressionLang,
                                        //Code = $"{expressionScript}({expressionParams}) {{ \n}}"
                                        Code = FormatHelper.Insatnce.Javascript(expFuncs[expressionScript.Trim()]) ??
                                               string.Empty
                                    };

                                    expressionList.Add(exp);
                                }
                            }
                        }

                        var thirdPartyFiles = new List<ThirdPartyFile>();
                        var files = Regex.Matches(pluginEdit, @"filename\s?:\s?(""|')(?<file>.*)(""|')");
                        var domFilesMatches = Regex.Matches(pluginEdit, @"SetDOMSideScripts\(\[(?<file>.*)\]\)");
                        var domFileList = new List<string>();
                        var completeFileList = new HashSet<string>();

                        foreach(Match match in domFilesMatches)
                        {
                            var domScripts = match.Groups["file"].ToString().Split(',');
                            foreach(var domScript in domScripts)
                            {
                                var fn = domScript.Trim('"').Trim('\'');
                                domFileList.Add(fn);
                                completeFileList.Add(fn);
                            }
                        }

                        foreach(Match match in files)
                        {
                            var fn = match.Groups["file"].ToString();
                            completeFileList.Add(fn);
                        }

                        foreach (var fn in completeFileList)
                        {
                            var info = new FileInfo(Path.Combine(Path.Combine(tmpPath, fn)));

                            var f = new ThirdPartyFile
                            {
                                Bytes = File.ReadAllBytes(info.FullName),
                                Content = File.ReadAllText(info.FullName),
                                Extention = info.Extension,
                            };

                            switch (info.Extension)
                            {
                                case ".js":
                                    f.Content = FormatHelper.Insatnce.FixMinifiedFiles(f.Content);
                                    f.Compress = true;
                                    f.PlainText = true;
                                    break;
                                case ".html":
                                case ".css":
                                case ".txt":
                                case ".json":
                                case ".xml":
                                    f.PlainText = true;
                                    f.Compress= false;
                                    break;
                                default:
                                    f.Content = $"BINARY FILE => {f.FileName}\nBYTE LENGTH : ({f.Bytes.Length})";
                                    f.PlainText = false;
                                    f.Compress = false;
                                    break;
                            }


                            if (fn.Contains("c3runtime"))
                            {
                                f.C3Folder = true;
                                f.FileName = fn.Replace("c3runtime/", string.Empty).Trim();
                            }
                            else if (fn.Contains("c2runtime"))
                            {
                                f.C2Folder = true;
                                f.FileName = fn.Replace("c2runtime/", string.Empty).Trim();
                            }
                            else
                            {
                                f.Rootfolder = true;
                                f.FileName = fn.Replace("/", "\\").Trim();
                            }

                            foreach(var df in domFileList)
                            {
                                if(df.Contains(f.FileName))
                                {
                                    f.Domfolder = true;
                                }
                            }

                            f.PluginTemplate = TemplateHelper.ThirdPartyFile(f);

                            thirdPartyFiles.Add(f);
                        }

                        //todo: create c3addon, and map parsed data to c3addon 
                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = pluginCat,
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            PluginRunTime = pluginRun,
                            PluginEditTime = pluginEdit,
                            TypeEditTime = typeEdit,
                            TypeRunTime = typeRun,
                            InstanceEditTime = instanceEdit,
                            InstanceRunTime = instanceRun,
                            LanguageProperties = prop,
                            LanguageCategories = cats,
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = pluginType
                        };

                        c3addon.Actions = new Dictionary<string, Action>();
                        c3addon.Conditions = new Dictionary<string, Condition>();
                        c3addon.Expressions = new Dictionary<string, Expression>();

                        foreach (var action in actionList)
                        {
                            c3addon.Actions.Add(action.Id, action);
                        }

                        foreach (var condition in conditionList)
                        {
                            c3addon.Conditions.Add(condition.Id, condition);
                        }

                        foreach (var expression in expressionList)
                        {
                            c3addon.Expressions.Add(expression.Id, expression);
                        }

                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        c3addon.ThirdPartyFiles = new Dictionary<string, ThirdPartyFile>();
                        foreach (var thirdPartyFile in thirdPartyFiles)
                        {
                            c3addon.ThirdPartyFiles.Add($"{thirdPartyFile.ID}", thirdPartyFile);
                        }

                        if (!string.IsNullOrWhiteSpace(c2runtime))
                        {
                            c3addon.C2RunTime = c2runtime;
                        }

                        //regenerate addon file
                        c3addon.AddonJson = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.AddonJson, c3addon);

                        //fixup pluginedit time (replace png iconw ith svg)
                        c3addon.PluginEditTime = Regex.Replace(c3addon.PluginEditTime, @"this._info.SetIcon\(.*\);", "this._info.SetIcon(\"icon.svg\", \"image/svg+xml\");");

                        return c3addon;
                    }
                    else if (type != "effect" && c2Only)
                    {
                        string pluginEdit;

                        pluginEdit = File.ReadAllText(Path.Combine(tmpPath, $"{type}.js"));
                        string typeEdit = File.ReadAllText(Path.Combine(tmpPath, $"type.js"));
                        string instanceEdit = File.ReadAllText(Path.Combine(tmpPath, $"instance.js"));

                        string c2runtime = null;

                        if (Directory.Exists(Path.Combine(tmpPath, "c2runtime")))
                        {
                            c2runtime = File.ReadAllText(Path.Combine(tmpPath, "c2runtime", "runtime.js"));
                        }

                        PluginType pluginType = PluginType.SingleGlobalPlugin;
                        string pluginCat = "other";
                        switch (type)
                        {
                            case "plugin":
                                pluginType = pluginEdit.Contains("SetPluginType(\"world\")")
                                    ? PluginType.DrawingPlugin
                                    : PluginType.SingleGlobalPlugin;
                                pluginCat = Regex.Match(pluginEdit, @"PLUGIN_CATEGORY = ""(?<cat>).*""").Groups["cat"]
                                    .Value;
                                break;
                            case "behavior":
                                pluginType = PluginType.Behavior;
                                pluginCat = Regex.Match(pluginEdit, @"BEHAVIOR_CATEGORY = ""(?<cat>.*)""").Groups["cat"]
                                    .Value;
                                break;
                        }

                        if (string.IsNullOrWhiteSpace(pluginCat)) pluginCat = "other";

                        var ace = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "aces.json")));
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var prop = "\"properties\": " + (string.IsNullOrWhiteSpace(lang["properties"]?.ToString()) ? "{ }" : lang["properties"]);
                        var cats = "\"aceCategories\": " + (string.IsNullOrWhiteSpace(lang["aceCategories"]?.ToString()) ? "{ }" : lang["aceCategories"]);

                        var actionList = new List<Models.Action>();
                        var conditionList = new List<Models.Condition>();
                        var expressionList = new List<Models.Expression>();

                        foreach (JProperty category in ace.Properties())
                        {
                            //parse actions
                            var ationJson = ace[category.Name]["actions"]?.ToString();
                            var actions = ationJson != null ? JArray.Parse(ationJson) : null;
                            if (actions != null)
                            {
                                foreach (var action in actions.Children<JObject>())
                                {
                                    var actionId = action["id"].ToString();
                                    var actionAce = action.ToString();
                                    var actionLang = $"\"{actionId}\":" + lang["actions"][actionId];
                                    var actionScript = action["scriptName"].ToString();
                                    var actionParams = string.Empty;

                                    //only needed for stub methods
                                    if (action["params"] != null && action["params"].Children<JObject>().Any())
                                    {
                                        var ep = action["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        actionParams = string.Join(",", ep);
                                    }

                                    var act = new Models.Action
                                    {
                                        Id = actionId,
                                        Category = category.Name,
                                        Ace = actionAce,
                                        Language = actionLang,
                                        Code = $"{actionScript}({string.Join(",", actionParams)}) {{ \n}}"
                                    };

                                    actionList.Add(act);
                                }
                            }

                            //parse conditions
                            var conditionJson = ace[category.Name]["conditions"]?.ToString();
                            var conditions = conditionJson != null ? JArray.Parse(conditionJson) : null;
                            if (conditions != null)
                            {
                                foreach (var condition in conditions.Children<JObject>())
                                {
                                    var conditionId = condition["id"].ToString();
                                    var conditionAce = condition.ToString();
                                    var conditionLang = $"\"{conditionId}\":" + lang["conditions"][conditionId];
                                    var conditionScript = condition["scriptName"].ToString();
                                    var conditionParams = string.Empty;

                                    //only needed for stub methods
                                    if (condition["params"] != null && condition["params"].Children<JObject>().Any())
                                    {
                                        var ep = condition["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        conditionParams = string.Join(",", ep);
                                    }


                                    var cnd = new Models.Condition()
                                    {
                                        Id = conditionId,
                                        Category = category.Name,
                                        Ace = conditionAce,
                                        Language = conditionLang,
                                        Code = $"{conditionScript}({string.Join(",", conditionParams)}) {{ \n}}"
                                    };

                                    conditionList.Add(cnd);
                                }
                            }

                            //parse expression
                            var expressionJson = ace[category.Name]["expressions"]?.ToString();
                            var expressions = expressionJson != null ? JArray.Parse(expressionJson) : null;
                            if (expressions != null)
                            {
                                foreach (var expression in expressions.Children<JObject>())
                                {
                                    var expressionId = expression["id"].ToString();
                                    var expressionAce = expression.ToString();
                                    var expressionLang = $"\"{expressionId}\":" + lang["expressions"][expressionId];
                                    var expressionScript = expression["expressionName"].ToString();
                                    var expressionParams = string.Empty;

                                    //only needed for stub methods
                                    if (expression["params"] != null && expression["params"].Children<JObject>().Any())
                                    {
                                        var ep = expression["params"].Children<JObject>().Select(x =>
                                        {
                                            var p = x["id"].ToString();
                                            var ti = new CultureInfo("en-US", false).TextInfo;
                                            var param = ti.ToreplacedleCase(p.Replace("-", " ").ToLower()).Replace(" ", string.Empty);
                                            param = char.ToLowerInvariant(param[0]) + param.Substring(1);
                                            return param;
                                        });
                                        expressionParams = string.Join(",", ep);
                                    }

                                    var exp = new Models.Expression()
                                    {
                                        Id = expressionId,
                                        Category = category.Name,
                                        Ace = expressionAce,
                                        Language = expressionLang,
                                        Code = $"{expressionScript}({expressionParams}) {{ \n}}"
                                    };

                                    expressionList.Add(exp);
                                }
                            }
                        }

                        var files = Regex.Matches(pluginEdit, @"filename\s?:\s?(""|')(?<file>.*)(""|')");
                        var thirdPartyFiles = new List<ThirdPartyFile>();
                        foreach (Match match in files)
                        {
                            var fn = match.Groups["file"].ToString();
                            var info = new FileInfo(Path.Combine(Path.Combine(tmpPath, fn)));

                            var f = new ThirdPartyFile
                            {
                                Bytes = null,
                                Content = File.ReadAllText(info.FullName),
                                Extention = info.Extension,
                            };

                            f.PluginTemplate = TemplateHelper.ThirdPartyFile(f);

                            switch (info.Extension)
                            {
                                case ".js":
                                    f.Content = FormatHelper.Insatnce.FixMinifiedFiles(f.Content);
                                    f.Compress = true;
                                    f.PlainText = true;
                                    break;
                                case ".html":
                                case ".css":
                                case ".txt":
                                case ".json":
                                case ".xml":
                                    f.PlainText = true;
                                    f.Compress = false;
                                    break;
                                default:
                                    f.Content = $"BINARY FILE => {f.FileName}\nBYTE LENGTH : ({f.Bytes.Length})";
                                    f.PlainText = false;
                                    f.Compress = false;
                                    break;
                            }

                            if (fn.Contains("c3runtime"))
                            {
                                f.C3Folder = true;
                                f.FileName = fn.Replace("c3runtime/", string.Empty).Trim();
                            }
                            else if (fn.Contains("c2runtime"))
                            {
                                f.C2Folder = true;
                                f.FileName = fn.Replace("c2runtime/", string.Empty).Trim();
                            }
                            else
                            {
                                f.Rootfolder = true;
                                f.FileName = fn.Replace("/", "\\").Trim();
                            }

                            thirdPartyFiles.Add(f);
                        }

                        //todo: create c3addon, and map parsed data to c3addon 
                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = pluginCat,
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            //PluginRunTime = pluginRun,
                            PluginEditTime = pluginEdit,
                            TypeEditTime = typeEdit,
                            //TypeRunTime = typeRun,
                            InstanceEditTime = instanceEdit,
                            //InstanceRunTime = instanceRun,
                            LanguageProperties = prop,
                            LanguageCategories = cats,
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = pluginType
                        };

                        c3addon.Actions = new Dictionary<string, Action>();
                        c3addon.Conditions = new Dictionary<string, Condition>();
                        c3addon.Expressions = new Dictionary<string, Expression>();

                        foreach (var action in actionList)
                        {
                            c3addon.Actions.Add(action.Id, action);
                        }

                        foreach (var condition in conditionList)
                        {
                            c3addon.Conditions.Add(condition.Id, condition);
                        }

                        foreach (var expression in expressionList)
                        {
                            c3addon.Expressions.Add(expression.Id, expression);
                        }

                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        c3addon.ThirdPartyFiles = new Dictionary<string, ThirdPartyFile>();
                        foreach (var thirdPartyFile in thirdPartyFiles)
                        {
                            c3addon.ThirdPartyFiles.Add($"{thirdPartyFile.ID}", thirdPartyFile);
                        }

                        if (!string.IsNullOrWhiteSpace(c2runtime))
                        {
                            c3addon.C2RunTime = c2runtime;
                        }

                        //regenerate template files
                        c3addon.AddonJson = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.AddonJson, c3addon);
                        c3addon.PluginRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.PluginRunTime, c3addon); 
                        c3addon.TypeRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.TypeRunTime, c3addon);
                        c3addon.InstanceRunTime = TemplateCompiler.Insatnce.CompileTemplates(c3addon.Template.InstanceRunTime, c3addon);

                        //fixup pluginedit time (replace png iconw ith svg)
                        c3addon.PluginEditTime = Regex.Replace(c3addon.PluginEditTime, @"this._info.SetIcon\(.*\);", "this._info.SetIcon(\"icon.svg\", \"image/svg+xml\");");

                        return c3addon;
                    }
                    else
                    {
                        //read file text
                        var effectCode = File.ReadAllText(Path.Combine(tmpPath, "effect.fx"));

                        //parse json
                        var lang = JObject.Parse(File.ReadAllText(Path.Combine(tmpPath, "lang", "en-US.json")))["text"][type + "s"][id.ToLower()];

                        var effect = new Effect();
                        effect.BlendsBackground = addon["blends-background"] != null && addon["blends-background"].ToString().ToLower().Contains("true");
                        effect.CrossSampling = addon["cross-sampling"] != null && addon["cross-sampling"].ToString().ToLower().Contains("true");
                        effect.PreservesOpaqueness = addon["preserves-opaqueness"] != null && addon["preserves-opaqueness"].ToString().ToLower().Contains("true");
                        effect.Animated = addon["animated"] != null && addon["animated"].ToString().ToLower().Contains("true");
                        effect.MustPredraw = addon["must-predraw"] != null && addon["must-predraw"].ToString().ToLower().Contains("true");

                        if (addon["extend-box"] != null)
                        {
                            effect.ExtendBoxVertical = int.Parse(addon["extend-box"]["vertical"].ToString());
                            effect.ExtendBoxHorizontal = int.Parse(addon["extend-box"]["horizontal"].ToString());
                        }
                        
                        //add code fx
                        effect.Code = effectCode;

                        //setup params
                        effect.Parameters = new Dictionary<string, EffectParameter>();
                        foreach (var param in addon["parameters"])
                        {
                            var p = new EffectParameter
                            {
                                Json = param.ToString(formatting: Formatting.Indented),
                                Key = param["id"].ToString()
                            };

                            var l = lang["parameters"][p.Key];
                            p.Lang = $"\"{p.Key}\":" + l;

                            switch (param["type"].ToString())
                            {
                                case "float":
                                case "percent":
                                    p.VariableDeclaration = $"uniform lowp float {p.Key}";
                                    break;
                                case "color":
                                    p.VariableDeclaration = $"uniform lowp vec3 {p.Key}";
                                    break;
                            }   
                            effect.Parameters.Add(p.Key, p);
                        }

                        var c3addon = new C3Addon
                        {
                            AddonId = id,
                            AddonCategory = addon["category"].ToString(),
                            Author = addon["author"]?.ToString(),
                            Clreplaced = addon["name"]?.ToString()?.Replace(" ", string.Empty),
                            Company = addon["author"]?.ToString(),
                            Name = addon["name"]?.ToString(),
                            Description = addon["description"]?.ToString(),
                            AddonJson = addon.ToString(),
                            Id = Guid.NewGuid(),
                            CreateDate = DateTime.Now,
                            LastModified = DateTime.Now,
                            Type = PluginType.Effect,
                            Effect = effect
                        };

                        //c3 icon
                        c3addon.IconXml = File.Exists(Path.Combine(tmpPath, "icon.svg")) ?
                            File.ReadAllText(Path.Combine(tmpPath, "icon.svg")) :
                            ResourceReader.Insatnce.GetResourceText("c3IDE.Templates.Files.icon.svg");
                        

                        c3addon.Template = TemplateFactory.Insatnce.CreateTemplate(c3addon.Type);

                        return c3addon;
                    }
                });

            }
             catch (Exception ex)
            {
                LogManager.AddErrorLog(ex);
                LogManager.AddImportLogMessage($"ERROR -> \n{ex.Message}");
                LogManager.AddImportLogMessage($"TRACE -> \n{ex.StackTrace}");
                throw;
            }
            finally
            {
                WindowManager.ShowLoadingOverlay(false);
                var logData = string.Join(Environment.NewLine, LogManager.ImportLog);
                File.WriteAllText(Path.Combine(OptionsManager.CurrentOptions.DataPath, "import.log"), logData);
                LogManager.ImportLog.Clear();
            }

        }

19 View Source File : AceParameterHelper.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public Models.Action GenerateParam(Models.Action action, string id, string type, string value, string name, string desc)
        {
            var isVariadic = type == "variadic";

            if (action.Ace.Contains("\"params\": ["))
            {
                //ace param
                var aceTemplate = TemplateHelper.AceParam(id, type, value);

                //lang param
                var langTemplate = TemplateHelper.AceLang(id, type, name, desc);
                var newProperty = JObject.Parse(langTemplate);
                var langJson = JObject.Parse($"{{ {action.Language} }}")[action.Id];
                var langParams = langJson["params"];
                langParams.Last.AddAfterSelf(newProperty.Property(id));
                langJson["params"] = langParams;

                //code param
                var func = Regex.Match(action.Code, @"(?:\()(?<param>.*)(?:\))");
                var declaration = Regex.Match(action.Code, @".*(?:\()(?<param>.*)(?:\))").Value;
                var paramList = func.Groups["param"].Value.Split(',');
                var codeTemplate = TemplateHelper.AceCode(id, action.ScriptName, isVariadic, paramList);

                //updates
                action.Language = $"\"{action.Id}\": {langJson.ToString(formatting: Formatting.Indented)} ";
                action.Ace = FormatHelper.Insatnce.Json(Regex.Replace(action.Ace, @"}(\r\n?|\n|\s*)]", $"{aceTemplate}\r\n]"));
                action.Code = action.Code.Replace(declaration, codeTemplate);
            }
            //this will be the first param
            else
            {
                //ace param
                var aceTemplate = TemplateHelper.AceParamFirst(id, type, value);

                //language param
                var langTemplate = TemplateHelper.AceLangFirst(id, type, name, desc);

                //code param
                var codeTemplate = TemplateHelper.AceCodeFirst(id, action.ScriptName, isVariadic);

                //updates
                action.Language = action.Language.Replace(@"""
}", langTemplate);
                action.Ace = FormatHelper.Insatnce.Json(action.Ace.Replace("}", aceTemplate));
                action.Code = action.Code.Replace($"{action.ScriptName}()", codeTemplate);
            }

            return action;
        }

19 View Source File : AceParameterHelper.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso

public Models.Action GenerateParam(Models.Action action, string id, string type, string value, string name, string desc, List<string> comboItems)
        {
            var isVariadic = type == "variadic";

            if (action.Ace.Contains("\"params\": ["))
            {
                //ace param
                var aceTemplate = TemplateHelper.AceParam(id, type, value, comboItems);

                //lang param
                var langTemplate = TemplateHelper.AceLang(id, type, name, desc, comboItems);
                var newProperty = JObject.Parse(langTemplate);
                var langJson = JObject.Parse($"{{ {action.Language} }}")[action.Id];
                var langParams = langJson["params"];
                langParams.Last.AddAfterSelf(newProperty.Property(id));
                langJson["params"] = langParams;

                //code param
                var func = Regex.Match(action.Code, @"(?:\()(?<param>.*)(?:\))");
                var declaration = Regex.Match(action.Code, @".*(?:\()(?<param>.*)(?:\))").Value;
                var paramList = func.Groups["param"].Value.Split(',');
                var codeTemplate = TemplateHelper.AceCode(id, action.ScriptName, isVariadic, paramList);

                //updates
                action.Language = $"\"{action.Id}\": {langJson.ToString(formatting: Formatting.Indented)} ";
                action.Ace = FormatHelper.Insatnce.Json(Regex.Replace(action.Ace, @"}(\r\n?|\n|\s*)]", $"{aceTemplate}\r\n]"));
                action.Code = action.Code.Replace(declaration, codeTemplate);
            }
            //this will be the first param
            else
            {
                //ace param
                var aceTemplate = TemplateHelper.AceParamFirst(id, type, value, comboItems);

                //language param
                var langTemplate = TemplateHelper.AceLangFirst(id, type, name, desc, comboItems);

                //code param
                var codeTemplate = TemplateHelper.AceCodeFirst(id, action.ScriptName, isVariadic);

                //updates
                action.Language = action.Language.Replace(@"""
}", langTemplate);
                action.Ace = FormatHelper.Insatnce.Json(action.Ace.Replace("}", aceTemplate));
                action.Code = action.Code.Replace($"{action.ScriptName}()", codeTemplate);
            }

            return action;
        }

See More Examples