Here are the examples of the csharp api Newtonsoft.Json.Linq.JToken.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
836 Examples
19
View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void AddTaskItem(JObject obj)
{
ListViewItem item = new ListViewItem();
item.Tag = obj;
item.Text = obj["name"].ToString();
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
subItem.Text = obj["code"].ToString();
item.SubItems.Add(subItem);
customShellListView.Items.Add(item);
}
19
View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void button2_Click(object sender, EventArgs e)
{
string name = task_name.Text;
int count = customShellListView.Items.Count;
Object item1 = scb_condition1.SelectedItem;
Object item2 = scb_condition2.SelectedItem;
Object item3 = scb_condition3.SelectedItem;
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show(this, "请输入任务名称");
task_name.Focus();
}
else if (item1 == null)
{
MessageBox.Show(this, "请至少选择一个条件");
}
else if (count == 0)
{
MessageBox.Show(this, "请添加任务指令脚本(Shell)");
shell_name.Focus();
}
else
{
string condition = "";
ConditionItem ci1 = (ConditionItem)item1;
condition += gereplacedemUuid(ci1) + "," + (scb_status1.SelectedIndex == 1 ? "Y" : "N");
if(item2 != null){
ConditionItem ci2 = (ConditionItem)item2;
condition += gereplacedemCondi(1) + gereplacedemUuid(ci2) + "," + (scb_status2.SelectedIndex == 1 ? "Y" : "N");
if (item3 != null)
{
ConditionItem ci3 = (ConditionItem)item2;
condition += gereplacedemCondi(2) + gereplacedemUuid(ci3) + "," + (scb_status3.SelectedIndex == 1 ? "Y" : "N");
}
}
ListView.ListViewItemCollection coll = customShellListView.Items;
if (null == cmdShell)
{
cmdShell = new CmdShell();
cmdShell.Uuid = Guid.NewGuid().ToString("N");
}
JObject obj = null;
JArray list = new JArray();
List<TaskShell> shellList = new List<TaskShell>();
TaskShell task = null;
cmdShell.Name = name;
cmdShell.TaskType = TaskType.Condition;
cmdShell.Condition = condition;
cmdShell.Type = "条件任务";
foreach(ListViewItem item in coll){
obj = (JObject)item.Tag;
task = new TaskShell();
task.Uuid = Guid.NewGuid().ToString("N");
task.Shell = obj["code"].ToString();
task.Name = obj["name"].ToString();
shellList.Add(task);
}
cmdShell.ShellList = shellList;
if (null != this.callback)
{
this.callback(cmdShell);
}
this.Close();
}
}
19
View Source File : TimedTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void AddTaskItem(JObject obj)
{
ListViewItem item = new ListViewItem();
item.Tag = obj;
item.Text = obj["time"].ToString();
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListViewSubItem();
subItem.Text = obj["name"].ToString();
item.SubItems.Add(subItem);
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = obj["code"].ToString();
item.SubItems.Add(subItem);
customShellListView.Items.Add(item);
}
19
View Source File : TimedTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void button2_Click(object sender, EventArgs e)
{
string name = task_name.Text;
int count = customShellListView.Items.Count;
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show(this, "请输入任务名称");
task_name.Focus();
}
else if (count == 0)
{
MessageBox.Show(this, "请添加任务指令脚本(Shell)");
shell_name.Focus();
}
else
{
ListView.ListViewItemCollection coll = customShellListView.Items;
if (null == cmdShell)
{
cmdShell = new CmdShell();
cmdShell.Type = "定时任务";
cmdShell.TaskType = TaskType.Timed;
}
cmdShell.Name = name;
JObject obj = null;
JArray list = new JArray();
List<TaskShell> shellList = new List<TaskShell>();
TaskShell task = null;
foreach(ListViewItem item in coll){
obj = (JObject)item.Tag;
task = new TaskShell();
task.Uuid = Guid.NewGuid().ToString("N");
task.DateTime = obj["time"].ToString();
task.Shell = obj["code"].ToString();
task.Name = obj["name"].ToString();
shellList.Add(task);
}
cmdShell.ShellList = shellList;
if (null != this.callback)
{
this.callback(cmdShell);
}
this.Close();
}
}
19
View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void LoadProjectList()
{
ThreadPool.QueueUserWorkItem((a) => {
List<JObject> itemList = new List<JObject>();
// 1、获取webapps下的项目
ArrayList files = (ArrayList)monitorForm.RunSftpShell(string.Format("ls {0}webapps/", l_tomcat_path.Text), false, false);
if (files != null)
{
string dirname = "";
JObject json = null;
Object obj = null;
for (int ii = 0; ii < files.Count; ii++)
{
obj = files[ii];
if (obj is ChannelSftp.LsEntry)
{
dirname = ((ChannelSftp.LsEntry)obj).getFilename();
if (dirname.IndexOf(".") == -1 && dirname.IndexOf(":") == -1)
{
json = new JObject();
json.Add("name", dirname);
json.Add("url", l_visit_url.Text + (dirname == "ROOT" ? "" : "/" + dirname));
json.Add("path", l_tomcat_path.Text + "webapps/" + dirname);
itemList.Add(json);
}
}
}
}
// 2、获取server.xml中的映射配置
List<JObject> itemList2 = loadTomcatServerProject();
foreach (JObject p in itemList2)
{
itemList.Add(p);
}
// 渲染列表
this.BeginInvoke((MethodInvoker)delegate()
{
projects.Items.Clear();
ListViewItem item = null;
ListViewItem.ListViewSubItem subItem = null;
foreach (JObject pro in itemList)
{
item = new ListViewItem();
item.Tag = pro;
item.Name = pro["name"].ToString();
item.Text = pro["url"].ToString();
subItem = new ListViewItem.ListViewSubItem();
subItem.Text = pro["path"].ToString();
item.SubItems.Add(subItem);
projects.Items.Add(item);
}
});
});
}
19
View Source File : FrmBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void BtnAdd_Click(object sender, EventArgs e)
{
string url = gfxBrowser.Url.ToString();
string name = string.Empty;
string num = string.Empty;
switch (cmboSource.SelectedItem.ToString().ToLower())
{
case "mangadex":
name = url.Split('/')[5];
num = url.Split('/')[4];
url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;
Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
FrmEdit editor = new FrmEdit(m, false);
DialogResult result = editor.ShowDialog();
if (result == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in m.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
} catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(m);
String[] dls = m.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
} else
{ // Only download selected chapters
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
} else
{
}
break;
case "kissmanga":
// MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
// break;
// TODO
string kName = KissMangaHelper.GetName(url);
string kHash = KissMangaHelper.GetHash(url);
// Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);
FrmEdit editor1 = new FrmEdit(km, false);
DialogResult result1 = editor1.ShowDialog();
if (result1 == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in km.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
}
catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(km);
String[] dls = km.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
else
{ // Only download selected chapters
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
else
{
}
break;
case "nhentai":
num = url.Split('/')[4];
name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Nhentai(hDir, hJson.ToString());
FrmEdit edit = new FrmEdit(h, false);
DialogResult rezult = edit.ShowDialog();
if (rezult == DialogResult.OK)
{
WFClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
break;
}
MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
}
19
View Source File : BrowsePage.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void BtnAdd_Clicked(object sender, EventArgs e)
{
string url = txtUrl.Text;
string name = string.Empty;
string num = string.Empty;
if (url == "" || url == null)
{
PopUp("Error", "Please enter a URL");
return;
}
if (url.StartsWith("https://mangadex.org/replacedle/"))
{
// TODO: Name
name = url.Split('/')[5];
num = url.Split('/')[4];
url = "https://mangadex.org/api/manga/" + num;
Manga m = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
MClient.dbm.GetMangaDB().Add(m);
foreach (Chapter c in m.GetChapters())
{
MClient.dlm.AddToQueue(new MangaDexDownload(c));
}
// Start downloading the first one
MClient.dlm.DownloadNext();
}
else if (url.StartsWith("https://nhentai.net/g/"))
{
num = url.Split('/')[4];
name = txtName.Text != "" ? txtName.Text : "Hentai " + new Random().Next();
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Hentai(hDir, hJson.ToString());
MClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
MClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
MClient.dlm.DownloadNext();
} else
{
PopUp("Error", "Invalid URL!");
return;
}
PopUp("Info", "Download started!\nPlease do not close MikuReader until the download is complete.");
}
19
View Source File : BitfinexSocketApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private void SocketMessage(object sender, MessageReceivedEventArgs args)
{
var dataObject = JToken.Parse(args.Message);
if(dataObject is JObject)
{
Log.Write(LogVerbosity.Info, $"Received object message: {dataObject}");
var evnt = dataObject["event"].ToString();
if (evnt == "info")
HandleInfoEvent(dataObject.ToObject<BitfinexInfo>());
else if (evnt == "auth")
HandleAuthenticationEvent(dataObject.ToObject<BitfinexAuthenticationResponse>());
else if (evnt == "subscribed")
HandleSubscriptionEvent(dataObject.ToObject<BitfinexSubscriptionResponse>());
else if (evnt == "error")
HandleErrorEvent(dataObject.ToObject<BitfinexSocketError>());
else
HandleUnhandledEvent((JObject)dataObject);
}
else if(dataObject is JArray)
{
Log.Write(LogVerbosity.Info, $"Received array message: {dataObject}");
if(dataObject[1].ToString() == "hb")
{
// Heartbeat, no need to do anything with that
return;
}
if (dataObject[0].ToString() == "0")
HandleAccountEvent(dataObject.ToObject<BitfinexSocketEvent>());
else
HandleChannelEvent((JArray)dataObject);
}
}
19
View Source File : BitfinexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public BitfinexMarginInfoResponse GetMarginInformation()
{
var marginPost = new BitfinexPostBase
{
Request = MarginInfoRequstUrl,
Nonce = Common.UnixTimeStampUtc().ToString(CultureInfo.InvariantCulture)
};
var response = GetRestResponse(marginPost);
var jArr = JsonConvert.DeserializeObject(response) as JArray;
if (jArr == null || jArr.Count == 0)
return null;
var marginInfoStr = jArr[0].ToString();
var marginInfoResponseObj = JsonConvert.DeserializeObject<BitfinexMarginInfoResponse>(marginInfoStr);
Log.Info("Margin Info: {0}", marginInfoResponseObj.ToString());
return marginInfoResponseObj;
}
19
View Source File : Handlers.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public static void Products(string json)
{
/**
* Decode the JSON and add all products to the list.
*/
JArray products = JArray.Parse(json);
foreach (JToken product in products)
{
Worker.instance.loader.AddProduct(
JsonConvert.DeserializeObject<Product>(product.ToString())
);
}
}
19
View Source File : LayoutDescriptionEx.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
JObject jo = JObject.Load(reader);
switch (jo["Type"].Value<int>())
{
case 1:
return JsonConvert.DeserializeObject<StarsLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
case 2:
return JsonConvert.DeserializeObject<TextOnlyLineDescription>(jo.ToString(), SpecifiedSubclreplacedConversion);
default:
throw new Exception();
}
}
19
View Source File : SyncManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public void SendNet64Data(string name, byte[] data, string location)
{
if (!(data is object))
return;
var postStarsClient = new ExtendedWebClient();
JObject json = new JObject
{
["player"] = name,
["state"] = Convert.ToBase64String(data),
["location"] = location
};
string sendString = json.ToString();
NameValueCollection values = new NameValueCollection
{
{ "net", sendString }
};
postStarsClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
postStarsClient.Headers.Add(HttpRequestHeader.Cookie, token.ToString());
postStarsClient.UploadValuesAsync(new Uri(url + post), "POST", values);
}
19
View Source File : BybitServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private async void MessageReader(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (!queue_messages_received_from_fxchange.IsEmpty && queue_messages_received_from_fxchange.TryDequeue(out string mes))
{
JToken response = JToken.Parse(mes);
if (response.First.Path == "success")
{
bool is_success = response.SelectToken("success").Value<bool>();
if (is_success)
{
string type = JToken.Parse(response.SelectToken("request").ToString()).SelectToken("op").Value<string>();
if (response_handlers.ContainsKey(type))
{
response_handlers[type].Invoke(response);
}
else
{
SendLogMessage(mes, LogMessageType.System);
}
}
else if (!is_success)
{
string type = JToken.Parse(response.SelectToken("request").ToString()).SelectToken("op").Value<string>();
string error_mssage = response.SelectToken("ret_msg").Value<string>();
if (type == "subscribe" && error_mssage.Contains("already"))
continue;
SendLogMessage("Broken response success marker " + type, LogMessageType.Error);
}
}
else if (response.First.Path == "topic") //orderBookL2_25.BTCUSD
{
string type = response.SelectToken("topic").Value<string>().Split('.')[0];
if (response_handlers.ContainsKey(type))
{
response_handlers[type].Invoke(response);
}
else
{
SendLogMessage(mes, LogMessageType.System);
}
}
else
{
SendLogMessage("Broken response topic marker " + response.First.Path, LogMessageType.Error);
}
}
else
{
await Task.Delay(20);
}
}
catch (TaskCanceledException)
{
return;
}
catch (Exception exception)
{
SendLogMessage("MessageReader error: " + exception, LogMessageType.Error);
}
}
}
19
View Source File : FTXOrderCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public Order Create(JToken data)
{
var order = new Order();
var orderMarketId = data.SelectToken(IdPath).ToString();
var status = data.SelectToken(StatusPath).ToString();
order.NumberMarket = orderMarketId;
order.TimeCallBack = data.SelectToken(TimePath).Value<DateTime>();
order.Price = data.SelectToken(PricePath).Value<decimal?>() ?? default;
order.SecurityNameCode = data.SelectToken(SecurityNamePath).ToString();
order.Side = data.SelectToken(SidePath).ToString() == "sell" ?
Side.Sell :
Side.Buy;
order.Volume = data.SelectToken(SizePath).Value<decimal>();
order.TypeOrder = data.SelectToken(OrderTypePath).ToString() == "limit" ?
OrderPriceType.Limit :
OrderPriceType.Market;
order.State = ConvertOrderStatus(status);
return order;
}
19
View Source File : ExmoClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void GetMarketDepth(string securities)
{
if (securities == "")
{
return;
}
// var jsonCurrency = ApiQuery("order_book", null, securities);
// ask_quanreplacedy - объем всех ордеров на продажу
// ask_amount - сумма всех ордеров на продажу
// ask_top - минимальная цена продажи
// bid_quanreplacedy - объем всех ордеров на покупку
// bid_amount - сумма всех ордеров на покупку
// bid_top - максимальная цена покупки
// bid - список ордеров на покупку, где каждая строка это цена, количество и сумма
// ask - список ордеров на продажу, где каждая строка это цена, количество и сумма
var jsonCurrency = ApiQuery("order_book", new Dictionary<string, string>(), securities, 20);
string[] secs = securities.Split(',');
for (int i = 0; i < secs.Length; i++)
{
var jProperties = JToken.Parse(jsonCurrency)[secs[i]]; //.Children<JProperty>();
MarketDepth depth = new MarketDepth();
depth.SecurityNameCode = secs[i];
var jBid =
JToken.Parse(jProperties.SelectToken("bid").ToString());
List<MarketDepthLevel> Bids = new List<MarketDepthLevel>();
foreach (var bid in jBid)
{
MarketDepthLevel newBid = new MarketDepthLevel();
var str = bid.ToArray();
newBid.Price = str[0].ToString()
.Replace("{","")
.Replace("}", "")
.ToDecimal();
newBid.Bid = str[1].ToString()
.Replace("{", "")
.Replace("}", "")
.ToDecimal();
//newBid.Bid = bid..SelectToken("price").ToString().ToDecimal();
Bids.Add(newBid);
}
depth.Bids = Bids;
var jAsk =
JToken.Parse(jProperties.SelectToken("ask").ToString());
List<MarketDepthLevel> Ask = new List<MarketDepthLevel>();
foreach (var ask in jAsk)
{
MarketDepthLevel newAsk = new MarketDepthLevel();
var str = ask.ToArray();
newAsk.Price = str[0].ToString()
.Replace("{", "")
.Replace("}", "")
.ToDecimal();
newAsk.Ask = str[1].ToString()
.Replace("{", "")
.Replace("}", "")
.ToDecimal();
//newBid.Bid = bid..SelectToken("price").ToString().ToDecimal();
Ask.Add(newAsk);
}
depth.Asks = Ask;
if (UpdateMarketDepth != null)
{
UpdateMarketDepth(depth);
}
}
}
19
View Source File : ExmoClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void ExecuteOrder(Order order)
{
lock (_lockOrder)
{
try
{
if (IsConnected == false)
{
order.State = OrderStateType.Fail;
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
return;
}
/* pair - валютная пара
quanreplacedy - кол - во по ордеру
price - цена по ордеру
type - тип ордера, может принимать следующие значения:
buy - ордер на покупку
sell - ордер на продажу*/
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("pair", order.SecurityNameCode);
param.Add("type", order.Side == Side.Buy ? "buy" : "sell");
param.Add("quanreplacedy",
order.Volume.ToString(CultureInfo.InvariantCulture)
.Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, "."));
param.Add("price",
order.Price.ToString(CultureInfo.InvariantCulture)
.Replace(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator, "."));
var jsonCurrency = ApiQuery("order_create", param);
string res =
JToken.Parse(jsonCurrency).SelectToken("result").ToString();
if (Convert.ToBoolean(res.ToLower()) != true)
{
order.State = OrderStateType.Fail;
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
string error =
JToken.Parse(jsonCurrency).SelectToken("error").ToString();
SendLogMessage("Exmo order execution error. " + error, LogMessageType.Error);
return;
}
string id =
JToken.Parse(jsonCurrency).SelectToken("order_id").ToString();
order.NumberMarket = id;
order.State = OrderStateType.Activ;
/* "result": true,
"error": "",
"order_id": 123456*/
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
}
catch (Exception ex)
{
SendLogMessage(ex.ToString(), LogMessageType.Error);
}
}
}
19
View Source File : FTXTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public MyTrade CreateMyTrade(JToken data)
{
var trade = new MyTrade();
trade.SecurityNameCode = data.SelectToken(SecurityNamePath).ToString();
trade.NumberOrderParent = data.SelectToken(OrderIdPath).ToString();
trade.Price = data.SelectToken(PricePath).Value<decimal>();
trade.Volume = data.SelectToken(SizePath).Value<decimal>();
trade.Side = data.SelectToken(SidePath).ToString() == "sell" ? Side.Sell : Side.Buy;
trade.NumberTrade = data.SelectToken(TradeIdPath).ToString();
trade.Time = data.SelectToken(TimePath).Value<DateTime>();
return trade;
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private async void MessageReader(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (!_queueMessagesReceivedFromExchange.IsEmpty &&
_queueMessagesReceivedFromExchange.TryDequeue(out string mes))
{
var response = JToken.Parse(mes);
var type = response.SelectToken("type").ToString();
if (_responseHandlers.ContainsKey(type))
{
lock (_locker)
{
_responseHandlers[type].Invoke(response);
}
}
else
{
SendLogMessage(mes, LogMessageType.System);
}
}
else
{
await Task.Delay(20);
}
}
catch (TaskCanceledException)
{
return;
}
catch (Exception exception)
{
SendLogMessage("MessageReader error: " + exception, LogMessageType.Error);
}
}
}
19
View Source File : GateIoServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void MessageReader(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
if (!_queueMessagesReceivedFromExchange.IsEmpty)
{
string mes;
if (_queueMessagesReceivedFromExchange.TryDequeue(out mes))
{
if (mes.StartsWith("{\"error"))
{
continue;
}
var jt = JToken.Parse(mes);
var channel = jt.SelectToken("method").ToString();
if (channel == "trades.update")
{
foreach (var trade in _tradesCreator.Create(mes))
{
OnTradeEvent(trade);
}
}
else if (channel == "depth.update")
{
OnMarketDepthEvent(_marketDepthCreator.Create(mes));
}
else if (channel == "balance.update")
{
OnPortfolioEvent(_portfolioCreator.UpdatePortfolio(mes));
}
else if (channel == "order.update")
{
OnOrderEvent(_orderCreator.Create(mes));
}
}
}
else
{
Thread.Sleep(20);
}
}
catch (TaskCanceledException)
{
return;
}
catch (Exception exception)
{
SendLogMessage("MessageReader error: " + exception, LogMessageType.Error);
}
}
}
19
View Source File : GateIoServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void SendOrder(Order order)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}={1}", "currencyPair", order.SecurityNameCode.ToLower());
builder.Append("&");
builder.AppendFormat("{0}={1}", "rate", order.Price);
builder.Append("&");
builder.AppendFormat("{0}={1}", "amount", order.Volume);
builder.Append("&");
builder.AppendFormat("{0}={1}", "text", "t-" + order.NumberUser);
var headers = new Dictionary<string, string>();
headers.Add("Key", _publicKey);
headers.Add("Sign", SingRestData(_secretKey, builder.ToString()));
var data = Encoding.UTF8.GetBytes(builder.ToString());
var endPoint = order.Side == Side.Buy ? "buy" : "sell";
var result = _restChannel.SendPostQuery(PrivateRestUri, endPoint, data, headers);
var jt = JToken.Parse(result);
var responseData = jt["result"].ToString();
if (responseData == "false")
{
order.State = OrderStateType.Fail;
OnOrderEvent(order);
SendLogMessage("Error placing order: you have insufficient funds", LogMessageType.Trade);
}
}
19
View Source File : GateIoServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public override void CancelOrder(Order order)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}={1}", "orderNumber", order.NumberMarket);
builder.Append("&");
builder.AppendFormat("{0}={1}", "currencyPair", order.SecurityNameCode.ToLower());
builder.Append("&");
builder.AppendFormat("{0}={1}", "text", "t-" + order.NumberUser);
var headers = new Dictionary<string, string>();
headers.Add("Key", _publicKey);
headers.Add("Sign", SingRestData(_secretKey, builder.ToString()));
var data = Encoding.UTF8.GetBytes(builder.ToString());
var endPoint = "cancelOrder";
var result = _restChannel.SendPostQuery(PrivateRestUri, endPoint, data, headers);
var jt = JToken.Parse(result);
var responseData = jt["result"].ToString();
if (responseData == "false")
{
SendLogMessage(jt["message"].ToString(), LogMessageType.Error);
}
}
19
View Source File : KrakenSocket.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleErrorMessage(JToken response)
{
var errorMessage = response.SelectToken("msg").ToString();
if(errorMessage == "Already subscribed")
{
return;
}
SendLogMessage(errorMessage, LogMessageType.Error);
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleSubscribedMessage(JToken response)
{
var channel = response.SelectToken("channel").ToString();
switch (channel)
{
case "trades":
var securityName = response.SelectToken("market").ToString();
_subscribedSecurities.Add(securityName);
break;
case "fills":
_isPortfolioSubscribed = true;
break;
default:
break;
}
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleUnsubscribedMessage(JToken response)
{
var channel = response.SelectToken("channel").ToString();
switch (channel)
{
case "trades":
var securityName = response.SelectToken("market").ToString();
_subscribedSecurities.Remove(securityName);
break;
case "fills":
_isPortfolioSubscribed = false;
break;
default:
break;
}
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleInfoMessage(JToken response)
{
SendLogMessage(response.ToString(), LogMessageType.NoName);
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandlePartialMessage(JToken response)
{
var channel = response.SelectToken("channel").ToString();
var data = response.SelectToken("data");
var securityName = response.SelectToken("market").ToString();
switch (channel)
{
case "orderbook":
var marketDepth = _marketDepthCreator.Create(data);
marketDepth.SecurityNameCode = securityName;
if (_securityMarketDepths.ContainsKey(marketDepth.SecurityNameCode))
{
_securityMarketDepths[marketDepth.SecurityNameCode] = marketDepth;
}
else
{
_securityMarketDepths.Add(marketDepth.SecurityNameCode, marketDepth);
}
OnMarketDepthEvent(marketDepth);
break;
case "trades":
break;
case "ticker":
break;
case "fills":
break;
case "orders":
break;
default:
SendLogMessage("Unhandeled channel :" + channel, LogMessageType.System);
break;
}
}
19
View Source File : FTXServer.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void HandleUpdateMessage(JToken response)
{
var channel = response.SelectToken("channel").ToString();
var data = response.SelectToken("data");
var securityName = response.SelectToken("market")?.ToString();
switch (channel)
{
case "orderbook":
HandleUpdateMarketDepthMessage(data, securityName);
break;
case "trades":
var trades = _tradesCreator.Create(data, securityName);
foreach(var trade in trades)
{
OnTradeEvent(trade);
}
break;
case "ticker":
break;
case "fills":
OnMyTradeEvent(_tradesCreator.CreateMyTrade(data));
break;
case "orders":
HandleUpdateOrderMessage(data);
break;
default:
SendLogMessage("Unhandeled channel :" + channel, LogMessageType.System);
break;
}
}
19
View Source File : GateMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : GateMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private MarketDepth CreateNew(JArray quotes)
{
var newDepth = new MarketDepth();
newDepth.Time = DateTime.UtcNow;
newDepth.SecurityNameCode = quotes[2].ToString();
var needDepth = _allDepths.Find(d => d.SecurityNameCode == newDepth.SecurityNameCode);
if (needDepth != null)
{
_allDepths.Remove(needDepth);
}
var bids = quotes[1]["bids"].Children();
var asks = quotes[1]["asks"].Children();
foreach (var bid in bids)
{
newDepth.Bids.Add(new MarketDepthLevel()
{
Price = bid[0].Value<decimal>(),
Bid = bid[1].Value<decimal>(),
});
}
foreach (var ask in asks)
{
newDepth.Asks.Add(new MarketDepthLevel()
{
Price = ask[0].Value<decimal>(),
Ask = ask[1].Value<decimal>(),
});
}
_allDepths.Add(newDepth);
return newDepth.GetCopy();
}
19
View Source File : GateMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private MarketDepth Update(JArray quotes)
{
var needDepth = _allDepths.Find(d => d.SecurityNameCode == quotes[2].ToString());
if (needDepth == null)
{
throw new ArgumentNullException("GateIo: MarketDepth for updates not found");
}
if (quotes[1]["bids"] != null)
{
var bidsLevels = quotes[1]["bids"].Children();
foreach (var bidLevel in bidsLevels)
{
decimal price = bidLevel[0].Value<decimal>();
decimal bid = bidLevel[1].Value<decimal>();
if (bid != 0)
{
InsertLevel(price, bid, Side.Buy, needDepth);
}
else
{
DeleteLevel(price, Side.Buy, needDepth);
}
}
SortBids(needDepth.Bids);
}
if (quotes[1]["asks"] != null)
{
var asksLevels = quotes[1]["asks"].Children();
foreach (var askLevel in asksLevels)
{
decimal price = askLevel[0].Value<decimal>();
decimal ask = askLevel[1].Value<decimal>();
if (ask != 0)
{
InsertLevel(price, ask, Side.Sell, needDepth);
}
else
{
DeleteLevel(price, Side.Sell, needDepth);
}
}
SortAsks(needDepth.Asks);
}
return needDepth.GetCopy();
}
19
View Source File : GateTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
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 : TinkoffClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public void ExecuteOrder(Order order)
{
lock (_lockOrder)
{
try
{
if (IsConnected == false)
{
order.State = OrderStateType.Fail;
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
return;
}
string request = "";
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("lots", order.Volume.ToString());
param.Add("operation", order.Side.ToString());
param.Add("price", order.Price.ToString());
// curl - X POST "https://api-invest.tinkoff.ru/openapi/orders/limit-order?figi=BBG004730N88" -
// H "accept: application/json" - H "Authorization: Bearer t.ZmEaoirPe5unR6Cw0o7YSq-Hl4lCkGES-0XgZmOg9XGl_Ds6OeAzdS9P-x1lRmQjzu7Ol6cMTgN-QUv9ISvyGQ"
// -
//H "Content-Type: application/json" - d "{\"lots\":1,\"operation\":\"Buy\",\"price\":230}"
Security security = _allSecurities.Find(sec => sec.Name == order.SecurityNameCode);
if (security == null)
{
return;
}
string url = _url + "orders/limit-order?figi=" + security.NameId;
var jsonCurrency = ApiQuery(url, "POST", param);
if (jsonCurrency == null)
{
order.State = OrderStateType.Fail;
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
return;
}
var jorder = JToken.Parse(jsonCurrency).SelectToken("payload");
order.NumberMarket = jorder.SelectToken("orderId").ToString();
//order.NumberUser = Convert.ToInt32(Convert.ToInt64(order.NumberMarket) - 100000000);
order.State = OrderStateType.Activ;
order.TimeCallBack = DateTime.Now;
if (MyOrderEvent != null)
{
MyOrderEvent(order);
}
}
catch (Exception ex)
{
SendLogMessage(ex.ToString(), LogMessageType.Error);
}
}
}
19
View Source File : ZbMarketDepthCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public MarketDepth Create(string data)
{
var jt = JToken.Parse(data);
var time = jt[TimePath].ToString();
var newDepth = new MarketDepth();
newDepth.Time = TimeManager.GetDateTimeFromTimeStampSeconds(Convert.ToInt64(time));
newDepth.SecurityNameCode = jt[NamePath].ToString().Split('_')[0];
var bids = jt.SelectTokens(BidsPath).Children();
var asks = jt.SelectTokens(AsksPath).Children();
foreach (var bid in bids)
{
newDepth.Bids.Add(new MarketDepthLevel()
{
Price = bid[0].Value<decimal>(),
Bid = bid[1].Value<decimal>(),
});
}
for (int i = asks.Count() -1; i> 0 ; i--)
{
JToken ask = asks.ElementAt(i);
newDepth.Asks.Add(new MarketDepthLevel()
{
Price = ask[0].Value<decimal>(),
Ask = ask[1].Value<decimal>(),
});
}
return newDepth;
}
19
View Source File : ZbTradesCreator.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public List<Trade> Create(string data)
{
var trades = new List<Trade>();
var jt = JToken.Parse(data);
var tradesData = jt.SelectTokens(DataPath).Children();
var security = jt[NamePath].ToString().Split('_')[0];
foreach (var trade in tradesData)
{
var time = trade[TimePath].ToString();
var newTrade = new Trade();
newTrade.Time = TimeManager.GetDateTimeFromTimeStampSeconds(Convert.ToInt64(time));
newTrade.SecurityNameCode = security;
newTrade.Price = trade[PricePath].Value<decimal>();
newTrade.Id = trade[IdPath].ToString();
newTrade.Side = trade[DirectionPath].ToString() == "sell" ? Side.Sell : Side.Buy;
newTrade.Volume = trade[VolumePath].Value<decimal>();
trades.Add(newTrade);
}
return trades;
}
19
View Source File : KeyBinding.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko
License : GNU General Public License v2.0
Project Creator : AmanoTooko
public static void LoadConfig()
{
var settingArrayList = Settings.Default.KeyBinding37;
if (Settings.Default.IsEightKeyLayout) settingArrayList = Settings.Default.KeyBinding13;
var settingKeyArrayList = Settings.Default.CtrlKeyBinding;
if (settingArrayList != null)
for (var i = 0; i < settingArrayList.Count; i++)
_keymap[i + 48] = (int) settingArrayList[i];
if (settingKeyArrayList != null)
{
_ctrKeyMap["OctaveLower"] = (Keys)settingKeyArrayList[0];
_ctrKeyMap["OctaveHigher"] = (Keys)settingKeyArrayList[1];
}
var tmpArraylist = JsonConvert.DeserializeObject<ArrayList>(Settings.Default.HotKeyBinding);
hotkeyArrayList = new ArrayList();
foreach (JObject j in tmpArraylist)
hotkeyArrayList.Add(new GlobalHotKey(j["Name"].ToString(), (Modifiers) j["Modifiers"].Value<int>(),
(Keys) j["Key"].Value<int>(), j["Enabled"].Value<bool>()));
}
19
View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin
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
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 : Main.cs
License : GNU Lesser General Public License v3.0
Project Creator : andisturber
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 : NgItemWizard.cs
License : MIT License
Project Creator : andfomin
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 : Anki.cs
License : MIT License
Project Creator : AnkiTools
License : MIT License
Project Creator : AnkiTools
private void AddFields(JObject models, List<double> mids)
{
var regex = new Regex("{{hint:(.*?)}}|{{type:(.*?)}}|{{(.*?)}}");
foreach (var mid in mids)
{
var qfmt = models["" + mid]["tmpls"].First["qfmt"].ToString().Replace("\"", "");
var afmt = models["" + mid]["tmpls"].First["afmt"].ToString();
var css = models["" + mid]["css"].ToString();
afmt = afmt.Replace("{{FrontSide}}", qfmt);
var matches = regex.Matches(afmt);
FieldList fields = new FieldList();
foreach (Match match in matches)
{
if (match.Value.Contains("type:") || match.Value.Contains("hint:"))
continue;
var value = match.Value;
var field = new Field(value.Replace("{{", "").Replace("}}", ""));
fields.Add(field);
}
_infoPerMid.Add("" + mid, new Info(afmt.Replace("\n", "\\n"), css.Replace("\n", "\\n"), fields));
}
}
19
View Source File : FlowHelper.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
public static async Task<Customer> GetFlowOutput(string userId)
{
using (HttpClient httpClient = new HttpClient())
{
try
{
httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
// Create a JSON object
JObject user = new JObject();
user.Add("userId", userId);
// Get response from Microsoft Flow
var stringContent = new StringContent(user.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync("https://prod-123.westus.logic.azure.com:443/workflows/e3a77fa66f25479d9c9633ed5c579946/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=gKmbRSPO1BzvPUc8RxRZtcttqSQErPXDbB8bK28PXO0", stringContent);
var array = response.Content.ReadreplacedtringAsync().Result.Split('|');
// Customer
return new Customer()
{
Name = array[0],
Address = array[1],
MobileNumber = array[2]
};
}
catch(Exception ex)
{
throw ex;
}
}
}
19
View Source File : D365WebAPIHelper.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
public async static Task<string> GenerateLead(Prospect prospect, CRMCredentials crmUser)
{
HttpMessageHandler messageHandler = null;
Version webAPIVersion = new Version(9, 0);
//One message handler for OAuth authentication, and the other for Windows integrated
// authentication. (replacedumes that HTTPS protocol only used for CRM Online.)
if (crmUser.ServiceUrl.StartsWith("https://"))
{
messageHandler = new OAuthMessageHandler(crmUser.ServiceUrl, crmUser.ClientID, crmUser.RedirectUrl, crmUser.AuthpointEnd, crmUser.Key,
new HttpClientHandler());
}
try
{
//Create an HTTP client to send a request message to the CRM Web service.
using (HttpClient httpClient = new HttpClient(messageHandler))
{
//Specify the Web API address of the service and the period of time each request
// has to execute.
httpClient.BaseAddress = new Uri(crmUser.ServiceUrl);
httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// Get the current userId of the service account (owner incase of Lead)
HttpResponseMessage whoAmIResponse = await httpClient.GetAsync("api/data/v9.0/WhoAmI");
Guid userId;
if (whoAmIResponse.IsSuccessStatusCode)
{
JObject jWhoAmIResponse =
JObject.Parse(whoAmIResponse.Content.ReadreplacedtringAsync().Result);
userId = (Guid)jWhoAmIResponse["UserId"];
// Populate the fields of prospect customer (lead)
JObject lead = new JObject();
lead.Add("subject", "Lead from the Event Bot");
lead.Add("lastname", prospect.Name);
lead.Add("mobilephone", prospect.PhoneNumber);
lead.Add("emailaddress1", prospect.Email);
lead.Add("[email protected]", $"/systemusers({userId})");
// Create request and response
HttpRequestMessage createRequest = new HttpRequestMessage(HttpMethod.Post, "api/data/v9.0/leads");
createRequest.Content = new StringContent(lead.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage createResponse = await httpClient.SendAsync(createRequest);
// Check if the status is good to go (204)
if (createResponse.StatusCode == HttpStatusCode.NoContent)
{
return Helpers.Common.GenerateReferenceID(6);
}
else
{
return $"Failed to register {createResponse.StatusCode}";
}
}
else
return $"Failed - {whoAmIResponse.StatusCode}";
}
}
catch (Exception ex)
{
throw ex;
}
}
19
View Source File : FlowHelper.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
public static async Task<Customer> GetFlowOutput(string userId)
{
using (HttpClient httpClient = new HttpClient())
{
try
{
httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
// Create a JSON object
JObject user = new JObject();
user.Add("userId", userId);
// Get response from Microsoft Flow
var stringContent = new StringContent(user.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync("https://prod-81.westus.logic.azure.com:443/workflows/a4c85f0fb48f4e3e94ed88c4271afdce/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=e1Pw3CXokS9J4Gk8MhHMaWgth1AlDHRcNYxOdky9DE0", stringContent);
var array = response.Content.ReadreplacedtringAsync().Result.Split('|');
// Customer
return new Customer()
{
Name = array[0],
Address = array[1],
MobileNumber = array[2]
};
}
catch(Exception ex)
{
throw ex;
}
}
}
19
View Source File : FlowHelper.cs
License : MIT License
Project Creator : arafattehsin
License : MIT License
Project Creator : arafattehsin
public static async Task<Customer> GetFlowOutput(string userId)
{
using (HttpClient httpClient = new HttpClient())
{
try
{
httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes
// Create a JSON object
JObject user = new JObject();
user.Add("userId", userId);
// Get response from Microsoft Flow
var stringContent = new StringContent(user.ToString(), Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync("https://prod-03.westus.logic.azure.com:443/workflows/f446abefc3734bc589de93712347d6e5/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=aS5_STOxFTMx2hND4zLMQSqZDNyFqlZse0t5VgguCMM", stringContent);
var array = response.Content.ReadreplacedtringAsync().Result.Split('|');
// Customer
return new Customer()
{
Name = array[0],
Address = array[1],
MobileNumber = array[2]
};
}
catch(Exception ex)
{
throw ex;
}
}
}
19
View Source File : C2ParsingService.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso
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
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 : TemplateHelper.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso
License : GNU General Public License v3.0
Project Creator : armandoalonso
public static string GeneratePropertyLang(string editTime, string propLang)
{
//generate new property json
var propertyRegex = new Regex(@"new SDK[.]PluginProperty\(\""(?<type>\w+)\""\W+\""(?<id>(\w+|-)+)\""");
var propertyMatches = propertyRegex.Matches(editTime);
//get current dynamic properties
var dynamicProps = JToken.Parse($"{{{propLang}}}")["properties"];
var propList = new List<string>();
foreach (Match m in propertyMatches)
{
var type = m.Groups["type"].ToString();
var id = m.Groups["id"].ToString();
string template;
if (dynamicProps?[id] != null)
{
//prop already exists
var value = dynamicProps[id].ToString();
template = $"\"{id}\": {value}";
}
else
{
//this prop is new
switch (type)
{
case "combo":
template = TemplateHelper.LanguagePropertyCombo(id);
break;
case "link":
template = TemplateHelper.LanguagePropertyLink(id);
break;
default:
template = TemplateHelper.LanguagePropertyDefault(id);
break;
}
}
//create new property
propList.Add(template);
}
//set the editor to the new property json
return FormatHelper.Insatnce.Json(TemplateHelper.LanguageProperty(string.Join(",\n", propList)), true);
}
19
View Source File : ResourceManager.cs
License : GNU General Public License v2.0
Project Creator : Asixa
License : GNU General Public License v2.0
Project Creator : Asixa
public static float JsonToF(JToken t) => float.Parse(t.ToString());
19
View Source File : ResourceManager.cs
License : GNU General Public License v2.0
Project Creator : Asixa
License : GNU General Public License v2.0
Project Creator : Asixa
public static Vector3 JsonToV3(JToken t) =>Vector3.FromList(JsonConvert.DeserializeObject<List<float>>(t.ToString()));
See More Examples