public static GcmNotification WithData(this GcmNotification n, IDictionary<string, string> data)
		{
			if (data == null)
				return n;

			var json = new Newtonsoft.Json.Linq.JObject();

			try
			{
				if (!String.IsNullOrEmpty (n.JsonData))
					json = Newtonsoft.Json.Linq.JObject.Parse (n.JsonData);
			}
			catch { } 

			foreach (var pair in data)
				json.Add (pair.Key, new Newtonsoft.Json.Linq.JValue (pair.Value));

			n.JsonData = json.ToString (Newtonsoft.Json.Formatting.None);

			return n;
		}
Example #2
0
        public void ProcessRequest(HttpContext context)
        {
            //write your handler implementation here.
            string Obj = context.Request["object"];
            if (!string.IsNullOrEmpty(Obj)) {
                switch (Obj.ToLower()) {
                    case "dashboard":
                        string nodeType = context.Request["nodeType"];
                        switch (nodeType) {
                            case "RootNode":
                                Newtonsoft.Json.Linq.JObject ResultSet = new Newtonsoft.Json.Linq.JObject();
                                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                                xDoc.Load(context.Server.MapPath("~/Admin/Config/ApplicationSettings.xml"));
                                Newtonsoft.Json.Converters.XmlNodeConverter converter = new Newtonsoft.Json.Converters.XmlNodeConverter();
                                string OutputJSON = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xDoc).Replace("@", string.Empty);
                                context.Response.Write(OutputJSON);
                                break;
                            default:
                                string[] TypeParts = nodeType.Split(',');

                                break;
                        }
                        break;
                }
            }
        }
Example #3
0
 public Newtonsoft.Json.Linq.JObject getData()
 {
     Newtonsoft.Json.Linq.JObject obj = new Newtonsoft.Json.Linq.JObject();
     obj[Fields.Position] = Newtonsoft.Json.Linq.JToken.FromObject(Position);
     obj[Fields.Direction] = Newtonsoft.Json.Linq.JToken.FromObject(Direction);
     return obj;
 }
Example #4
0
 public override void Process(System.Web.HttpContext context)
 {
     if (context.Request["action"] == null || !SAAO.User.IsLogin) return;
     if (context.Request["action"] == "list")
     {
         R.Data = SAAO.Event.ListJson();
     }
     else if (context.Request["action"] == "update")
     {
         if (context.Request.Form["event_id"] == null || context.Request.Form["start_date"] == null || context.Request.Form["end_date"] == null) return;
         if (context.Request.Form["event_text"] == null)
         {
             R.Flag = 2;
         }
         else
         {
             var o = new Newtonsoft.Json.Linq.JObject
             {
                 ["event_id"] = context.Request.Form["event_id"],
                 ["event_text"] = context.Request.Form["event_text"],
                 ["start_date"] = context.Request.Form["start_date"],
                 ["end_date"] = context.Request.Form["end_date"]
             };
             R.Data = SAAO.Event.UpdateEvent(o);
         }
     }
     else if (context.Request["action"] == "delete")
     {
         if (context.Request["id"] == null) return;
         SAAO.Event.DeleteEvent(context.Request["id"].ToString());
     }
 }
Example #5
0
 public virtual JSONObject toJSONObject()
 {
     JSONObject obj = new JSONObject();
     obj.Add("symbol", symbol);
     obj.Add("period", (long?)period.longValue());
     obj.Add("start", start);
     return obj;
 }
        private void web1_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            GTMAccessToken _gtmAccessToken = null;

            if (e.Uri.Query.ToLower().IndexOf("code") != -1 )
            {
                //get the "code" from GTM
                string _code = e.Uri.Query.Replace("?code=", "");
                e.Cancel = true;

                var _rc = new RestSharp.RestClient(@"https://api.citrixonline.com");
                RestSharp.RestRequest _gtmTokenCodeReq = new RestSharp.RestRequest("/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id={api_key}", RestSharp.Method.GET);
                _gtmTokenCodeReq.AddUrlSegment("responseKey", _code);
                _gtmTokenCodeReq.AddUrlSegment("api_key", this.gtmAPIKey.Text);

                var _gtmTokenCodeResp = _rc.Execute(_gtmTokenCodeReq);

                if (_gtmTokenCodeResp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var jsonCode = _gtmTokenCodeResp.Content;
                    _gtmAccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject<GTMAccessToken>(jsonCode);
                }

                //now we have the token. Create a meeting
                var _gtmMeetingReq = new RestSharp.RestRequest(@"/G2M/rest/meetings", RestSharp.Method.POST);
                _gtmMeetingReq.AddHeader("Accept", "application/json");
                _gtmMeetingReq.AddHeader("Content-type", "application/json");
                _gtmMeetingReq.AddHeader("Authorization", string.Format("OAuth oauth_token={0}", _gtmAccessToken.access_token));

                //creating the meeting request json for the request.
                Newtonsoft.Json.Linq.JObject _meetingRequestJson = new Newtonsoft.Json.Linq.JObject();
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("subject", "Immediate Meeting"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("starttime", DateTime.UtcNow.AddSeconds(30).ToString("s")));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("endtime", DateTime.UtcNow.AddHours(1).AddSeconds(30).ToString("s")));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("passwordrequired", "false"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("conferencecallinfo", "Hybrid"));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("timezonekey", ""));
                _meetingRequestJson.Add(new Newtonsoft.Json.Linq.JProperty("meetingtype", "Immediate"));

                //converting the jobject back to string for use within the request
                string gtmJSON = Newtonsoft.Json.JsonConvert.SerializeObject(_meetingRequestJson);

                _gtmMeetingReq.AddParameter("text/json", gtmJSON, RestSharp.ParameterType.RequestBody);

                var _responseMeetingRequest = _rc.Execute(_gtmMeetingReq);

                if (_responseMeetingRequest.StatusCode == System.Net.HttpStatusCode.Created)
                {
                    // meeting created to add a message, format it and add it to the list
                    string _meetingResponseJson = _responseMeetingRequest.Content;

                    Newtonsoft.Json.Linq.JArray _meetingResponse = Newtonsoft.Json.Linq.JArray.Parse(_meetingResponseJson);
                    var _gtmMeetingObject = _meetingResponse[0];

                    MessageBox.Show(_gtmMeetingObject["joinURL"].ToString());
                }
            }
        }
Example #7
0
 public override string toJSONString()
 {
     JSONObject obj = new JSONObject();
     obj.Add("command", commandName);
     obj.Add("prettyPrint", prettyPrint);
     obj.Add("arguments", arguments);
     obj.Add("extended", true);
     return obj.ToString();
 }
Example #8
0
 public void FieldsFromJSONObject(JSONObject value)
 {
     this.balance = (double?)value["balance"];
     this.equity = (double?)value["equity"];
     this.currency = (string)value["currency"];
     this.margin = (double?)value["margin"];
     this.margin_free = (double?)value["margin_free"];
     this.margin_level = (double?)value["margin_level"];
 }
 public Signout(string email, string password)
 {
     Url = Urls.Signout;
     ToPost = new Newtonsoft.Json.Linq.JObject
     {
         {"username", email},
         {"password", password},
     }.ToString();
 }
Example #10
0
        /// <summary>
        /// Initialises a new GameState object from JSON Data
        /// </summary>
        /// <param name="json_data"></param>
        public GameState(string json_data)
        {
            if (json_data.Equals(""))
            {
                json_data = "{}";
            }

            json = json_data;
            _ParsedData = Newtonsoft.Json.Linq.JObject.Parse(json_data);
        }
Example #11
0
 public virtual JSONObject toJSONObject()
 {
     JSONObject obj = new JSONObject();
     obj.Add("cmd", (long)cmd.longValue());
     obj.Add("type", (long)type.longValue());
     obj.Add("price", price);
     obj.Add("sl", sl);
     obj.Add("tp", tp);
     obj.Add("symbol", symbol);
     obj.Add("volume", volume);
     obj.Add("ie_deviation", ie_deviation);
     obj.Add("order", order);
     obj.Add("comment", comment);
     obj.Add("expiration", expiration);
     return obj;
 }
Example #12
0
        public void GET(string key, RequestInfo info)
        {
            // Start with a scratch object
            var o = new Newtonsoft.Json.Linq.JObject();

            // Add application wide settings
            o.Add("ApplicationOptions", new Newtonsoft.Json.Linq.JArray(
                from n in Program.DataConnection.Settings
                select Newtonsoft.Json.Linq.JObject.FromObject(n)
            ));

            try
            {
                // Add built-in defaults
                Newtonsoft.Json.Linq.JObject n;
                using(var s = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".newbackup.json")))
                    n = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(s.ReadToEnd());

                MergeJsonObjects(o, n);
            }
            catch
            {
            }

            try
            {
                // Add install defaults/overrides, if present
                var path = System.IO.Path.Combine(Duplicati.Library.AutoUpdater.UpdaterManager.InstalledBaseDir, "newbackup.json");
                if (System.IO.File.Exists(path))
                {
                    Newtonsoft.Json.Linq.JObject n;
                    n = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(System.IO.File.ReadAllText(path));

                    MergeJsonObjects(o, n);
                }
            }
            catch
            {
            }

            info.OutputOK(new
            {
                success = true,
                data = o
            });
        }
Example #13
0
        public void CreateNewProject(string path, string name)
        {
            path = Path.GetFullPath(path);
            string wrkdir = "resources";

            Newtonsoft.Json.Linq.JObject args = new Newtonsoft.Json.Linq.JObject();
            args["inputPath"] = wrkdir;
            args["outputPath"] = path;
            args["name"] = name;
            if (TemplateFilesManager.ProcessTemplates(MAKE_NEW_PROJECT_TEMPLATE_PATH, args) && Directory.Exists(path))
            {
                ProjectModel projectModel = new ProjectModel();
                projectModel.Setup(name, path);
                string json = JsonConvert.SerializeObject(projectModel, Formatting.Indented);
                File.WriteAllText(projectModel.ProjectFilePath, json);
                OpenProject(projectModel.ProjectFilePath);
            }
        }
Example #14
0
        public async void makeRequest()
        {
            var param = File.ReadAllLines("auth.dat");
            Newtonsoft.Json.Linq.JObject RESPONSE = Newtonsoft.Json.Linq.JObject.Parse(param[0]);
            using (var newClient = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                    {"grant_type", "refresh_token"},
                    {"refresh_token", (string)RESPONSE["refresh_token"]},
                    {"client_id", "envatomate-3ur0bxxw"},
                    {"client_secret", "hhlB6MdIT5xCEy3wlwwbOaEK2XryGYqe"}
                };
                var content = new FormUrlEncodedContent(values);
                var response = await newClient.PostAsync("https://api.envato.com/token", content);
                var responseString = await response.Content.ReadAsStringAsync();
                Newtonsoft.Json.Linq.JObject NEWRESPONSE = Newtonsoft.Json.Linq.JObject.Parse(responseString);
                refreshedResponse = NEWRESPONSE;
                accessToken = (string)refreshedResponse["access_token"];
            }

            var client = new RestClient("https://api.envato.com/v1/market/private/user/account.json");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Authorization", "Bearer " + refreshedResponse.GetValue("access_token"));
            IRestResponse newResponse = client.Execute(request);


            // Check Response //
            Newtonsoft.Json.Linq.JObject THIS_ENVATO_RESPONSE = Newtonsoft.Json.Linq.JObject.Parse(newResponse.Content);
            //DEBUG - MessageBox.Show(ENVATO_RESPONSE.ToString());//
            // End of checking //

            // Populate the form //
            welcomeLabel.Text = ("Welcome, " + (string)THIS_ENVATO_RESPONSE["account"]["firstname"] + ".");
            profileImg.ImageLocation = (string)THIS_ENVATO_RESPONSE["account"]["image"];
            UI_BALANCE.Text = "£" + (string)THIS_ENVATO_RESPONSE["account"]["balance"];
            // End of populating //
        }
Example #15
0
 public string ToJson()
 {
     Newtonsoft.Json.Linq.JObject res = new Newtonsoft.Json.Linq.JObject();
     res.Add("state", _state);
     if (_state)
     {
         if (_data.Count > 0)
         {
             Newtonsoft.Json.Linq.JObject data = new Newtonsoft.Json.Linq.JObject();
             Newtonsoft.Json.Linq.JProperty propData = new Newtonsoft.Json.Linq.JProperty("data", data);
             res.Add(propData);
             foreach (string key in _data.Keys)
             {
                 data.Add(key, _data[key].ToString());
             }
         }
     }
     else
     {
         res.Add("message", _message ?? "错误");
     }
     return res.ToString();
 }
        private void FormatResult(Newtonsoft.Json.Linq.JObject jobj, int i)
        {
            if (type == "recipes")
            {
                string name         = jobj["name"].ToString();
                string author       = jobj["author_name"].ToString();
                string instructions = jobj["instructions"].ToString();
                string preptime     = jobj["prep_time"].ToString();
                string portions     = jobj["portions"].ToString();
                string description  = jobj["description"].ToString();
                string rating       = jobj["rating"].ToString();


                if (i == 0)
                {
                    ResultSearch0.Content = "RECIPE NAME: " + name + "\nAUTHOR: " + author + "\nINSTRUCTIONS: " + instructions + "\nPREP TIME: " + preptime + "\nPORTIONS: " + portions + "\nDESCRIPTION: " + description + "\nRATING: " + rating;
                }

                if (i == 1)
                {
                    ResultSearch1.Content = "RECIPE NAME: " + name + "\nAUTHOR: " + author + "\nINSTRUCTIONS: " + instructions + "\nPREP TIME: " + preptime + "\nPORTIONS: " + portions + "\nDESCRIPTION: " + description + "\nRATING: " + rating;
                }

                if (i == 2)
                {
                    ResultSearch2.Content = "RECIPE NAME: " + name + "\nAUTHOR: " + author + "\nINSTRUCTIONS: " + instructions + "\nPREP TIME: " + preptime + "\nPORTIONS: " + portions + "\nDESCRIPTION: " + description + "\nRATING: " + rating;
                }

                if (i == 3)
                {
                    ResultSearch3.Content = "RECIPE NAME: " + name + "\nAUTHOR: " + author + "\nINSTRUCTIONS: " + instructions + "\nPREP TIME: " + preptime + "\nPORTIONS: " + portions + "\nDESCRIPTION: " + description + "\nRATING: " + rating;
                }
            }

            if (type == "cookbooks")
            {
                string name   = jobj["name"].ToString();
                string author = jobj["author_name"].ToString();
                string rating = jobj["rating"].ToString();

                if (i == 0)
                {
                    ResultSearch0.Content = "COOKBOOK NAME: " + name + "\nAUTHOR: " + author + "\nRATING: " + rating;
                }

                if (i == 1)
                {
                    ResultSearch1.Content = "COOKBOOK NAME: " + name + "\nAUTHOR: " + author + "\nRATING: " + rating;
                }

                if (i == 2)
                {
                    ResultSearch2.Content = "COOKBOOK NAME: " + name + "\nAUTHOR: " + author + "\nRATING: " + rating;
                }

                if (i == 3)
                {
                    ResultSearch3.Content = "COOKBOOK NAME: " + name + "\nAUTHOR: " + author + "\nRATING: " + rating;
                }
            }
        }
Example #17
0
        public bool FieldsFromJSONObject(JSONObject value, string str)
        {
            this.ask = (double?)value["ask"];
            this.bid = (double?)value["bid"];
            this.askVolume = (double?)value["askVolume"];
            this.bidVolume = (double?)value["bidVolume"];
            this.exemode = new EXECUTION_CODE((long?)value["exemode"]);
            this.high = (double?)value["high"];
            this.low = (double?)value["low"];
            this.symbol = (string)value["symbol"];
            this.timestamp = (long?)value["timestamp"];
            this.level = (long?)value["level"];

            profits = new Dictionary<long?,double?>();
            if (value["profits"]!=null){

                JSONArray jsonarray = (JSONArray)value["profits"];

                foreach(JSONObject i in jsonarray){

                    profits[(long?)i["order"]] =  (double?) i["profit"];
                }

            }

            if ((ask == null) || (bid == null) || (symbol == null) || (timestamp == null) || (exemode == null)) return false;
            return true;
        }
Example #18
0
 void RawJsonCallback(string json)
 {
     Console.WriteLine(json);
     Newtonsoft.Json.Linq.JObject statusjson = new Newtonsoft.Json.Linq.JObject();
     Newtonsoft.Json.Linq.JToken jtoken;
     statusjson = Newtonsoft.Json.Linq.JObject.Parse(json);
     if (statusjson.TryGetValue("text", out jtoken))
     {
         label1.Text += "\n" + (string)statusjson["user"]["name"] + "「" + (string)statusjson["text"] + "」";
     }
     //label1.Text += "\n" + json;
 }
Example #19
0
 public Newtonsoft.Json.Linq.JObject getJSONObject()
 {
     Newtonsoft.Json.Linq.JObject obj = new Newtonsoft.Json.Linq.JObject();
     obj[Fields.Position.ToString()] = Newtonsoft.Json.Linq.JToken.FromObject(Position);
     return obj;
 }
        public dynamic SaveMobileCustomerOrder([FromBody] Newtonsoft.Json.Linq.JObject param)
        {
            dynamic  objParamInfo    = param;
            dynamic  objresponse     = null;
            string   CustomerOrderID = objParamInfo.CustomerOrderID != null ? objParamInfo.CustomerOrderID : "0";
            string   CustomerID      = objParamInfo.CustomerID;
            string   OrderMonth      = objParamInfo.OrderMonth;
            string   remark          = objParamInfo.Remark;
            DateTime Date            = DateTime.Now;

            try
            {
                string customerId = _session.GetString("LoginUserID");
                if (CustomerID == customerId)
                {
                    var sobj = _repositoryWrapper.CustomerOrder.FindByString(CustomerOrderID);
                    if (sobj != null)
                    {
                        sobj.ordermonth      = objParamInfo.OrderMonth;
                        sobj.customerOrderID = objParamInfo.customerOrderID;
                        sobj.customerID      = objParamInfo.CustomerID;
                        sobj.remark          = objParamInfo.Remark;
                        sobj.createuser      = Convert.ToInt32(CustomerID);
                        sobj.userType        = true;
                        sobj.status          = objParamInfo.status;
                        sobj.modifieddate    = System.DateTime.Now;
                        sobj.inactive        = true;
                        _repositoryWrapper.CustomerOrder.Update(sobj);
                        for (int i = 0; i < objParamInfo.data.Count; i++)
                        {
                            string CustomerOrderDetailID = objParamInfo.data[i].ID;
                            var    dobj = _repositoryWrapper.CustomerOrderDetail.FindByString(CustomerOrderDetailID);
                            dobj.customerorderDetailID = CustomerOrderDetailID;
                            dobj.customerOrderID       = CustomerOrderID;
                            dobj.productID             = objParamInfo.data[i].ProductID;
                            dobj.week1_liter           = objParamInfo.data[i].Week1;
                            dobj.week2_liter           = objParamInfo.data[i].Week2;
                            dobj.week3_liter           = objParamInfo.data[i].Week3;
                            dobj.week4_liter           = objParamInfo.data[i].Week4;
                            dobj.total        = objParamInfo.data[i].Total;
                            dobj.remark       = objParamInfo.data[i].Remark;
                            dobj.modifieddate = System.DateTime.Now;
                            dobj.inactive     = true;
                            _repositoryWrapper.CustomerOrderDetail.Update(dobj);
                        }
                    }
                    else
                    {
                        CustomerOrderID = _repositoryWrapper.CustomerOrder.GetCustomerOrderNo();
                        var newobj = new CustomerOrder();
                        newobj.customerOrderID = CustomerOrderID;
                        newobj.customerID      = Convert.ToInt32(CustomerID);
                        newobj.ordermonth      = Convert.ToDateTime(OrderMonth);
                        newobj.status          = 2;
                        sobj.createuser        = Convert.ToInt32(CustomerID);
                        sobj.userType          = true;
                        newobj.modifieddate    = Date;
                        newobj.inactive        = true;
                        newobj.remark          = remark;
                        _repositoryWrapper.CustomerOrder.Create(newobj);

                        for (int i = 0; i < objParamInfo.data.Count; i++)
                        {
                            string CustomerOrderDetailID = _repositoryWrapper.CustomerOrderDetail.GetCustomerOrderDetailNo();
                            var    dobj = new CustomerOrderDetail();
                            dobj.customerorderDetailID = CustomerOrderDetailID;
                            dobj.customerOrderID       = CustomerOrderID;
                            dobj.productID             = objParamInfo.data[i].ProductID;
                            dobj.week1_liter           = objParamInfo.data[i].Week1;
                            dobj.week2_liter           = objParamInfo.data[i].Week2;
                            dobj.week3_liter           = objParamInfo.data[i].Week3;
                            dobj.week4_liter           = objParamInfo.data[i].Week4;
                            dobj.total        = objParamInfo.data[i].Total;
                            dobj.remark       = objParamInfo.data[i].Remark;
                            dobj.modifieddate = System.DateTime.Now;
                            dobj.inactive     = true;
                            _repositoryWrapper.CustomerOrderDetail.Create(dobj);
                        }
                    }
                    objresponse = new { status = 1, message = "Success" };
                }
                else
                {
                    String Message = "Sorry! Please Try Again ";
                    objresponse = new { status = 0, message = Message };
                }
            }
            catch (ValidationException vex)
            {
                //_repositoryWrapper.EventLog.Error("CustomerOrderMobile Controller/ Save CustomerOrderMobile", vex.Message);
                //objresponse = new { data = 0, error = vex.ValidationResult.ErrorMessage };
                objresponse = new { status = 0, message = "Sorry! Please Try Again" };
                Console.WriteLine(vex.Message);
            }

            return(objresponse);
        }
Example #21
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            picBackground.Visible = false;

            showMsg("", 1, Color.Black);

            btnBillSearch.Visible    = false;
            txtAccountNumber.Enabled = false;
            txtRandValue.Enabled     = false;

            _current_acc_number = txtAccountNumber.Text.Replace("-", "").Trim();

            if (_current_acc_number == "")
            {
                showMsg("Please enter a payment reference number.", 1, Color.Firebrick);
                txtAccountNumber.Enabled = true;
                txtRandValue.Enabled     = true;
                txtAccountNumber.Focus();
                return;
            }

            if (txtRandValue.Text == "")
            {
                showMsg("Please enter a payment amount.", 1, Color.Firebrick);
                txtAccountNumber.Enabled = true;
                txtRandValue.Enabled     = true;
                txtRandValue.Focus();
                return;
            }

            string value = txtRandValue.Text.Replace(".", "");

            value = value.Replace(",", "");

            if (Convert.ToInt32(value) > 2000000)
            {
                showMsg("Amount entered is too high.", 1, Color.Firebrick);
                txtAccountNumber.Enabled = true;
                txtRandValue.Enabled     = true;
                txtRandValue.Focus();
                return;
            }

            btnOK.Text    = "...";
            btnOK.Enabled = false;
            btnOK.Refresh();

            btnClose.Enabled = false;
            btnClose.Refresh();

            string htmlResponse = "";

            string process = "0";

            if (step == 1)
            {
                process = "1";
            }

            String convenience_fee = "";

            if (no_fee == 0)
            {
                convenience_fee = "&fee=0";
            }

            Util.showWait("Processing Bill Payment Request.");

            Web WebResponse = new Web(60000);

            if (is_mamamoney)
            {
                htmlResponse = WebResponse.GetURL("/payaccount/payment/do-payment-mamamoney?accno=" + _current_acc_number + "&amt=" + value + "&cc=" + payment_type + "&p=" + process + convenience_fee);
            }
            else
            {
                htmlResponse = WebResponse.GetURL("/payaccount/payment/do-payment?accno=" + _current_acc_number + "&amt=" + value + "&cc=" + payment_type + "&p=" + process + convenience_fee);
            }
            WebResponse = null;

            Util.showWait(false);

            if (htmlResponse.IndexOf("err>") > -1)
            {
                showMsg(htmlResponse.StripErrorTags(), 1, Color.Firebrick);

                btnOK.Enabled    = true;
                btnClose.Enabled = true;

                txtAccountNumber.Enabled = true;
                txtRandValue.Enabled     = true;

                txtAccountNumber.Focus();

                btnOK.Text = "Confirm";
                step       = 0;
            }
            else
            {
                if (step == 0)
                {
                    showMsg(htmlResponse, 0, Color.Black);

                    btnOK.Text    = "Pay Bill";
                    btnOK.Enabled = true;

                    btnOKNoFee.Visible = false;

                    if (globalSettings.pos_user_admin)
                    {
                        if (globalSettings.gen_cashier_billconvenience_admin.Equals("1"))
                        {
                            btnOKNoFee.Visible = true;
                        }
                    }
                    else
                    {
                        if (globalSettings.gen_cashier_billconvenience_cashier.Equals("1"))
                        {
                            btnOKNoFee.Visible = true;
                        }
                    }

                    btnClear.Visible = false;

                    btnClose.Text    = "Cancel";
                    btnClose.Enabled = true;
                    step             = 1;
                }
                else
                {
                    btnOKNoFee.Visible = false;
                    btnOK.Visible      = false;
                    btnClose.Enabled   = true;
                    btnClose.Text      = "Done!";

                    if (globalSettings.gen_cashdr == "1")
                    {
                        //Util.OpenCashDrawer();
                        Util.DoOpenCashDrawer = true;
                    }

                    try
                    {
                        Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse(htmlResponse);

                        finBalance.populateBalanceFromJson(json);

                        string print_data = "";
                        if (!String.IsNullOrEmpty((string)json["print_data"]))
                        {
                            byte[] data = Convert.FromBase64String((string)json["print_data"]);
                            print_data = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
                        }

                        Util.printBillPaymentSlip(print_data);

                        String _value = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0.00}", Decimal.Parse(txtRandValue.Text.Replace(",", ""), System.Globalization.CultureInfo.InvariantCulture));

                        //String _value = value.Substring(0, value.Length - 2) + "." + value.Substring(value.Length - 2, value.Length);

                        if (globalSettings.gen_show_last_sale_login == "1")
                        {
                            try
                            {
                                globalVoucher.setLastSaleDetail("Bill Payment, " + txtAccountNumber.Text, "R " + _value, globalSettings.pos_user_firstname, "", finBalance.dtmd, finBalance.dtmt);
                            }
                            catch
                            {
                                globalVoucher.clearLastSaleDetail();
                            }
                        }

                        //_frmHome.refreshBalanceStatus();
                    }
                    catch (Exception ex)
                    {
                        Util.showMessage(ex.Message, Color.Red);
                    }

                    showMsg(Environment.NewLine + "Payment complete." + Environment.NewLine + Environment.NewLine + "Please check your reprint history if there was a problem printing the confirmation slip.", 1, Color.Black);
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            op = RequestData.Get <string>("op");
            id = RequestData.Get <string>("id");
            switch (RequestActionString)
            {
            case "IsIsbn":
                string          val     = RequestData.Get <string>("Value");
                IList <Product> proEnts = Product.FindAll("from Product where Isbn='" + val + "'");
                if (proEnts.Count > 0)
                {
                    PageState.Add("IsIsbn", true);
                }
                else
                {
                    PageState.Add("IsIsbn", false);
                }
                break;

            case "GetPackageInfo":
                string Isbn = RequestData.Get <string>("Isbn");
                sql = "select * from SHHG_AimExamine..Products where FirstSkinIsbn='" + Isbn + "' and FirstSkinCapacity is not null";
                IList <EasyDictionary> dics = DataHelper.QueryDictList(sql);
                if (dics.Count > 0)
                {
                    PageState.Add("ProductIsbn", dics[0].Get <string>("Isbn").ToUpper());
                    PageState.Add("ProductQuan", dics[0].Get <int>("FirstSkinCapacity"));
                }
                sql  = "select * from SHHG_AimExamine..Products where SecondSkinIsbn='" + Isbn + "' and SecondSkinCapacity is not null";
                dics = DataHelper.QueryDictList(sql);
                if (dics.Count > 0)
                {
                    PageState.Add("ProductIsbn", dics[0].Get <string>("Isbn").ToUpper());
                    PageState.Add("ProductQuan", dics[0].Get <int>("SecondSkinCapacity"));
                }
                break;

            case "ScanSkin":    //判断包装编号是否存在
                string       skinNo = RequestData.Get <string>("SkinNo");
                IList <Skin> sEnts  = Skin.FindAll("from Skin where SkinNo='" + skinNo + "'");
                if (sEnts.Count > 0)    //如果该包装的记录不存在
                {
                    PageState.Add("SkinExist", true);
                }
                else
                {
                    PageState.Add("SkinExist", false);
                }
                break;

            case "ScanCompressor":
                string             seriesNo = RequestData.Get <string>("SeriesNo");
                IList <Compressor> cEnts    = Compressor.FindAll("from Compressor where SeriesNo='" + seriesNo + "'");
                if (cEnts.Count == 0)
                {
                    PageState.Add("CompressorExist", false);
                }
                else
                {
                    PageState.Add("CompressorExist", true);
                }
                break;

            case "InWarehouse":
                InWarehouse    iwEnt      = InWarehouse.TryFind(id);
                IList <string> entStrList = RequestData.GetList <string>("data");
                if (entStrList != null && entStrList.Count > 0)
                {
                    for (int j = 0; j < entStrList.Count; j++)
                    {
                        Newtonsoft.Json.Linq.JObject objL = JsonHelper.GetObject <Newtonsoft.Json.Linq.JObject>(entStrList[j]);
                        if (Convert.ToInt32(objL.Value <string>("ActuallyQuantity")) > 0)    //只有输入了入库数量才会增加实际入库记录
                        {
                            InWarehouseDetailDetail iwddEnt = new InWarehouseDetailDetail(); //新建一个实际入库详细信息
                            if (iwEnt.InWarehouseType == "采购入库")
                            {
                                iwddEnt.InWarehouseDetailId   = objL.Value <string>("Id");
                                iwddEnt.PurchaseOrderDetailId = objL.Value <string>("PurchaseOrderDetailId");
                            }
                            else    //其他入库的情形
                            {
                                iwddEnt.OtherInWarehouseDetailId = objL.Value <string>("Id");
                            }
                            iwddEnt.Quantity  = Convert.ToInt32(objL.Value <string>("ActuallyQuantity"));
                            iwddEnt.ProductId = objL.Value <string>("ProductId");
                            iwddEnt.Remark    = objL.Value <string>("Remark");
                            iwddEnt.DoCreate();

                            StockLog slEnt = new StockLog();    //创建库存变更日志
                            slEnt.InOrOutDetailId = objL.Value <string>("Id");
                            slEnt.InOrOutBillNo   = iwEnt.InWarehouseNo;
                            slEnt.OperateType     = "产品入库";
                            slEnt.WarehouseId     = iwEnt.WarehouseId;
                            slEnt.WarehouseName   = iwEnt.WarehouseName;
                            IList <StockInfo> siEnts = StockInfo.FindAllByProperties(StockInfo.Prop_ProductId, objL.Value <string>("ProductId"), StockInfo.Prop_WarehouseId, iwEnt.WarehouseId);
                            if (siEnts.Count > 0)
                            {
                                slEnt.StockQuantity = siEnts[0].StockQuantity;
                            }
                            slEnt.Quantity  = Convert.ToInt32(objL.Value <string>("ActuallyQuantity"));
                            slEnt.ProductId = objL.Value <string>("ProductId");
                            Product pEnt = Product.Find(objL.Value <string>("ProductId"));
                            slEnt.ProductName = pEnt.Name;
                            slEnt.ProductCode = pEnt.Code;
                            slEnt.ProductIsbn = pEnt.Isbn;
                            slEnt.ProductPcn  = pEnt.Pcn;
                            slEnt.DoCreate();

                            ProcessSkin(objL.Value <string>("SkinArray"), objL.Value <string>("ISBN"), iwEnt.Id);
                            ProcessCompressor(objL.Value <string>("SeriesArray"), objL.Value <string>("ISBN"), iwEnt.Id);
                            processremark(objL.Value <string>("Remark"), pEnt, iwEnt.Id);

                            //如果实际入库数量和未入库的数量相等 则入库状态为已入库
                            if (objL.Value <string>("ActuallyQuantity") == objL.Value <string>("NoIn"))
                            {
                                if (iwEnt.InWarehouseType == "采购入库")
                                {
                                    InWarehouseDetail iwdEnt = InWarehouseDetail.Find(objL.Value <string>("Id"));
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray")))
                                    {
                                        iwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString();
                                    }
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray")))
                                    {
                                        iwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString();
                                    }
                                    iwdEnt.InWarehouseState = "已入库";
                                    iwdEnt.DoUpdate();
                                }
                                else
                                {
                                    OtherInWarehouseDetail oiwdEnt = OtherInWarehouseDetail.Find(objL.Value <string>("Id"));
                                    oiwdEnt.InWarehouseState = "已入库";
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray")))
                                    {
                                        oiwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString();
                                    }
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray")))
                                    {
                                        oiwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString();
                                    }
                                    oiwdEnt.DoUpdate();
                                }
                            }
                            else    //如果未入库的数量不等于现在输入的数量。只更新包装和压缩机序列号集合
                            {
                                if (iwEnt.InWarehouseType == "采购入库")
                                {
                                    InWarehouseDetail iwdEnt = InWarehouseDetail.Find(objL.Value <string>("Id"));
                                    iwdEnt.Remark = objL.Value <string>("Remark");
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray")))
                                    {
                                        iwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString();
                                    }
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray")))
                                    {
                                        iwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString();
                                    }
                                    iwdEnt.DoUpdate();
                                }
                                else
                                {
                                    OtherInWarehouseDetail oiwdEnt = OtherInWarehouseDetail.Find(objL.Value <string>("Id"));
                                    oiwdEnt.Remark = objL.Value <string>("Remark");
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SkinArray")))
                                    {
                                        oiwdEnt.SkinArray = objL.Value <string>("SkinArray").ToString();
                                    }
                                    if (!string.IsNullOrEmpty(objL.Value <string>("SeriesArray")))
                                    {
                                        oiwdEnt.SeriesArray = objL.Value <string>("SeriesArray").ToString();
                                    }
                                    oiwdEnt.DoUpdate();
                                }
                            }
                            //修改库存
                            InStorage(iwddEnt.ProductId, iwddEnt.Quantity.Value, iwEnt.WarehouseId);
                        }
                    }
                }
                ProcessInWarehouse(iwEnt);
                if (iwEnt.InWarehouseType == "采购入库")    //处理采购单和采购单详细
                {
                    ProcessPurchaseOrderAndDetail(iwEnt);
                }
                break;

            default:
                DoSelect();
                break;
            }
        }
Example #23
0
 public TradeRecordsCommand(JSONObject arguments, bool prettyPrint)
     : base(arguments, prettyPrint)
 {
 }
Example #24
0
 public bool FieldsFromJSONObject(JSONObject value, string str)
 {
     this.close_price = (double?)value["close_price"];
     this.close_time = (long?)value["close_time"];
     this.closed = (bool?)value["closed"];
     this.cmd = (long?)value["cmd"];
     this.comment = (string)value["comment"];
     this.commission = (double?)value["commission"];
     this.commission_agent = (double?)value["commission_agent"];
     this.digits = (long?)value["digits"];
     this.expiration = (long?)value["expiration"];
     this.login = (long?)value["login"];
     this.margin_rate = (double?)value["margin_rate"];
     this.open_price = (double?)value["open_price"];
     this.open_time = (long?)value["open_time"];
     this.order = (long?)value["order"];
     this.profit = (double?)value["profit"];
     this.sl = (double?)value["sl"];
     this.spread = (long?)value["spread"];
     this.storage = (double?)value["storage"];
     this.symbol = (string)value["symbol"];
     this.taxes = (double?)value["taxes"];
     this.timestamp = (long?)value["timestamp"];
     this.tp = (double?)value["tp"];
     this.value_date = (long?)value["value_date"];
     this.volume = (double?)value["volume"];
     if ((login == null) || (volume == null) || (cmd == null) || (symbol == null) || (order == null)) return false;
     return true;
 }
Example #25
0
 public Node() : base()
 {
     _ParsedData = new Newtonsoft.Json.Linq.JObject();
 }
 public APIException(int statusCode, Newtonsoft.Json.Linq.JObject errorObject) : this(statusCode, errorObject.ToString())
 {
     this.Type = @"application/json";
 }
 public static void Load()
 {
     Config = Newtonsoft.Json.Linq.JObject.Parse(System.IO.File.ReadAllText("./Config.json"));
 }
Example #28
0
        /** Handle results returned from the document
         */
        public override void _HandleResult(Newtonsoft.Json.Linq.JToken value)
        {
            if (OfficeExtension.Utility._IsNullOrUndefined(value))
            {
                return;
            }
            Newtonsoft.Json.Linq.JObject obj = value as Newtonsoft.Json.Linq.JObject;
            if (obj == null)
            {
                return;
            }

            OfficeExtension.Utility._FixObjectPathIfNecessary(this, obj);
            if (!OfficeExtension.Utility._IsUndefined(obj["Height"]))
            {
                this.LoadedPropertyNames.Add("Height");
                this.m_height = obj["Height"].ToObject <double>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Left"]))
            {
                this.LoadedPropertyNames.Add("Left");
                this.m_left = obj["Left"].ToObject <double>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Name"]))
            {
                this.LoadedPropertyNames.Add("Name");
                this.m_name = obj["Name"].ToObject <string>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Top"]))
            {
                this.LoadedPropertyNames.Add("Top");
                this.m_top = obj["Top"].ToObject <double>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Width"]))
            {
                this.LoadedPropertyNames.Add("Width");
                this.m_width = obj["Width"].ToObject <double>();
            }

            if (!OfficeExtension.Utility._IsUndefined(obj["Axes"]))
            {
                this.Axes._HandleResult(obj["Axes"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["DataLabels"]))
            {
                this.DataLabels._HandleResult(obj["DataLabels"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["Format"]))
            {
                this.Format._HandleResult(obj["Format"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["Legend"]))
            {
                this.Legend._HandleResult(obj["Legend"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["Series"]))
            {
                this.Series._HandleResult(obj["Series"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["Title"]))
            {
                this.Title._HandleResult(obj["Title"]);
            }
            if (!OfficeExtension.Utility._IsUndefined(obj["Worksheet"]))
            {
                this.Worksheet._HandleResult(obj["Worksheet"]);
            }
        }
        public TaskStatus Handle(IHttpProxy httpHandler)
        {
            httpHandler.ResponseContentType = "application/json";
            var forms = httpHandler.Form.ToObject <SortedDictionary <string, string> >();

            try
            {
                if (forms.Count > 0)
                {
                    //验证sign
                    var config = new Config(ResturantFactory.ResturantListener.OnGetPlatformConfigXml(ResturantPlatformType.Meituan));
                    if (forms["sign"] != MeituanHelper.Sign(forms, config.SignKey))
                    {
                        throw new Exception("签名验证失败");
                    }

                    Newtonsoft.Json.Linq.JObject orderJSONObj = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(forms["orderRefund"]);
                    string notifyType = orderJSONObj.Value <string>("notifyType");

                    /*
                     * apply	发起退款
                     * agree	确认退款
                     * reject	驳回退款
                     * cancelRefund	用户取消退款申请
                     * cancelRefundComplaint	取消退款申诉
                     */
                    OrderRefundInfo info = new OrderRefundInfo();
                    info.OrderID    = orderJSONObj.Value <string>("orderId");
                    info.ErpStoreID = Convert.ToInt32(forms["ePoiId"]);
                    info.Reason     = orderJSONObj.Value <string>("reason");

                    if (ResturantFactory.ResturantListener != null)
                    {
                        new Thread(() =>
                        {
                            try
                            {
                                if (notifyType == "apply")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefund(ResturantPlatformType.Meituan, info);
                                }
                                else if (notifyType == "agree")
                                {
                                    ResturantFactory.ResturantListener.OnOrderRefundCompleted(ResturantPlatformType.Meituan, info);
                                }
                                else if (notifyType == "cancelRefund" || notifyType == "cancelRefundComplaint")
                                {
                                    ResturantFactory.ResturantListener.OnCancelOrderRefund(ResturantPlatformType.Meituan, info);
                                }
                            }
                            catch { }
                        }).Start();
                    }
                }
            }
            catch (Exception ex)
            {
                using (Log log = new Log("美团OrderRefundCallback解析错误"))
                {
                    log.Log(ex.ToString());
                }
            }
            httpHandler.ResponseWrite("{\"data\":\"OK\"}");

            return(TaskStatus.Completed);
        }
Example #30
0
        static void Main(string[] args)
        {
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/hal+json"));


            var response = client.GetAsync(api_url + "/breweries").Result;

            var data = response.Content.ReadAsStringAsync().Result;

            Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(data);
            //mergem la vectorul cu berarii
            Newtonsoft.Json.Linq.JToken berarii_links_array = obj.First.Last.Last.First;

            // extragem fiecare link de berarie si il adaugam in lista
            foreach (var item in berarii_links_array)
            {
                berarii_links.Add(item.First.First.ToString());
            }


            //MENIU
            do
            {
                Console.WriteLine("\nMENIUL PRINCIPAL:\n");
                Console.WriteLine("Pentru a vizualiza berariile apasati tasta 1");
                Console.WriteLine("Pentru a vizualiza stilurile de bere apasati tasta 2");
                Console.WriteLine("Pentru a adauga o bere noua apasati tasta 3");
                Console.WriteLine("Pentru a iesi apasati tasta E");
                Console.WriteLine("\n Alegeti optiunea dorita!");
                opt = Console.ReadLine();
                switch (opt)
                {
                case "1":
                    berarii();
                    meniu_berarie();
                    break;

                case "2":
                    stiluri_bere();
                    meniu_stiluri();
                    break;

                case "3":
                    Console.WriteLine("Introduceti Numele berii pe care doriti sa o adaugati:");
                    string bere = "";
                    bere = Console.ReadLine();
                    using (var client = new HttpClient())
                    {
                        Bere b = new Bere {
                            Name = bere
                        };
                        client.BaseAddress = new Uri("http://datc-rest.azurewebsites.net/beers");
                        response           = client.PostAsJsonAsync(client.BaseAddress, b).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            Console.WriteLine("Success");
                        }
                        else
                        {
                            Console.WriteLine("Error");
                        }
                        Console.ReadKey();
                    }
                    break;

                case "e":
                    break;

                default:
                    Console.WriteLine("Alegeti alta optiune, cea introdusa de dumneavoastra nu exista!!!!!!!!!\n");
                    Console.ReadKey();
                    break;
                }
                Console.Clear();
            } while (!opt.Equals("e"));


            Console.ReadKey();
        }
        public string Tree1()
        {
            int    showType   = Request.Querys("showtype").ToString().ToInt(0);//显示类型 0组织架构 1角色组
            string rootId     = Request.Querys("rootid");
            string searchWord = Request.Querys("searchword");
            bool   showUser   = !"0".Equals(Request.Querys("shouser"));

            Business.Organize     organize     = new Business.Organize();
            Business.User         user         = new Business.User();
            Business.WorkGroup    workGroup    = new Business.WorkGroup();
            Business.OrganizeUser organizeUser = new Business.OrganizeUser();
            var  organizeUserList = organizeUser.GetAll();
            Guid orgRootId        = organize.GetRootId();

            Newtonsoft.Json.Linq.JArray jArray = new Newtonsoft.Json.Linq.JArray();

            #region 搜索
            if (!searchWord.IsNullOrWhiteSpace())
            {
                Guid parentId = Guid.NewGuid();
                if (1 == showType)//搜索工作组
                {
                    var workGroups = workGroup.GetAll().FindAll(p => p.Name.ContainsIgnoreCase(searchWord.Trim()));
                    Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                    {
                        { "id", parentId },
                        { "parentID", Guid.Empty },
                        { "title", "查询“" + searchWord + "”的结果" },
                        { "ico", "fa-search" },
                        { "link", "" },
                        { "type", 1 },
                        { "hasChilds", workGroups.Count }
                    };
                    jArray.Add(jObject);
                    Newtonsoft.Json.Linq.JArray jArray1 = new Newtonsoft.Json.Linq.JArray();
                    foreach (var group in workGroups)
                    {
                        Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", group.Id },
                            { "parentID", parentId },
                            { "title", group.Name },
                            { "ico", "fa-slideshare" },
                            { "link", "" },
                            { "type", 5 },
                            { "hasChilds", 0 }
                        };
                        jArray1.Add(jObject1);
                    }
                    jObject.Add("childs", jArray1);
                }
                else //搜索组织和人员
                {
                    var organizes = organize.GetAll().FindAll(p => p.Name.ContainsIgnoreCase(searchWord.Trim()));
                    var users     = user.GetAll().FindAll(p => p.Name.ContainsIgnoreCase(searchWord.Trim()));
                    Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                    {
                        { "id", parentId },
                        { "parentID", Guid.Empty },
                        { "title", "查询“" + searchWord + "”的结果" },
                        { "ico", "fa-search" },
                        { "link", "" },
                        { "type", 1 },
                        { "hasChilds", organizes.Count + users.Count }
                    };
                    jArray.Add(jObject);
                    Newtonsoft.Json.Linq.JArray jArray1 = new Newtonsoft.Json.Linq.JArray();
                    foreach (var organizeModel in organizes)
                    {
                        Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", organizeModel.Id },
                            { "parentID", parentId },
                            { "title", organizeModel.Name },
                            { "ico", "" },
                            { "link", "" },
                            { "type", organizeModel.Type },
                            { "hasChilds", organize.HasChilds(organizeModel.Id) ? 1 : 0 }
                        };
                        jArray1.Add(jObject1);
                    }
                    foreach (var userModel in users)
                    {
                        Newtonsoft.Json.Linq.JObject jObject1 = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", userModel.Id },
                            { "parentID", parentId },
                            { "title", userModel.Name },
                            { "ico", "fa-user" },
                            { "link", "" },
                            { "userID", userModel.Id },
                            { "type", 4 },
                            { "hasChilds", 0 }
                        };
                        jArray1.Add(jObject1);
                    }
                    jObject.Add("childs", jArray1);
                }
                return(jArray.ToString());
            }
            #endregion

            #region 显示角色组
            if (1 == showType)
            {
                var workgroups = workGroup.GetAll();
                foreach (var workgroupModel in workgroups)
                {
                    Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                    {
                        { "id", workgroupModel.Id },
                        { "parentID", Guid.Empty },
                        { "title", workgroupModel.Name },
                        { "ico", "fa-slideshare" },
                        { "link", "" },
                        { "type", 5 },
                        { "hasChilds", 0 }
                    };
                    jArray.Add(jObject);
                }
                return(jArray.ToString());
            }
            #endregion

            if (rootId.IsNullOrWhiteSpace())
            {
                rootId = orgRootId.ToString();
            }
            #region 添加根节点
            string[] rootIdArray = rootId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string root in rootIdArray)
            {
                if (root.IsGuid(out Guid guid))//组织机构
                {
                    var organizeModel = organize.Get(guid);
                    if (null != organizeModel)
                    {
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", organizeModel.Id },
                            { "parentID", organizeModel.ParentId },
                            { "title", organizeModel.Name },
                            { "ico", organizeModel.Id == orgRootId ? "fa-sitemap" : "" },
                            { "link", "" },
                            { "type", organizeModel.Type },
                            { "hasChilds", organize.HasChilds(organizeModel.Id) ? 1 : showUser?organize.HasUsers(organizeModel.Id) ? 1 : 0 : 0 }
                        };
                        jArray.Add(jObject);
                    }
                }
                else if (root.StartsWith(Business.Organize.PREFIX_USER))//人员
                {
                    var userModel = user.Get(root.RemoveUserPrefix().ToGuid());
                    if (null != userModel)
                    {
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", userModel.Id },
                            { "parentID", Guid.Empty },
                            { "title", userModel.Name },
                            { "ico", "fa-user" },
                            { "link", "" },
                            { "type", 4 },
                            { "hasChilds", 0 }
                        };
                        jArray.Add(jObject);
                    }
                }
                else if (root.StartsWith(Business.Organize.PREFIX_RELATION))//兼职人员
                {
                    var organizeUserModel = organizeUser.Get(root.RemoveUserRelationPrefix().ToGuid());
                    if (null != organizeUserModel)
                    {
                        var userModel = user.Get(organizeUserModel.UserId);
                        if (null != userModel)
                        {
                            Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                            {
                                { "id", organizeUserModel.Id },
                                { "parentID", Guid.Empty },
                                { "title", userModel.Name + "<span style='color:#666;'>[兼任]</span>" },
                                { "ico", "fa-user" },
                                { "link", "" },
                                { "type", 6 },
                                { "userID", userModel.Id },
                                { "hasChilds", 0 }
                            };
                            jArray.Add(jObject);
                        }
                    }
                }
                else if (root.StartsWith(Business.Organize.PREFIX_WORKGROUP))//工作组
                {
                    var workgroupModel = workGroup.Get(root.RemoveWorkGroupPrefix().ToGuid());
                    if (null != workgroupModel)
                    {
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", workgroupModel.Id },
                            { "parentID", Guid.Empty },
                            { "title", workgroupModel.Name },
                            { "ico", "fa-slideshare" },
                            { "link", "" },
                            { "type", 5 },
                            { "hasChilds", workGroup.GetAllUsers(workgroupModel.Id).Count }
                        };
                        jArray.Add(jObject);
                    }
                }
            }
            #endregion

            #region 只有一个根时显示二级
            if (rootIdArray.Length == 1)
            {
                string rootIdString = rootIdArray[0];
                if (rootIdString.IsGuid(out Guid guid))
                {
                    var jObject0 = (Newtonsoft.Json.Linq.JObject)jArray[0];
                    Newtonsoft.Json.Linq.JArray jArray0 = new Newtonsoft.Json.Linq.JArray();
                    var childs        = organize.GetChilds(guid);
                    var organizeUser1 = organizeUserList.FindAll(p => p.OrganizeId == guid);
                    foreach (var child in childs)
                    {
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", child.Id },
                            { "parentID", child.ParentId },
                            { "title", child.Name },
                            { "ico", "" },
                            { "link", "" },
                            { "type", child.Type },
                            { "hasChilds", organize.HasChilds(child.Id) ? 1 : showUser?organize.HasUsers(child.Id) ? 1 : 0 : 0 }
                        };
                        jArray0.Add(jObject);
                    }
                    if (showUser)
                    {
                        var users = organize.GetUsers(guid);
                        foreach (var userModel in users)
                        {
                            var  organizeUserModel1 = organizeUser1.Find(p => p.UserId == userModel.Id);
                            bool isPartTime         = organizeUserModel1.IsMain != 1;//是否是兼职
                            Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                            {
                                { "id", isPartTime ? organizeUserModel1.Id : userModel.Id },
                                { "parentID", guid },
                                { "title", userModel.Name + (isPartTime ? "<span style='color:#666;'>[兼任]</span>" : "") },
                                { "ico", "fa-user" },
                                { "link", "" },
                                { "userID", userModel.Id },
                                { "type", isPartTime ? 6 : 4 },
                                { "hasChilds", 0 }
                            };
                            jArray0.Add(jObject);
                        }
                    }
                    jObject0.Add("childs", jArray0);
                }
                else if (rootIdString.StartsWith(Business.Organize.PREFIX_WORKGROUP))
                {
                    var jObject0 = (Newtonsoft.Json.Linq.JObject)jArray[0];
                    Newtonsoft.Json.Linq.JArray jArray0 = new Newtonsoft.Json.Linq.JArray();
                    var users = workGroup.GetAllUsers(rootIdString.RemoveWorkGroupPrefix().ToGuid());
                    foreach (var userModel in users)
                    {
                        Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject()
                        {
                            { "id", userModel.Id },
                            { "parentID", rootIdString.RemoveWorkGroupPrefix() },
                            { "title", userModel.Name },
                            { "ico", "fa-user" },
                            { "link", "" },
                            { "type", 4 },
                            { "hasChilds", 0 }
                        };
                        jArray0.Add(jObject);
                    }
                    jObject0.Add("childs", jArray0);
                }
            }
            #endregion

            return(jArray.ToString());
        }
Example #32
0
        private Newtonsoft.Json.Linq.JObject parseStruct(OEIShared.IO.GFF.GFFStruct gffStruct)
        {
            var j = new Newtonsoft.Json.Linq.JObject();

            foreach (OEIShared.IO.GFF.GFFField field in gffStruct.Fields.Values)
                j.Add(field.StringLabel, parseField(field));

            return j;
        }
        private VirtualMachine SetAzureVMDiagnosticsExtensionC(VirtualMachine vm, VirtualMachineInstanceView vmStatus, string storageAccountName, string storageAccountKey)
        {
            System.Xml.XmlDocument xpublicConfig = null;

            var extensionName = AEMExtensionConstants.WADExtensionDefaultName[this.OSType];

            var    extTemp    = AEMHelper.GetAEMExtension(vm, this.OSType);
            object publicConf = null;

            if (extTemp != null)
            {
                publicConf    = extTemp.Settings;
                extensionName = extTemp.Name;
            }

            if (publicConf != null)
            {
                var jpublicConf = publicConf as Newtonsoft.Json.Linq.JObject;
                if (jpublicConf == null)
                {
                    throw new ArgumentException();
                }

                var base64 = jpublicConf["xmlCfg"] as Newtonsoft.Json.Linq.JValue;
                if (base64 == null)
                {
                    throw new ArgumentException();
                }

                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString())));

                if (xDoc.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters") != null)
                {
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration").Attributes["overallQuotaInMB"].Value = "4096";
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").Attributes["scheduledTransferPeriod"].Value = "PT1M";

                    xpublicConfig = xDoc;
                }
            }

            if (xpublicConfig == null)
            {
                xpublicConfig = new System.Xml.XmlDocument();
                xpublicConfig.LoadXml(AEMExtensionConstants.WADConfigXML);
            }

            foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[OSType])
            {
                var currentCounter = xpublicConfig.
                                     SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']");
                if (currentCounter == null)
                {
                    var node = xpublicConfig.CreateElement("PerformanceCounterConfiguration");
                    xpublicConfig.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").AppendChild(node);
                    node.SetAttribute("counterSpecifier", perfCounter.counterSpecifier);
                    node.SetAttribute("sampleRate", perfCounter.sampleRate);
                }
            }

            var endpoint = this._Helper.GetCoreEndpoint(storageAccountName);

            endpoint = "https://" + endpoint;

            Newtonsoft.Json.Linq.JObject jPublicConfig = new Newtonsoft.Json.Linq.JObject();
            jPublicConfig.Add("xmlCfg", new Newtonsoft.Json.Linq.JValue(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(xpublicConfig.InnerXml))));

            Newtonsoft.Json.Linq.JObject jPrivateConfig = new Newtonsoft.Json.Linq.JObject();
            jPrivateConfig.Add("storageAccountName", new Newtonsoft.Json.Linq.JValue(storageAccountName));
            jPrivateConfig.Add("storageAccountKey", new Newtonsoft.Json.Linq.JValue(storageAccountKey));
            jPrivateConfig.Add("storageAccountEndPoint", new Newtonsoft.Json.Linq.JValue(endpoint));

            WriteVerbose("Installing WAD extension");

            Version wadVersion = this._Helper.GetExtensionVersion(vm, vmStatus, OSType,
                                                                  AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[this.OSType]);

            VirtualMachineExtension vmExtParameters = new VirtualMachineExtension();

            vmExtParameters.Publisher = AEMExtensionConstants.WADExtensionPublisher[this.OSType];
            vmExtParameters.VirtualMachineExtensionType = AEMExtensionConstants.WADExtensionType[this.OSType];
            vmExtParameters.TypeHandlerVersion          = wadVersion.ToString(2);
            vmExtParameters.Settings                = jPublicConfig;
            vmExtParameters.ProtectedSettings       = jPrivateConfig;
            vmExtParameters.Location                = vm.Location;
            vmExtParameters.AutoUpgradeMinorVersion = true;
            vmExtParameters.ForceUpdateTag          = DateTime.Now.Ticks.ToString();

            this.VirtualMachineExtensionClient.CreateOrUpdate(ResourceGroupName, vm.Name, extensionName, vmExtParameters);

            return(this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(ResourceGroupName, vm.Name));
        }
Example #34
0
        private string GetValidMask(CustomFieldType customFieldType, String mask)
        {
            var resultMask = new Newtonsoft.Json.Linq.JObject();
            if (String.IsNullOrEmpty(mask) ||
                (customFieldType != CustomFieldType.TextField && customFieldType != CustomFieldType.TextArea && customFieldType != CustomFieldType.SelectBox))
            {
                return String.Empty;
            }

            try
            {
                var maskObj = Newtonsoft.Json.Linq.JToken.Parse(mask);
                if (customFieldType == CustomFieldType.TextField)
                {
                    var size = maskObj.Value<int>("size");
                    if (size == 0)
                    {
                        resultMask.Add("size", 1);
                    }
                    else if (size > Global.MaxCustomFieldSize)
                    {
                        resultMask.Add("size", Global.MaxCustomFieldSize);
                    }
                    else
                    {
                        resultMask.Add("size", size);
                    }
                }
                if (customFieldType == CustomFieldType.TextArea)
                {
                    var rows = maskObj.Value<int>("rows");
                    var cols = maskObj.Value<int>("cols");

                    if (rows == 0)
                    {
                        resultMask.Add("rows", 1);
                    }
                    else if (rows > Global.MaxCustomFieldRows)
                    {
                        resultMask.Add("rows", Global.MaxCustomFieldRows);
                    }
                    else
                    {
                        resultMask.Add("rows", rows);
                    }

                    if (cols == 0)
                    {
                        resultMask.Add("cols", 1);
                    }
                    else if (cols > Global.MaxCustomFieldCols)
                    {
                        resultMask.Add("cols", Global.MaxCustomFieldCols);
                    }
                    else
                    {
                        resultMask.Add("cols", cols);
                    }
                }
                if (customFieldType == CustomFieldType.SelectBox)
                {
                    if (maskObj is Newtonsoft.Json.Linq.JArray)
                    {
                        return mask;
                    }
                    else
                    {
                        throw new ArgumentException("Mask is not valid");
                    }
                }
            }
            catch (Exception ex)
            {
                if (customFieldType == CustomFieldType.TextField)
                {
                    resultMask.Add("size", Global.DefaultCustomFieldSize);
                }
                if (customFieldType == CustomFieldType.TextArea)
                {
                    resultMask.Add("rows", Global.DefaultCustomFieldRows);
                    resultMask.Add("cols", Global.DefaultCustomFieldCols);
                }
                if (customFieldType == CustomFieldType.SelectBox)
                {
                    throw ex;
                }
            }
            return JsonConvert.SerializeObject(resultMask);
        }
        /// <summary>
        /// Call the Foursquare Location api to return venues in the area.
        /// https://developer.foursquare.com/docs/api
        /// </summary>
        /// <param name="searchQuery">the type of venue to search for</param>
        /// <returns></returns>
        public string GetVenuesInfo(string searchQuery)
        {
            string venuesResponse = "";

            try {
                // the latitude
                var latituteLongitude = MistyApiInfo.FoursquareLocationLatLon;
                var venuesUrl         = MistyApiInfo.FoursquareBaseUrl + "/venues/explore?client_id=" + MistyApiInfo.FoursquareClientId + "&client_secret=" + MistyApiInfo.FoursquareClientSecret + "&v=20180323&limit=" + numberOfResults + "&ll=" + latituteLongitude + "&query=" + searchQuery;
                _misty.SkillLogger.LogVerbose($"MistyFoursquareApi : IN GetVenueInfo - {venuesUrl}");
                // Call the Foursquares API
                var response = GetResponse(venuesUrl);
                //_misty.SkillLogger.Log($"MistyFoursquareApi : IN GetVenueInfo - response json: {response}");
                Newtonsoft.Json.Linq.JObject jsonResp = Newtonsoft.Json.Linq.JObject.Parse(response);
                // { "meta":{
                //      "code":200,
                //      "requestId":"5e49807b006dce001b64ed2f"
                //      },
                //  "response":{
                //      "suggestedFilters":{
                //          "header":"Tap to show:",
                //          "filters":[{"name":"Open now","key":"openNow"}]},"suggestedRadius":5873,"headerLocation":"Port Coquitlam","headerFullLocation":"Port Coquitlam","headerLocationGranularity":"city",
                //      "query":"restaurants",
                //      "totalResults":118,
                //      "suggestedBounds":{"ne":{"lat":49.27830514616493,"lng":-122.73593470988092},"sw":{"lat":49.24079193053648,"lng":-122.79941234714852}},
                //      "groups":[{"type":"Recommended Places","name":"recommended",
                //         "items":[
                //         { "reasons":{"count":0,
                //            "items":[{
                //              "summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},
                //            "venue":{
                //                  "id":"4e5e9f91a809fd79d29b7ed6",
                //                  "name":"Santa Rosa","contact":{},
                //                  "location":{"address":"121-1585 Broadway St",
                //                  "crossStreet":"at Mary Hill Bypass",
                //                  "lat":49.242497076701405,"lng":-122.7645993232727,
                //                  "labeledLatLngs":[{
                //                      "label":"display",
                //                      "lat":49.242497076701405,"lng":-122.7645993232727}],
                //                  "distance":1017,
                //                  "postalCode":"V3C 2M7","cc":"CA",
                //                  "city":"Port Coquitlam",
                //                  "state":"BC",
                //                  "country":"Canada",
                //                  "formattedAddress":[
                //                      "121-1585 Broadway St (at Mary Hill Bypass)","Port Coquitlam BC V3C 2M7","Canada"]},
                //              "categories":[{"id":"4bf58dd8d48988d1c1941735","name":"Mexican Restaurant","pluralName":"Mexican Restaurants","shortName":"Mexican","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/mexican_","suffix":".png"},"primary":true}],"verified":false,"stats":{"tipCount":0,"usersCount":0,"checkinsCount":0,"visitsCount":0},"beenHere":{"count":0,"lastCheckinExpiredAt":0,"marked":false,"unconfirmedCount":0},"photos":{"count":0,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"referralId":"e-0-4e5e9f91a809fd79d29b7ed6-0"},
                //        { "reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"4bca6077937ca59322d7a792","name":"Pallas Athena","contact":{},"location":{"address":"101 - 1250 Dominion Ave","crossStreet":"at Ottawa St","lat":49.25836705904778,"lng":-122.74873434597104,"labeledLatLngs":[{"label":"display","lat":49.25836705904778,"lng":-122.74873434597104}],"distance":1502,"postalCode":"V3B 8G7","cc":"CA","city":"Port Coquitlam","state":"BC","country":"Canada","formattedAddress":["101 - 1250 Dominion Ave (at Ottawa St)","Port Coquitlam BC V3B 8G7","Canada"]},"categories":[{"id":"4bf58dd8d48988d10e941735","name":"Greek Restaurant","pluralName":"Greek Restaurants","shortName":"Greek","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/greek_","suffix":".png"},"primary":true}],"verified":false,"stats":{"tipCount":0,"usersCount":0,"checkinsCount":0,"visitsCount":0},"beenHere":{"count":0,"lastCheckinExpiredAt":0,"marked":false,"unconfirmedCount":0},"photos":{"count":0,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"referralId":"e-0-4bca6077937ca59322d7a792-1"},
                //        { "reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"4c031cc59a7920a1b288cf79","name":"Dinakis Mediterranean Grill","contact":{},"location":{"address":"101-2020 Oxford Connector","lat":49.26532448553105,"lng":-122.77246835948404,"labeledLatLngs":[{"label":"display","lat":49.26532448553105,"lng":-122.77246835948404}],"distance":1592,"postalCode":"V3C 0A4","cc":"CA","city":"Port Coquitlam","state":"BC","country":"Canada","formattedAddress":["101-2020 Oxford Connector","Port Coquitlam BC V3C 0A4","Canada"]},"categories":[{"id":"4bf58dd8d48988d1c0941735","name":"Mediterranean Restaurant","pluralName":"Mediterranean Restaurants","shortName":"Mediterranean","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/mediterranean_","suffix":".png"},"primary":true}],"verified":false,"stats":{"tipCount":0,"usersCount":0,"checkinsCount":0,"visitsCount":0},"beenHere":{"count":0,"lastCheckinExpiredAt":0,"marked":false,"unconfirmedCount":0},"photos":{"count":0,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"referralId":"e-0-4c031cc59a7920a1b288cf79-2"},
                //        { "reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"5010a60be4b0d8233cd74a26","name":"Sushi K Kamizato 神里","contact":{},"location":{"address":"2105 - 2850 Shaughnessy St","crossStreet":"at Lougheed Hwy","lat":49.26530381698295,"lng":-122.7775546404203,"labeledLatLngs":[{"label":"display","lat":49.26530381698295,"lng":-122.7775546404203}],"distance":1726,"postalCode":"V3C 0A4","cc":"CA","neighborhood":"Shaughnessy Station","city":"Port Coquitlam","state":"BC","country":"Canada","formattedAddress":["2105 - 2850 Shaughnessy St (at Lougheed Hwy)","Port Coquitlam BC V3C 0A4","Canada"]}
                string venuesText   = "";
                string totalResults = (string)jsonResp["response"]["totalResults"];
                if (totalResults != "0")
                {
                    venuesText = "A few restaurants in the area include ";
                    for (int i = 0; i < numberOfResults; i++)
                    {
                        if (i > 0)
                        {
                            venuesText += ". and ";
                        }
                        venuesText += (string)jsonResp["response"]["groups"][0]["items"][i]["venue"]["name"];
                    }
                }
                else
                {
                    venuesText = "Sorry I could not find any results for " + searchQuery;
                }
                _misty.SkillLogger.LogVerbose($"MistyFoursquareApi : IN GetVenueInfo() - venuesText: {venuesText}");
                return(venuesText);
            }
            catch (Exception ex)
            {
                _misty.SkillLogger.Log($"Misty.Services: IN GetVenueInfo() => Exception", ex);
            }
            return(venuesResponse);
        }
Example #36
0
        public void UpdateWorkClass(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            string           strID        = Data["CLASS_ID"].ToString().Trim();
            string           newClassName = Data["NEW_CLASS_NAME"].ToString().Trim();
            string           startTime    = Data["START_TIME"].ToString().Trim();
            string           endTime      = Data["END_TIME"].ToString().Trim();
            OleExec          oleDB        = null;
            T_C_WORK_CLASS   workClass    = null;
            Row_C_WORK_CLASS workClassRow = null;

            if (string.IsNullOrEmpty(strID))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("CLASS ID");
                StationReturn.Data = "";
                return;
            }
            if (string.IsNullOrEmpty(startTime))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("START TIME");
                StationReturn.Data = "";
                return;
            }
            if (string.IsNullOrEmpty(endTime))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("END TIME");
                StationReturn.Data = "";
                return;
            }
            try
            {
                oleDB        = this.DBPools["SFCDB"].Borrow();
                workClass    = new T_C_WORK_CLASS(oleDB, DBTYPE);
                workClassRow = (Row_C_WORK_CLASS)workClass.NewRow();
                if (!workClass.WorkClassIsExistByID(strID, oleDB))
                {
                    StationReturn.Status      = StationReturnStatusValue.Fail;
                    StationReturn.MessageCode = "MES00000007";
                    StationReturn.Data        = "";
                }
                else if (!string.IsNullOrEmpty(newClassName) && workClass.WorkClassIsExistByName(newClassName, oleDB))
                {
                    StationReturn.Status      = StationReturnStatusValue.Fail;
                    StationReturn.MessageCode = "MES00000008";
                    StationReturn.MessagePara.Add(newClassName);
                    StationReturn.Data = "";
                }
                else
                {
                    workClassRow = (Row_C_WORK_CLASS)workClass.GetObjByID(strID, oleDB, DBTYPE);
                    if (!string.IsNullOrEmpty(newClassName))
                    {
                        workClassRow.NAME = newClassName;
                    }
                    if (!string.IsNullOrEmpty(startTime))
                    {
                        workClassRow.START_TIME = startTime;
                    }
                    if (!string.IsNullOrEmpty(endTime))
                    {
                        workClassRow.END_TIME = endTime;
                    }
                    oleDB.ThrowSqlExeception = true;
                    oleDB.ExecSQL(workClassRow.GetUpdateString(DBTYPE));
                    StationReturn.Status      = StationReturnStatusValue.Pass;
                    StationReturn.MessageCode = "MES00000003";
                    StationReturn.Data        = "";
                }
                this.DBPools["SFCDB"].Return(oleDB);
            }
            catch (Exception exception)
            {
                this.DBPools["SFCDB"].Return(oleDB);
                throw exception;
            }
        }
Example #37
0
 public TradeTransactionStatusCommand(JSONObject arguments, bool prettyPrint)
     : base(arguments, prettyPrint)
 {
 }
Example #38
0
 public TradesCommand(JSONObject arguments, bool prettyPrint)
     : base(arguments, prettyPrint)
 {
 }
        private void AddSuperchargerState(Newtonsoft.Json.Linq.JObject suc, ArrayList send)
        {
            int     sucID    = int.MinValue;
            bool    SuCfound = GetSuperchargerByName(suc["name"].ToString(), out sucID);
            dynamic location = suc["location"];
            double  lat      = location["lat"];
            double  lng      = location["long"];

            if (!SuCfound)
            {
                // add new entry to supercharger list in DB

                sucID = AddNewSupercharger(suc["name"].ToString(), lat, lng);
            }

            if (suc.ContainsKey("available_stalls") &&
                suc.ContainsKey("total_stalls") &&
                suc.ContainsKey("site_closed") &&
                bool.TryParse(suc["site_closed"].ToString(), out bool site_closed) &&
                site_closed == false)
            {
                Tools.DebugLog($"SuC: <{suc["name"]}> <{suc["available_stalls"]}> <{suc["total_stalls"]}>");
                if (int.TryParse(suc["available_stalls"].ToString(), out int available_stalls) &&
                    int.TryParse(suc["total_stalls"].ToString(), out int total_stalls))
                {
                    if (total_stalls > 0)
                    {
                        if (!ContainsSupercharger(send, suc["name"].ToString()))
                        {
                            Dictionary <string, object> sendKV = new Dictionary <string, object>();
                            send.Add(sendKV);
                            sendKV.Add("n", suc["name"]);
                            sendKV.Add("lat", lat);
                            sendKV.Add("lng", lng);
                            sendKV.Add("ts", DateTime.UtcNow.ToString("s", Tools.ciEnUS));
                            sendKV.Add("a", available_stalls);
                            sendKV.Add("t", total_stalls);

                            using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring))
                            {
                                con.Open();
                                // find internal ID of supercharger by name
                                using (MySqlCommand cmd = new MySqlCommand(@"
INSERT
    superchargerstate(
        nameid,
        ts,
        available_stalls,
        total_stalls
    )
VALUES(
    @nameid,
    @ts,
    @available_stalls,
    @total_stalls
)", con))
                                {
                                    cmd.Parameters.AddWithValue("@nameid", sucID);
                                    cmd.Parameters.AddWithValue("@ts", DateTime.Now);
                                    cmd.Parameters.AddWithValue("@available_stalls", available_stalls);
                                    cmd.Parameters.AddWithValue("@total_stalls", total_stalls);
                                    SQLTracer.TraceNQ(cmd);
                                }
                                con.Close();
                            }
                        }
                    }
                    else
                    {
                        // TODO how do we handle total_stalls == 0 ?
                    }
                }
            }
            else if (suc.ContainsKey("site_closed") &&
                     bool.TryParse(suc["site_closed"].ToString(), out site_closed) &&
                     site_closed)
            {
                Tools.DebugLog($"SuC: <{suc["name"]}> site_closed");
                if (!ContainsSupercharger(send, suc["name"].ToString()))
                {
                    Dictionary <string, object> sendKV = new Dictionary <string, object>();
                    send.Add(sendKV);
                    sendKV.Add("n", suc["name"]);
                    sendKV.Add("lat", lat);
                    sendKV.Add("lng", lng);
                    sendKV.Add("ts", DateTime.UtcNow.ToString("s", Tools.ciEnUS));
                    sendKV.Add("a", -1);
                    sendKV.Add("t", -1);
                    using (MySqlConnection con = new MySqlConnection(DBHelper.DBConnectionstring))
                    {
                        con.Open();
                        // find internal ID of supercharger by name
                        using (MySqlCommand cmd = new MySqlCommand("INSERT superchargerstate (nameid, ts, available_stalls, total_stalls) values (@nameid, @ts, @available_stalls, @total_stalls) ", con))
                        {
                            cmd.Parameters.AddWithValue("@nameid", sucID);
                            cmd.Parameters.AddWithValue("@ts", DateTime.Now);
                            cmd.Parameters.AddWithValue("@available_stalls", -1);
                            cmd.Parameters.AddWithValue("@total_stalls", -1);
                            SQLTracer.TraceNQ(cmd);
                        }
                        con.Close();
                    }
                }
            }
            else if (suc.ContainsKey("site_closed") &&
                     bool.TryParse(suc["site_closed"].ToString(), out site_closed) &&
                     !site_closed)
            {
                Tools.DebugLog($"SuC: <{suc["name"]}> no info (fields available: available_stalls {suc.ContainsKey("available_stalls")} total_stalls {suc.ContainsKey("available_stalls")})");
                Tools.DebugLog(new Tools.JsonFormatter(JsonConvert.SerializeObject(suc)).Format());
            }
            else
            {
                Tools.DebugLog($"suc ContainsKey available_stalls {suc.ContainsKey("available_stalls")} total_stalls {suc.ContainsKey("available_stalls")} site_closed {suc.ContainsKey("site_closed")}");
            }
        }
 public void Init(Newtonsoft.Json.Linq.JObject jo, SManager SManager)
 {
     this.DB        = DB;
     AlarmReplyForm = new AlarmReplyForm();
 }
Example #41
0
        private void refresh_ui()
        {
            globalRefreshCount++;
            Newtonsoft.Json.Linq.JObject status = null;
            Newtonsoft.Json.Linq.JToken  blocks = null;
            try
            {
                this.updateLabel.BeginInvoke((MethodInvoker) delegate()
                {
                    updateLabel.Text      = "Syncing Network ...";
                    updateLabel.ForeColor = Color.FromArgb(255, 128, 0);
                });
                var balances = ConnectionManager.request("getBalance");
                if (balances.Item1 == false)
                {
                    throw new Exception("getBalance call failed: " + balances.Item2);
                }
                float availableBal = (float)(balances.Item3["availableBalance"]) / 100;
                float lockedBal    = (float)(balances.Item3["lockedAmount"]) / 100;
                this.availableAmountLabel.BeginInvoke((MethodInvoker) delegate() { this.availableAmountLabel.Text = availableBal.ToString("0.00") + " TRTL"; });
                this.lockedAmountLabel.BeginInvoke((MethodInvoker) delegate() { this.lockedAmountLabel.Text = lockedBal.ToString("0.00") + " TRTL"; });

                var Addresses = ConnectionManager.request("getAddresses");
                if (Addresses.Item1 == false)
                {
                    throw new Exception("getAddresses call failed: " + balances.Item2);
                }
                var addressList = Addresses.Item3["addresses"];
                this.myAddressText.BeginInvoke((MethodInvoker) delegate() { myAddressText.Text = addressList[0].ToString(); });

                status = ConnectionManager.request("getStatus").Item3;
                var parameters = new Dictionary <string, object>()
                {
                    { "blockCount", (int)status["blockCount"] },
                    { "firstBlockIndex", 1 },
                    { "addresses", addressList }
                };
                var blocksRet = ConnectionManager.request("getTransactions", parameters);
                if (blocksRet.Item1 == false)
                {
                    throw new Exception("getTransactions call failed: " + balances.Item2);
                }
                blocks         = blocksRet.Item3["items"];
                currentTimeout = 0;
                currentTry     = 0;
            }
            catch (Exception ex)
            {
                this.updateLabel.BeginInvoke((MethodInvoker) delegate()
                {
                    updateLabel.Text = "Daemon error, retrying ...";
                    windowLogger.Log(LogTextbox, "Daemon error, retrying ...");
                    updateLabel.ForeColor = Color.FromArgb(205, 12, 47);
                });
                if (currentTimeout >= watchdogTimeout)
                {
                    if (currentTry <= watchdogMaxTry)
                    {
                        //daemon restart
                    }
                    else
                    {
                        MessageBox.Show("Turtle Wallet has tried numerous times to relaunch the needed daemon and has failed. Please relaunch the wallet!", "Walletd daemon could not be recovered!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        windowLogger.Log(LogTextbox, "Turtle Wallet has tried numerous times to relaunch the needed daemon and has failed. Please relaunch the wallet!");
                        this.Close();
                    }
                }
                else
                {
                    currentTimeout++;
                }
                return;
            }
            if (blocks == null)
            {
                return;
            }
            foreach (var block in blocks.Reverse())
            {
                var bblock = (Newtonsoft.Json.Linq.JObject)block;
                if (bblock.ContainsKey("transactions"))
                {
                    foreach (var transaction in block["transactions"])
                    {
                        if (cachedTrx.Contains(transaction["transactionHash"].ToString()))
                        {
                            continue;
                        }
                        string address = "";
                        long   desired_transfer_amount = 0;
                        if ((long)transaction["amount"] < 0)
                        {
                            desired_transfer_amount = ((long)transaction["amount"] + (long)transaction["fee"]) * -1;
                        }
                        else
                        {
                            desired_transfer_amount = ((long)transaction["amount"]);
                        }

                        foreach (var transfer in transaction["transfers"])
                        {
                            if ((long)transfer["amount"] == desired_transfer_amount)
                            {
                                address = transfer["address"].ToString();
                            }
                        }

                        List <ListViewItem.ListViewSubItem> subitems = new List <ListViewItem.ListViewSubItem>();

                        if ((long)transaction["unlockTime"] == 0 || (long)transaction["unlockTime"] <= (long)status["blockCount"] - 40)
                        {
                            var confirmItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "  🐢  ✔", System.Drawing.Color.Green, System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                            subitems.Add(confirmItem);
                        }
                        else
                        {
                            var confirmItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "  🐢  ✘", System.Drawing.Color.DarkRed, System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                            subitems.Add(confirmItem);
                        }

                        if ((long)transaction["amount"] > 0)
                        {
                            var directionItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "IN\u2007\u2007⇚\u2007\u2007\u2007", System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))), System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                            subitems.Add(directionItem);
                        }
                        else
                        {
                            var directionItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, "OUT ⇛\u2007\u2007\u2007", System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))), System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                            subitems.Add(directionItem);
                        }

                        var amountItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, ((long)(transaction["amount"]) / 100).ToString("0.00"), System.Drawing.Color.White, System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                        subitems.Add(amountItem);

                        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
                        dtDateTime = dtDateTime.AddSeconds((long)(transaction["timestamp"])).ToLocalTime();
                        var ts       = dtDateTime.ToString("yyyy/MM/dd HH:mm:ss tt");
                        var dateItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, ts, System.Drawing.Color.White, System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                        subitems.Add(dateItem);

                        var addItem = new System.Windows.Forms.ListViewItem.ListViewSubItem(null, address, System.Drawing.Color.White, System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(29)))), ((int)(((byte)(29))))), new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))));
                        subitems.Add(addItem);

                        System.Windows.Forms.ListViewItem trxItem = new System.Windows.Forms.ListViewItem(subitems.ToArray(), -1);
                        trxItem.UseItemStyleForSubItems = false;
                        txList.BeginInvoke((MethodInvoker) delegate()
                        {
                            if (globalRefreshCount > 1)
                            {
                                txList.Items.Insert(0, trxItem);
                            }
                            else
                            {
                                txList.Items.Add(trxItem);
                            }
                            foreach (ColumnHeader column in txList.Columns)
                            {
                                column.Width = -2;
                            }
                        });
                        cachedTrx.Add(transaction["transactionHash"].ToString());
                        windowLogger.Log(LogTextbox, "Found transaction " + transaction["transactionHash"].ToString() + ". Added to list ...");
                    }
                }
            }

            string titleUpdate = "TurtleCoin Wallet - Network Sync [" + status["blockCount"].ToString() + " / " + status["knownBlockCount"].ToString() + "] | Peers: " + status["peerCount"].ToString() + " | Updated: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss tt");

            this.BeginInvoke((MethodInvoker) delegate()
            {
                this.Text = titleUpdate;
                this.Update();
            });
        }
Example #42
0
        public void FieldsFromJSONObject(JSONObject value)
        {
            this.key = (string)value["key"];
            this.time = (long?)value["time"];
            this.topic = (string)value["topic"];
            this.category = (string)value["category"];
            this.body = (string)value["body"];
            this.bodylen = (long?)value["bodylen"];
            this.priority = (long?)value["priority"];

            this.keywords = (LinkedList<string>)new LinkedList<string>();
            string keywordString = (string)value["keywords"];
            if (keywordString != null)
            {
                keywordString = keywordString.Replace(", ", ",");
                while (keywordString.Contains("  "))
                {
                    keywordString = keywordString.Replace("  ", " ");
                }
                string[] keys = StringHelperClass.StringSplit(keywordString, ",", true);
                foreach (string key in keys)
                {
                    this.keywords.AddLast(key);
                }
            }
        }
Example #43
0
        public static List <string> GetMarketData(string mainMarket, Dictionary <string, MarketInfo> marketInfos, PTMagicConfiguration systemConfiguration, LogHelper log)
        {
            List <string> result = new List <string>();

            string lastMarket = "";

            Newtonsoft.Json.Linq.JObject lastTicker = null;
            try
            {
                string baseUrl = "https://api.binance.us/api/v1/ticker/24hr";

                log.DoLogInfo("BinanceUS - Getting market data...");
                Newtonsoft.Json.Linq.JArray jsonArray = GetSimpleJsonArrayFromURL(baseUrl, log);
                if (jsonArray.Count > 0)
                {
                    double mainCurrencyPrice = 1;
                    if (!mainMarket.Equals("USDT", StringComparison.InvariantCultureIgnoreCase) && !mainMarket.Equals("USD", StringComparison.InvariantCultureIgnoreCase))
                    {
                        mainCurrencyPrice = BinanceUS.GetMainCurrencyPrice(mainMarket, systemConfiguration, log);
                    }

                    log.DoLogInfo("BinanceUS - Market data received for " + jsonArray.Count.ToString() + " currencies");

                    if (mainCurrencyPrice > 0)
                    {
                        Dictionary <string, Market> markets = new Dictionary <string, Market>();
                        foreach (Newtonsoft.Json.Linq.JObject currencyTicker in jsonArray)
                        {
                            string marketName = currencyTicker["symbol"].ToString();
                            //New variables for filtering out bad markets
                            float marketLastPrice = currencyTicker["lastPrice"].ToObject <float>();
                            float marketVolume    = currencyTicker["volume"].ToObject <float>();
                            if (marketName.EndsWith(mainMarket, StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (marketLastPrice > 0 && marketVolume > 0)
                                {
                                    // Set last values in case any error occurs
                                    lastMarket = marketName;
                                    lastTicker = currencyTicker;

                                    Market market = new Market();
                                    market.Position             = markets.Count + 1;
                                    market.Name                 = marketName;
                                    market.Symbol               = currencyTicker["symbol"].ToString();
                                    market.Price                = SystemHelper.TextToDouble(currencyTicker["lastPrice"].ToString(), 0, "en-US");
                                    market.Volume24h            = SystemHelper.TextToDouble(currencyTicker["quoteVolume"].ToString(), 0, "en-US");
                                    market.MainCurrencyPriceUSD = mainCurrencyPrice;

                                    markets.Add(market.Name, market);

                                    result.Add(market.Name);
                                }
                                else
                                {
                                    //Let the user know that the problem market was ignored.
                                    log.DoLogInfo("BinanceUS - Ignoring bad market data for " + marketName);
                                }
                            }
                        }

                        BinanceUS.CheckFirstSeenDates(markets, ref marketInfos, systemConfiguration, log);

                        BaseAnalyzer.SaveMarketInfosToFile(marketInfos, systemConfiguration, log);

                        BinanceUS.CheckForMarketDataRecreation(mainMarket, markets, systemConfiguration, log);

                        DateTime fileDateTime = DateTime.UtcNow;

                        FileHelper.WriteTextToFile(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, "MarketData_" + fileDateTime.ToString("yyyy-MM-dd_HH.mm") + ".json", JsonConvert.SerializeObject(markets), fileDateTime, fileDateTime);

                        log.DoLogInfo("BinanceUS - Market data saved for " + markets.Count.ToString() + " markets with " + mainMarket + ".");

                        FileHelper.CleanupFiles(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + Constants.PTMagicPathData + Path.DirectorySeparatorChar + Constants.PTMagicPathExchange + Path.DirectorySeparatorChar, systemConfiguration.AnalyzerSettings.MarketAnalyzer.StoreDataMaxHours);
                        log.DoLogInfo("BinanceUS - Market data cleaned.");
                    }
                    else
                    {
                        log.DoLogError("BinanceUS - Failed to get main market price for " + mainMarket + ".");
                        result = null;
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response)
                    {
                        using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            Dictionary <string, string> errorData = JsonConvert.DeserializeObject <Dictionary <string, string> >(reader.ReadToEnd());
                            if (errorData != null)
                            {
                                string errorMessage = "Unable to get data from BinanceUS with URL '" + errorResponse.ResponseUri + "'!";
                                if (errorData.ContainsKey("code"))
                                {
                                    errorMessage += " - Code: " + errorData["code"];
                                }

                                if (errorData.ContainsKey("msg"))
                                {
                                    errorMessage += " - Message: " + errorData["msg"];
                                }

                                log.DoLogError(errorMessage);
                            }
                        }
                    }
                }
                result = null;
            }
            catch (Exception ex)
            {
                log.DoLogCritical("Exception while getting data for '" + lastMarket + "': " + ex.Message, ex);
                result = null;
            }

            return(result);
        }
Example #44
0
        internal void ReadCommand()
        {
            //Console.WriteLine("Read command: {0}", v);

            try
            {
                foreach (var item in commandsList)
                {
                    JsonSerializerSettings setting = new JsonSerializerSettings();
                    setting.CheckAdditionalContent = false;

                    Newtonsoft.Json.Linq.JObject message = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>((string)item, setting);
                    string type = (string)message["type"];
                    switch (type)
                    {
                    case "create":

                        // Console.WriteLine(message);

                        if (message["data"]["halfSize"] != null)
                        {
                            BoxState ob = JsonConvert.DeserializeObject <BoxState>(((object)message["data"]).ToString());
                            simulator.Create(ob);
                        }

                        if (message["data"]["radius"] != null)
                        {
                            SphereState ob = JsonConvert.DeserializeObject <SphereState>(((object)message["data"]).ToString());
                            simulator.Create(ob);
                            break;
                        }

                        break;

                    case "createBoxes":
                        //Console.WriteLine("Create boxes");
                        // simulator.boxToCreate = 10;
                        simulator.createObjects();
                        break;

                    case "gauntlet":

                        UseGauntlet(((object)message["data"]).ToString());
                        break;

                    case "move":

                        MoveMessage j = JsonConvert.DeserializeObject <MoveMessage>(((object)message["data"]).ToString());
                        //objects[]
                        Player2 onb = (Player2)simulator.users[j.client].player;
                        // Simulation.Awakener.AwakenBody(ob.bodyHandle);
                        onb.Move(j);

                        break;

                    case "rotate":
                        MoveMessage j2 = JsonConvert.DeserializeObject <MoveMessage>(((object)message["data"]).ToString());
                        //objects[]
                        Player2 onb2 = (Player2)simulator.users[j2.client].player;
                        // Simulation.Awakener.AwakenBody(ob.bodyHandle);
                        onb2.Rotate(j2);
                        break;

                    case "jump":
                        Jump(((object)message["data"]).ToString());
                        break;

                    case "shoot":
                        Shoot(((object)message["data"]).ToString());
                        break;

                    case "swipe":
                        Swipe(((object)message["data"]).ToString());
                        break;

                    case "generateMap":

                        var map = this.simulator.server.dataBase.GetMap((string)message["data"]);
                        this.simulator.map = map;

                        foreach (var obj in map.objects)
                        {
                            //obj.ToJson();
                            if (obj.Contains("halfSize"))
                            {
                                obj["halfSize"].AsBsonDocument.Remove("__refId");
                                obj.Remove("_id");
                                var stri = JsonConvert.DeserializeObject <BoxState>(obj.ToJson());
                                stri.quaternion = JsonConvert.DeserializeObject <Quaternion>(obj["quat"].ToJson());

                                this.simulator.Create(stri);
                            }
                            if (obj.Contains("radius"))
                            {
                                // obj["radius"].AsBsonDocument.Remove("__refId");
                                obj.Remove("_id");
                                var stri = JsonConvert.DeserializeObject <SphereState>(obj.ToJson());
                                stri.quaternion = JsonConvert.DeserializeObject <Quaternion>(obj["quat"].ToJson());

                                this.simulator.Create(stri);
                            }
                        }
                        break;

                    case "close":
                        //Console.WriteLine("Close");
                        simulator.Close();

                        break;

                    default:
                        QuixConsole.WriteLine("Command not registred " + type);
                        break;
                    }
                }

                commandsList.Clear();
            }
            catch (InvalidOperationException e)
            {
                QuixConsole.Log("Collection was modifieded", e);
            }
            catch (JsonReaderException e)
            {
                QuixConsole.Log("Json Problem ", e);
            }
            catch (Exception e) {
                QuixConsole.WriteLine(e);
            }
        }
Example #45
0
        public JsonResult LogarPeloFacebook(FacebookAccountViewModel facebookLogin)
        {
            DAOUsuarioProfissional daoUsuarioProfissional = null;
            UsuarioProfissional    usuarioProfissional    = null;
            string               urlGetOpenGraphAccesToken;
            HttpWebRequest       accessTokenRequest      = null;
            HttpWebResponse      accessTokenResponse     = null;
            string               accessTokenResponseText = null;
            string               accessToken             = null;
            string               urlCheckUserAccessToken;
            string               checkAccessTokenResponseText;
            DAOFacebookAccount   daoFacebookAccount   = null;
            FacebookAccount      facebookAccount      = null;
            DAOUsuario           daoUsuario           = null;
            Usuario              usuario              = null;
            DAOUsuarioParticular daoUsuarioParticular = null;
            UsuarioParticular    usuarioParticular    = null;

            try
            {
                urlGetOpenGraphAccesToken = @"https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=1753687224853096&client_secret=6af778d15f3ce0ffa2b4e1acdcede3a9";
                accessTokenRequest        = (HttpWebRequest)WebRequest.Create(urlGetOpenGraphAccesToken);
                accessTokenResponse       = (HttpWebResponse)accessTokenRequest.GetResponse();
                using (var accessTokenResponseReader = new System.IO.StreamReader(accessTokenResponse.GetResponseStream(), Encoding.UTF8))
                {
                    accessTokenResponseText = accessTokenResponseReader.ReadToEnd();
                }
                accessToken = accessTokenResponseText.Substring(13); //Buscar uma maneira melhor de fazer isto (extrair o token da string).

                urlCheckUserAccessToken = String.Format("https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", facebookLogin.AccessToken, accessToken);
                HttpWebRequest  checkUserAccessTokenRequest  = (HttpWebRequest)WebRequest.Create(urlCheckUserAccessToken);
                HttpWebResponse checkUserAccessTokenResponse = (HttpWebResponse)checkUserAccessTokenRequest.GetResponse();
                if (checkUserAccessTokenResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var checkAccessTokenResponseReader = new System.IO.StreamReader(checkUserAccessTokenResponse.GetResponseStream(), Encoding.UTF8))
                    {
                        checkAccessTokenResponseText = checkAccessTokenResponseReader.ReadToEnd();
                    }

                    Newtonsoft.Json.Linq.JObject jsonCheckAccessTokenResponse = JsonConvert.DeserializeObject(checkAccessTokenResponseText) as Newtonsoft.Json.Linq.JObject;
                    if (jsonCheckAccessTokenResponse["data"]["is_valid"].ToString() == "True")
                    {
                        if (jsonCheckAccessTokenResponse["data"]["app_id"].ToString() == "1753687224853096")
                        {
                            if (jsonCheckAccessTokenResponse["data"]["user_id"].ToString() == facebookLogin.Id)
                            {
                                daoFacebookAccount = new DAOFacebookAccount();
                                // Tenta obter um "FacebookAccount" no banco de dados, checando se é um usuário retornante.
                                facebookAccount = daoFacebookAccount.ObterFacebookAccount(facebookLogin.Id);
                                if (facebookAccount != null) // Se o "facebookAccount" entrar na condição de "não nulo", ou seja, foi encontrada uma instância com o mesmo "FacebookId" no banco de dados, o usuário em questão é considerado retornante, não é a primeira vez que ele loga via Facebook.
                                {
                                    // Obtém o complemento dos dados, caso o usuário seja um particular (obtém-se na tabela "UsuariosParticulares").
                                    if (facebookAccount.Usuario.Perfil == Usuario.TipoPerfil.UsuarioParticular)
                                    {
                                        daoUsuarioParticular       = new DAOUsuarioParticular();
                                        usuarioParticular          = daoUsuarioParticular.ObterUsuarioParticular(facebookAccount.Usuario.Id);
                                        usuarioParticular.Facebook = facebookAccount;
                                        facebookAccount.Usuario    = usuarioParticular;

                                        Session["Usuario"] = usuarioProfissional;

                                        return(Json(new
                                        {
                                            info = "redirect",
                                            data = Url.Action("UsuarioParticular", "Perfil")
                                        }));
                                    } // Obtém o complemento dos dados, caso o usuário seja um profissional (obtém-se na tabela "UsuáriosProfissionais").
                                    else if (facebookAccount.Usuario.Perfil == Usuario.TipoPerfil.UsuarioProfissional)
                                    {
                                        daoUsuarioProfissional       = new DAOUsuarioProfissional();
                                        usuarioProfissional          = daoUsuarioProfissional.ObterUsuarioProfissional(facebookAccount.Usuario.Id);
                                        usuarioProfissional.Facebook = facebookAccount;
                                        facebookAccount.Usuario      = usuarioProfissional;

                                        Session["Usuario"] = usuarioProfissional;

                                        return(Json(new
                                        {
                                            info = "redirect",
                                            data = Url.Action("UsuarioProfissional", "Perfil")
                                        }));
                                    }
                                }
                                else // Neste caso, não foi encontrado nenhum registro no banco com este "FacebookId", assumindo que este usuário entrou pelo Facebook pela primeira vez.
                                {
                                    daoUsuario = new DAOUsuario();
                                    // Busca-se por um registro de usuário com o e-mail retornado pelo Facebook, para descobrir se esta pessoa já tinha um cadastro tradicional (entrava com e-mail e senha anteriormente).
                                    usuario = daoUsuario.ObterUsuarioPorEmail(facebookLogin.Email);
                                    if (usuario != null)
                                    {
                                        // Neste caso, apesar de o usuário ter logado pela primeira vez via Facebook, o e-mail que o Facebook retornou já consta em um perfil na tabela "Usuarios" (ele já havia logado via e-mail/senha tradicionalmente).
                                        // Este usuário deve ser informado disto e informar a senha referente ao e-mail encontrado para poder prosseguir no site.
                                        Session["Usuario"] = usuario;

                                        return(Json(new
                                        {
                                            info = "exigirSenhaEmailEncontrado"
                                        }));
                                    }
                                    else
                                    {
                                        // Neste caso, o usuário será tratado como um usuário inédito, ou seja, é a primeira vez que o mesmo logou no sistema e escolheu o fazer via Facebook, pois o seu "FaceBookId" não consta na tabela "FacebookAccounts" e seu e-mail obtido do Facebook também não consta na tabela de "Usuarios". Este usuário será incluído com o perfil "Indefinido" (temporariamente), e perguntado com qual tipo de perfil ele deseja prosseguir.
                                        usuario                      = new Usuario();
                                        usuario.Nome                 = facebookLogin.Nome;
                                        usuario.Email                = facebookLogin.Email;
                                        usuario.Facebook             = new FacebookAccount();
                                        usuario.Facebook.FacebookId  = facebookLogin.Id;
                                        usuario.Facebook.Nome        = facebookLogin.Nome;
                                        usuario.Facebook.Email       = facebookLogin.Email;
                                        usuario.Facebook.AccessToken = facebookLogin.AccessToken;
                                        usuario.Perfil               = Usuario.TipoPerfil.PerfilIndefinido;
                                        if (daoUsuario.IncluirUsuarioComFacebook(usuario))
                                        {
                                            Session["Usuario"] = usuario;
                                        }
                                        return(Json(new
                                        {
                                            info = "solicitarDefinicaoPerfil"
                                        }));
                                    }
                                }
                            }
                        }
                    }
                }
                return(Json(new
                {
                    info = "naoDefinido"
                }));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #46
0
 public ConfirmRequotedCommand(JSONObject arguments, bool prettyPrint)
     : base(arguments, prettyPrint)
 {
 }
 private static System.Linq.Expressions.Expression <Func <WebFriendLinksEntity, bool> > FilterParams(System.Linq.Expressions.Expression <Func <WebFriendLinksEntity, bool> > expression, Newtonsoft.Json.Linq.JObject queryParam)
 {
     if (!queryParam["keyword"].IsEmpty())
     {
         string keyword = queryParam["keyword"].ToString();
         expression = expression.And(t => t.F_FullName.Contains(keyword));
     }
     if (!queryParam["nodeid"].IsEmpty())
     {
         string keyword = queryParam["nodeid"].ToString();
         expression = expression.And(t => t.F_NodeID.Equals(keyword));
     }
     if (!queryParam["linktype"].IsEmpty())
     {
         string keyword = queryParam["linktype"].ToString();
         expression = expression.And(t => t.F_LinkType.Equals(keyword));
     }
     if (!queryParam["F_DeleteMark"].IsEmpty())
     {
         string F_DeleteMark = queryParam["F_DeleteMark"].ToString();
         expression = expression.And(t => (t.F_DeleteMark.Equals(F_DeleteMark)));
     }
     if (!queryParam["F_EnabledMark"].IsEmpty())
     {
         string F_EnabledMark = queryParam["F_EnabledMark"].ToString();
         expression = expression.And(t => (t.F_EnabledMark.Equals(F_EnabledMark)));
     }
     return(expression);
 }
        private VirtualMachine SetAzureVMDiagnosticsExtensionC(VirtualMachine selectedVM, string storageAccountName, string storageAccountKey)
        {
            System.Xml.XmlDocument xpublicConfig = null;

            var extensionName = AEMExtensionConstants.WADExtensionDefaultName[this.OSType];

            var extTemp = this._Helper.GetExtension(selectedVM,
                AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[OSType]);
            object publicConf = null;
            if (extTemp != null)
            {
                publicConf = extTemp.Settings;
                extensionName = extTemp.Name;
            }

            if (publicConf != null)
            {
                var jpublicConf = publicConf as Newtonsoft.Json.Linq.JObject;
                if (jpublicConf == null)
                {
                    throw new ArgumentException();
                }

                var base64 = jpublicConf["xmlCfg"] as Newtonsoft.Json.Linq.JValue;
                if (base64 == null)
                {
                    throw new ArgumentException();
                }

                System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                xDoc.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString())));

                if (xDoc.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters") != null)
                {
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration").Attributes["overallQuotaInMB"].Value = "4096";
                    xDoc.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").Attributes["scheduledTransferPeriod"].Value = "PT1M";

                    xpublicConfig = xDoc;
                }
            }

            if (xpublicConfig == null)
            {
                xpublicConfig = new System.Xml.XmlDocument();
                xpublicConfig.LoadXml(AEMExtensionConstants.WADConfigXML);
            }

            foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[OSType])
            {
                var currentCounter = xpublicConfig.
                            SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']");
                if (currentCounter == null)
                {
                    var node = xpublicConfig.CreateElement("PerformanceCounterConfiguration");
                    xpublicConfig.SelectSingleNode("WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters").AppendChild(node);
                    node.SetAttribute("counterSpecifier", perfCounter.counterSpecifier);
                    node.SetAttribute("sampleRate", perfCounter.sampleRate);
                }
            }

            var endpoint = this._Helper.GetCoreEndpoint(storageAccountName);
            endpoint = "https://" + endpoint;

            Newtonsoft.Json.Linq.JObject jPublicConfig = new Newtonsoft.Json.Linq.JObject();
            jPublicConfig.Add("xmlCfg", new Newtonsoft.Json.Linq.JValue(System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(xpublicConfig.InnerXml))));

            Newtonsoft.Json.Linq.JObject jPrivateConfig = new Newtonsoft.Json.Linq.JObject();
            jPrivateConfig.Add("storageAccountName", new Newtonsoft.Json.Linq.JValue(storageAccountName));
            jPrivateConfig.Add("storageAccountKey", new Newtonsoft.Json.Linq.JValue(storageAccountKey));
            jPrivateConfig.Add("storageAccountEndPoint", new Newtonsoft.Json.Linq.JValue(endpoint));

            WriteVerbose("Installing WAD extension");
            VirtualMachineExtension vmExtParameters = new VirtualMachineExtension();

            vmExtParameters.Publisher = AEMExtensionConstants.WADExtensionPublisher[this.OSType];
            vmExtParameters.VirtualMachineExtensionType = AEMExtensionConstants.WADExtensionType[this.OSType];
            vmExtParameters.TypeHandlerVersion = AEMExtensionConstants.WADExtensionVersion[this.OSType];
            vmExtParameters.Settings = jPublicConfig;
            vmExtParameters.ProtectedSettings = jPrivateConfig;
            vmExtParameters.Location = selectedVM.Location;

            this.VirtualMachineExtensionClient.CreateOrUpdate(ResourceGroupName, selectedVM.Name, extensionName, vmExtParameters);

            return this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(ResourceGroupName, selectedVM.Name);
        }
Example #49
0
        private List<VideoInfo> generateVideoList(Category category)
        {
            login();
            currentVideoUrl = (category as RssLink).Url;
            List<VideoInfo> videos = new List<VideoInfo>();
            Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject();
            try
            {
                json = GetWebData<Newtonsoft.Json.Linq.JObject>((category as RssLink).Url);
            }
            catch(Exception e)
            {
                Log.Error("Error when trying to get TV4Play videos: {0}", (category as RssLink).Url);
                Log.Error(e);
                throw new OnlineVideosException("Error getting videos, try again!",false);
            }
            Newtonsoft.Json.Linq.JArray results = (Newtonsoft.Json.Linq.JArray)json["results"];
            foreach (var result in results)
            {
                if ((!tryFilterDrm || !(bool)result["is_drm_protected"]) && (isPremium || int.Parse(((string)result["availability"]["availability_group_free"]).Replace("+",string.Empty)) > 0))
                {
                    VideoInfo video = new VideoInfo();
                    video.Title = (string)result["title"];

                    if (category.Name == klipp || category.Name == helaProgram)
                    {
                        //broadcast_date_time=2012-12-12T21:30:00+01:00
                        var dateNode = result["broadcast_date_time"];
                        if (dateNode != null) video.Airdate = ((DateTime)dateNode).ToString("g", OnlineVideoSettings.Instance.Locale);
                    }
                    video.VideoUrl = string.Format(videoAssetBaseUrl, (string)result["id"]);
                    if (category.Name == filmer)
                    {
                        if (((string)result["poster_image"]) != null)
                        {
                            video.Thumb = ((string)result["poster_image"]).StartsWith("/") ?
                                string.Format(filmerImageUrl, webApiBaseUrl, (string)result["poster_image"]) :
                                (string)result["poster_image"];
                        }
                        video.Description = (string)result["synopsis"];
                    }
                    else
                    {
                        video.Thumb = string.Format(programImageUrl, "", HttpUtility.UrlEncode((string)result["image"]));
                        video.Description = (string)result["description"];
                    }
                    videos.Add(video);
                }
            }
            HasNextPage = false;
            if (category.Name == klipp || category.Name == helaProgram)
            {
                var assets_types_hits = json["assets_types_hits"];
                bool gotClip = (assets_types_hits["clip"] != null);
                bool gotProgram = (assets_types_hits["program"] != null);
                int hits = 0;
                if (gotClip && gotProgram)
                {
                    hits = (int)json["assets_types_hits"][(category.Name == helaProgram) ? "program" : "clip"];
                }
                else if (gotProgram && category.Name == helaProgram)
                {
                    hits = (int)json["assets_types_hits"]["program"];
                }
                else if (gotClip && category.Name == klipp)
                {
                    hits = (int)json["assets_types_hits"]["clip"];
                }

                HasNextPage = hits > (currentPage * numberOfVideosPerPage);
                if (HasNextPage)
                {
                    currentVideoUrl = (category as RssLink).Url.Replace("&page=" + currentPage, "&page=" + (currentPage + 1));
                    currentPage++;
                }
            }
            return videos;
        }
Example #50
0
        public void Deploy()
        {
            Console.WriteLine("");
            Console.WriteLine("Deploying JSON");

            Console.WriteLine("Loading Module directory " + sModulePath + "...");
            DirectoryResourceRepository directoryResourceRepository = new DirectoryResourceRepository(sModulePath);

            ContentManager contentManager = new ContentManager(sClientPath, sServerPath);
            NWN2ResourceManager manager = new NWN2ResourceManager();

            contentManager.ServerContentItemScanning += (name, status, bBegin) =>
            {
                if (!bBegin)
                    Console.Write(" -> Staging (" + status.ToString() + ")");
                else
                    Console.Write("\nScanning: " + name);
            };

            contentManager.InitializeModule(directoryResourceRepository);
            contentManager.ResetAllResourcesToDefaultServer();
            contentManager.ResetScanResults();

            checked
            {
                manager.AddRepository(directoryResourceRepository);

                string sModuleName = Path.GetFileNameWithoutExtension(sModulePath);
                string sTlkPath = "";

                foreach (DownloadableResource d in contentManager.GetDownloadableResources())
                {
                    switch (d.Type)
                    {
                        case DownloadableResource.FileType.Hak:
                            string hakPath = sHomePath + "\\hak\\" + d.Name;
                            Console.WriteLine("Adding Hak: " + d.Name);
                            if (File.Exists(hakPath))
                                manager.AddRepository(new ERFResourceRepository(hakPath));
                            else
                                Console.WriteLine("ERROR - Hak file not found in " + hakPath);
                            break;

                        case DownloadableResource.FileType.Tlk:
                            sTlkPath = sHomePath + "\\tlk\\" + d.Name;
                            if (File.Exists(sTlkPath))
                                Console.WriteLine("Found TLK: " + d.Name);
                            else
                                Console.WriteLine("ERROR - Tlk not found in " + sTlkPath);
                            break;
                    }
                }

                KeyValuePair<String, ushort>[] resourceTypes = { new KeyValuePair<String, ushort>("creature", ResUTC),
                                                               new KeyValuePair<String, ushort>("door", ResUTD),
                                                               new KeyValuePair<String, ushort>("encounter", ResUTE),
                                                               new KeyValuePair<String, ushort>("item", ResUTI),
                                                               new KeyValuePair<String, ushort>("store", ResUTM),
                                                               new KeyValuePair<String, ushort>("placeable", ResUTP),
                                                               new KeyValuePair<String, ushort>("tree", ResUTR),
                                                               new KeyValuePair<String, ushort>("sound", ResUTS),
                                                               new KeyValuePair<String, ushort>("trigger", ResUTT),
                                                               new KeyValuePair<String, ushort>("waypoint", ResUTW),
                                                               new KeyValuePair<String, ushort>("light", ResULT),
                                                               new KeyValuePair<String, ushort>("prefab", ResPFB) };

                //ushort[] resourceTypes = { ResUTC, ResUTD, ResUTE, ResUTI, ResUTM, ResUTP, ResUTR, ResUTS, ResUTT, ResUTW, ResULT, ResPFB };

                var json = new Newtonsoft.Json.Linq.JObject();

                foreach (KeyValuePair<String, ushort> rType in resourceTypes)
                {
                    var jsonArray = new Newtonsoft.Json.Linq.JArray();

                    foreach (IResourceEntry resource in manager.FindEntriesByType(rType.Value))
                    {
                        Console.WriteLine(rType.Key + ": " + resource.FullName);

                        var gff = new OEIShared.IO.GFF.GFFFile(resource.GetStream(false));

                        if (gff != null)
                        {
                            Newtonsoft.Json.Linq.JObject jsonData = null;

                            jsonData = new Newtonsoft.Json.Linq.JObject(parseGFF(gff));
                            //Console.WriteLine(jsonData);
                            /*
                            switch (rType.Value)
                            {
                                case ResUTC:
                                    var creature = new NWN2Toolset.NWN2.Data.Blueprints.NWN2CreatureBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(creature);
                                    break;
                                case ResUTD:
                                    var door = new NWN2Toolset.NWN2.Data.Blueprints.NWN2DoorBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(door);
                                    break;
                                case ResUTE:
                                    var encounter = new NWN2Toolset.NWN2.Data.Blueprints.NWN2EncounterBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(encounter);
                                    break;
                                case ResUTI:
                                    var item = new NWN2Toolset.NWN2.Data.Blueprints.NWN2ItemBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(item);
                                    break;
                                case ResUTM:
                                    var store = new NWN2Toolset.NWN2.Data.Blueprints.NWN2StoreBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(store);
                                    break;
                                case ResUTP:
                                    var placeable = new NWN2Toolset.NWN2.Data.Blueprints.NWN2PlaceableBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(placeable);
                                    break;
                                case ResUTR:
                                    var tree = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TreeBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(tree);
                                    break;
                                case ResUTS:
                                    var sound = new NWN2Toolset.NWN2.Data.Blueprints.NWN2SoundBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(sound);
                                    break;
                                case ResUTT:
                                    var trigger = new NWN2Toolset.NWN2.Data.Blueprints.NWN2TriggerBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(trigger);
                                    break;
                                case ResUTW:
                                    var waypoint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2WaypointBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(waypoint);
                                    break;
                                case ResULT:
                                    var light = new NWN2Toolset.NWN2.Data.Blueprints.NWN2LightBlueprint(gff.TopLevelStruct);
                                    jsonData = new Newtonsoft.Json.Linq.JObject(light);
                                    break;
                                case ResPFB:
                                    //blueprint = new NWN2Toolset.NWN2.Data.Blueprints.NWN2BlueprintSet(gff.TopLevelStruct);
                                    break;
                                default:
                                    break;
                            }
                            */
                            if (jsonData != null) jsonArray.Add(jsonData);
                        }
                    }

                    if (jsonArray.Count > 0) json.Add(rType.Key,jsonArray);
                }

                Console.WriteLine("");
                Console.WriteLine("Staging JSON Complete.");
                Console.WriteLine("");
                Console.WriteLine(json);

                System.IO.File.WriteAllText(@".\nwn2.json", json.ToString());
            }
        }
Example #51
0
        public void AddToUserInventory(ItemSchema.ItemDBSchema item)
        {
            var queryRequest = new QueryRequest()
                               .Statement("SELECT meta(`FarmWorld`).id, * FROM `FarmWorld` WHERE userName=$1 AND uniqueName=$2")
                               .AddPositionalParameter(item.userName)
                               .AddPositionalParameter(item.uniqueName);
            var result = _bucket.Query <dynamic>(queryRequest);

            if (!result.Success)
            {
                throw new Exception(String.Format("AddToUserInventory initial queryRequest failed: {0}", result.Status));
            }
            if (result.Rows.Count > 1)
            {
                throw new Exception(String.Format("AddToUserInventory initial query returned more than 1 row for uuesr {0} item {1}", item.userName, item.uniqueName));
            }

            if (result.Rows.Count == 0)  // TODO: Potential race here if 2 items are added at same time on an item that did not exist before.
            {
                var idResult = _bucket.Increment("UserItemInventoryCounter");
                if (!idResult.Success)
                {
                    Console.WriteLine("Failed to get next increment for UserItemInventoryCounter.");
                    return;
                }

                var document = new Document <dynamic>
                {
                    Id      = "item" + idResult.Value.ToString(),
                    Content = item
                };
                var upsert = _bucket.Upsert(document);
                if (!upsert.Success)
                {
                    throw new Exception(String.Format("Upserting item failed for user {0} and item {1} and quantity {2}", item.userName, item.uniqueName, item.quantity));
                }
            }
            else
            {
                var    row = result.Rows[0];
                string id  = row.GetValue("id");

                var lockResult = _bucket.GetAndLock <dynamic>(id, 1); // TODO: Implement wait and retry.
                if (!lockResult.Success)
                {
                    if (lockResult.Status == Couchbase.IO.ResponseStatus.Locked)
                    {
                        Console.WriteLine(String.Format("Item with id {0} already DB locked for user {1}.", id, item.userName));
                    }
                    else if (lockResult.Status == Couchbase.IO.ResponseStatus.KeyNotFound)
                    {
                        throw new Exception(String.Format("Locking item failed for user {0} and item {1} and quantity {2}", item.userName, item.uniqueName, item.quantity));
                    }
                    else
                    {
                        throw new NotImplementedException(String.Format("Lock operation threw status {0} which is not handled on id {1}.", lockResult.Status, id));
                    }
                }

                Newtonsoft.Json.Linq.JObject obj = lockResult.Value;
                obj["quantity"] = item.quantity + obj.Value <int>("quantity");

                IOperationResult replaceResult = _bucket.Replace(id, obj, lockResult.Cas);  // This replaces the object and releases the DB lock.
                if (!replaceResult.Success)
                {
                    throw new Exception(String.Format("Replace on item id '{0}' did not work: {1}.", id, replaceResult.Status));
                }
            }
        }
Example #52
0
 public void FieldsFromJSONObject(JSONObject value)
 {
     FieldsFromJSONObject(value, null);
 }
Example #53
0
 public void SendMessage(string type, Newtonsoft.Json.Linq.JObject message, Socket socket)
 {
     SendMessage(type, message.ToString(), socket);
 }
Example #54
0
 public void FieldsFromJSONObject(JSONObject value)
 {
     this.day = (long?) value["day"];
         this.fromT = (long?) value["fromT"];
         this.toT = (long?) value["toT"];
 }
Example #55
0
        public void AddWorkClass(Newtonsoft.Json.Linq.JObject requestValue, Newtonsoft.Json.Linq.JObject Data, MESStationReturn StationReturn)
        {
            string         className = Data["CLASS_NAME"].ToString().Trim();
            string         startTime = Data["START_TIME"].ToString().Trim();
            string         endTime   = Data["END_TIME"].ToString().Trim();
            bool           isExist   = false;
            OleExec        oleDB     = null;
            T_C_WORK_CLASS workClass = null;

            if (string.IsNullOrEmpty(className))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("CLASS NAME");
                StationReturn.Data = "";
                return;
            }
            if (string.IsNullOrEmpty(startTime))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("START TIME");
                StationReturn.Data = "";
                return;
            }
            if (string.IsNullOrEmpty(endTime))
            {
                StationReturn.Status      = StationReturnStatusValue.Fail;
                StationReturn.MessageCode = "MES00000006";
                StationReturn.MessagePara.Add("END TIME");
                StationReturn.Data = "";
                return;
            }
            try
            {
                oleDB     = this.DBPools["SFCDB"].Borrow();
                workClass = new T_C_WORK_CLASS(oleDB, DBTYPE);
                if (workClass.WorkClassIsExistByName(className, oleDB))
                {
                    StationReturn.MessagePara.Add(className);
                    isExist = true;
                }
                if (workClass.TimeIsExist(startTime, oleDB))
                {
                    StationReturn.MessagePara.Add(startTime);
                    isExist = true;
                }
                if (workClass.TimeIsExist(endTime, oleDB))
                {
                    StationReturn.MessagePara.Add(endTime);
                    isExist = true;
                }
                if (isExist)
                {
                    StationReturn.Status      = StationReturnStatusValue.Fail;
                    StationReturn.MessageCode = "MES00000008";
                    StationReturn.Data        = "";
                }
                else
                {
                    Row_C_WORK_CLASS workClassRow = (Row_C_WORK_CLASS)workClass.NewRow();
                    workClassRow.ID          = workClass.GetNewID(this.BU, oleDB, DBTYPE);
                    workClassRow.NAME        = className;
                    workClassRow.START_TIME  = startTime;
                    workClassRow.END_TIME    = endTime;
                    oleDB.ThrowSqlExeception = true;
                    oleDB.ExecSQL(workClassRow.GetInsertString(DBTYPE));
                    StationReturn.Status      = StationReturnStatusValue.Pass;
                    StationReturn.MessageCode = "MES00000002";
                    StationReturn.Data        = "";
                }
                this.DBPools["SFCDB"].Return(oleDB);
            }
            catch (Exception exctption)
            {
                this.DBPools["SFCDB"].Return(oleDB);
                throw exctption;
            }
        }
        public async Task <bool> RefreshTokenAsync(string refreshToken)
        {
            WebRequest request = WebRequest.Create(TokenRequestEndpoint);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            // fill post request form data
            string data = $"client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&refresh_token={refreshToken}&grant_type=refresh_token";

            if (!string.IsNullOrEmpty(CLIENT_SECRET))
            {
                data += $"&client_secret={CLIENT_SECRET}";
            }
            using (StreamWriter requestWriter = new StreamWriter(await request.GetRequestStreamAsync()))
            {
                requestWriter.Write(data, 0, data.Length);
                requestWriter.Close();
            }

            try
            {
                using (WebResponse response = await request.GetResponseAsync())
                {
                    using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
                    {
                        string streamtoStr = await streamReader.ReadToEndAsync();

                        Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(streamtoStr);
                        string accessToken     = jObject["access_token"]?.ToString();
                        string newRefreshToken = jObject["refresh_token"]?.ToString();
                        int    expiresIn       = -1;
                        if (jObject["expires_in"] != null)
                        {
                            expiresIn = jObject["expires_in"].ToObject <int>();
                        }
                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            AccessToken = accessToken;
                            if (!string.IsNullOrEmpty(newRefreshToken))
                            {
                                RefreshToken = newRefreshToken;
                            }
                            else
                            {
                                RefreshToken = refreshToken;
                            }
                            if (expiresIn > 0)
                            {
                                ExpiresAt = DateTime.Now.AddSeconds(expiresIn);
                            }
                            else
                            {
                                ExpiresAt = null;
                            }
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LastError = ex.Message;
            }
            return(false);
        }
Example #57
0
 public override void DeserializeJson(Newtonsoft.Json.Linq.JObject json)
 {
     Utils.SafeAssign(ref m_minAllowedRepeatIntervalMs, json["MinAllowedRepeatIntervalMs"]);
 }
Example #58
0
 public void FieldsFromJSONObject(JSONObject value)
 {
     mainPort      = (int)value["mainPort"];
     streamingPort = (int)value["streamingPort"];
     address       = (string)value["address"];
 }
        private void CustomizedExceptionSerialization(StringBuilder builder, System.Exception exception)
        {
            try
            {
                Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer()
                {
                    // disable serializable interface to allow e.g.: null value handling
                    // this is needed to work properly with types implementing ISerializable interface
                    ContractResolver =
                        (_mode == WorkMode.Full)
                        ? (new Newtonsoft.Json.Serialization.DefaultContractResolver()
                    {
                        IgnoreSerializableInterface = true
                    })
                        : (new PartialSerializationContractResolver((_propertyNames != null) ? _propertyNames : _defaultPropertyNames)),

                    Formatting =
                        _mode == WorkMode.Slim ? Newtonsoft.Json.Formatting.None : Newtonsoft.Json.Formatting.Indented,

                    NullValueHandling =
                        _mode == WorkMode.Full ? Newtonsoft.Json.NullValueHandling.Include : Newtonsoft.Json.NullValueHandling.Ignore,

                    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                };


                // partial serialization to JObject
                var jsonObject = Newtonsoft.Json.Linq.JObject.FromObject(exception, jsonSerializer);

                // appending Exception type property to serialized
                if (_includeClassName)
                {
                    if (exception.InnerException == null)
                    {
                        // optimization for simple exception
                        jsonObject.Add(_className, exception.GetType().ToString());
                    }
                    else
                    {
                        System.Collections.Generic.Stack <Tuple <string, Newtonsoft.Json.Linq.JObject> > stack =
                            new Stack <Tuple <string, Newtonsoft.Json.Linq.JObject> >();

                        Newtonsoft.Json.Linq.JObject j = jsonObject;


                        for (System.Exception e = exception; ; j = (Newtonsoft.Json.Linq.JObject)j["InnerException"])
                        {
                            stack.Push(new Tuple <string, Newtonsoft.Json.Linq.JObject>(e.GetType().ToString(), j));

                            e = e.InnerException;

                            if (e == null)
                            {
                                break;
                            }
                        }

                        foreach (var pair in stack)
                        {
                            pair.Item2.Add(_className, pair.Item1);
                        }
                    }
                }

                builder.Append(jsonObject.ToString(jsonSerializer.Formatting));
            }
            catch (Exception ex)
            {
                NLog.Common.InternalLogger.Error(ex, "Exception serialization failed. Newtonsoft.Json error.");
            }
        }
Example #60
-1
 public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
 {
     var exception = value as System.Exception;
     if (exception != null)
     {
         var resolver = serializer.ContractResolver as Newtonsoft.Json.Serialization.DefaultContractResolver ?? _defaultContractResolver;
 
         var jObject = new Newtonsoft.Json.Linq.JObject();
         jObject.Add(resolver.GetResolvedPropertyName("discriminator"), exception.GetType().Name);
         jObject.Add(resolver.GetResolvedPropertyName("Message"), exception.Message);
         jObject.Add(resolver.GetResolvedPropertyName("StackTrace"), _hideStackTrace ? "HIDDEN" : exception.StackTrace);
         jObject.Add(resolver.GetResolvedPropertyName("Source"), exception.Source);
         jObject.Add(resolver.GetResolvedPropertyName("InnerException"),
             exception.InnerException != null ? Newtonsoft.Json.Linq.JToken.FromObject(exception.InnerException, serializer) : null);
 
         foreach (var property in GetExceptionProperties(value.GetType()))
         {
             var propertyValue = property.Key.GetValue(exception);
             if (propertyValue != null)
             {
                 jObject.AddFirst(new Newtonsoft.Json.Linq.JProperty(resolver.GetResolvedPropertyName(property.Value),
                     Newtonsoft.Json.Linq.JToken.FromObject(propertyValue, serializer)));
             }
         }
 
         value = jObject;
     }
 
     serializer.Serialize(writer, value);
 }