Example #1
0
        /* Создаем комбинации полученные в виде списка строк с позициями id(AssingCombination),
         * затем заменяем позиции id на сами id(напр. 1 на [2699153045], 321 на [2699153205,2699153081,2699153045])*/
        public List <JArray> CreateCombinations(JArray outcomes)
        {
            var ids           = "";
            var allOutcomeIds = new List <JArray>();
            var combinations  = new List <string>();

            for (int i = 1; i <= outcomes?.Count(); i++)
            {
                ids += i.ToString();
            }
            AssignCombination("", ids, combinations);
            combinations.Reverse();

            foreach (var combination in combinations)
            {
                // Разбиваем строку "123" на массив чисел [1, 2, 3]
                var cs = combination.ToCharArray().Select(c => (int)char.GetNumericValue(c)).ToList();
                cs.Reverse();
                // Заменяем позиции id на сами id
                var outcomeIds = new JArray();
                foreach (var c in cs)
                {
                    outcomeIds.Add(outcomes[c - 1]["id"]);
                }
                allOutcomeIds.Add(outcomeIds);
            }

            return(allOutcomeIds);
        }
        public async Task <IActionResult> GetAccessList(int page = 1, int limit = 10)
        {
            var users = db.UserInfos.AsNoTracking().Select(s => new
            {
                s.Id,
                s.Name,
                s.UserAccess
            });
            JArray jArray = new JArray();
            await users.ForEachAsync(u =>
            {
                JObject jObject = new JObject();
                jObject.Add("Id", u.Id);
                jObject.Add("Name", u.Name);
                Enum.GetValues(typeof(Access)).Cast <Access>().ToList().ForEach(s =>
                {
                    jObject.Add(s.ToString(), (u.UserAccess & s) == s);
                });
                jArray.Add(jObject);
            });

            var retList = new
            {
                code  = 0,
                msg   = "",
                count = jArray?.Count(),
                data  = jArray?.Skip((page - 1) * limit).Take(limit)
            };

            return(Content(JsonConvert.SerializeObject(retList)));
        }
Example #3
0
        /// <summary>
        /// Read json file and return a JObject
        /// </summary>
        /// <param name="proc_guid"></param>
        /// <returns></returns>
        internal JObject readJsonFile()
        {
            try
            {
                file_name = (file_name.ToLower().EndsWith(".json")) ? file_name : String.Format("{0}.json", file_name);
                bool file_exist = File.Exists(file_name);
                canWrite = !((file_must_exists) && (!file_exist));

                if (file_exist)
                {
                    FileInfo fi = new FileInfo(file_name);

                    StreamReader   str    = new StreamReader(fi.FullName);
                    JsonTextReader jsr    = new JsonTextReader(str);
                    JObject        JProc  = null;
                    bool           errors = false;

                    try
                    {
                        JsonSerializer jser = new JsonSerializer();
                        JProc = jser.Deserialize <JObject>(jsr);
                        if (JProc == null)
                        {
                            errors = true;
                        }
                    }
                    catch (Exception exc)
                    {
                        jErrors.Add(exc.Message);
                        errors = true;
                    }
                    finally
                    {
                        str.Close();
                    }
                    if (errors)
                    {
                        String filecontent = File.ReadAllText(fi.FullName);
                        String schema      = "";
                        if (filecontent.Contains("$schema"))
                        {
                            schema = filecontent.Substring(filecontent.ToLower().IndexOf("schemas"));
                            schema = schema.Substring(0, schema.IndexOf("\"")).Replace("\\\\", "\\");
                        }
                        if ((schema != "") && (File.Exists(Path.Combine(AppDataPath, schema))))
                        {
                            try
                            {
                                String      schema_file = File.ReadAllText(Path.Combine(AppDataPath, schema));
                                JsonSchema4 JSchema     = JsonSchema4.FromData(schema_file);
                                foreach (ValidationError ve in JSchema.Validate(filecontent))
                                {
                                    jErrors.Add(String.Format("Error in {0} > {1}: {2}", ve.Path, ve.Property, ve.Kind));
                                }

                                errors = jErrors.Count() > 0;
                            }
                            catch (Exception exc)
                            {
                                jErrors.Add(String.Format("Error in json file '{0}': {1}", file_name, exc.Message));
                                canWrite = false;
                            }
                        }
                    }
                    return((!errors) ? JProc : new JObject());
                }
            }
            catch (Exception exc)
            {
                if (file_must_exists)
                {
                    jErrors.Add(String.Format("Error in '{0}': {1}", file_name, exc.Message));
                    canWrite = false;
                }
            }

            if (canWrite)
            {
                return(new JObject());
            }
            else
            {
                jErrors.Add(String.Format("Program file not found: {0}", file_name));
                return(null);
            }
        }
Example #4
0
        public int UpdateAll_Tobk1(Tobk request)
        {
            int Result = -1;

            try
            {
                using (var db = DbConnectionFactory.OpenDbConnection())
                {
                    if (request.UpdateAllString != null && request.UpdateAllString != "")
                    {
                        JArray ja = (JArray)JsonConvert.DeserializeObject(request.UpdateAllString);
                        if (ja != null)
                        {
                            for (int i = 0; i < ja.Count(); i++)
                            {
                                if (ja[i]["TableName"] == null || ja[i]["TableName"].ToString() == "")
                                {
                                    continue;
                                }
                                string strKey          = ja[i]["Key"].ToString();
                                string strTableName    = ja[i]["TableName"].ToString();
                                string strRemark       = "";
                                string strStatusCode   = "";
                                string strOnBehalfName = "";
                                if (ja[i]["OnBehalfName"] != null || ja[i]["OnBehalfName"].ToString() != "")
                                {
                                    strOnBehalfName = ja[i]["OnBehalfName"].ToString();
                                }
                                if (ja[i]["Remark"] != null || ja[i]["Remark"].ToString() != "")
                                {
                                    strRemark = ja[i]["Remark"].ToString();
                                }
                                if (ja[i]["StatusCode"] != null || ja[i]["StatusCode"].ToString() != "")
                                {
                                    strStatusCode = ja[i]["StatusCode"].ToString();
                                }
                                if (strStatusCode.ToLower() == "cancel")
                                {
                                    string strJobNo = "";
                                    if (ja[i]["JobNo"] != null || ja[i]["JobNo"].ToString() != "")
                                    {
                                        strJobNo = ja[i]["JobNo"].ToString();
                                    }
                                    if (strJobNo != "")
                                    {
                                        int          intMaxLineItemNo = 1;
                                        List <Jmjm3> list1            = db.Select <Jmjm3>("Select Max(LineItemNo) LineItemNo from Jmjm3 Where JobNo = " + Modfunction.SQLSafeValue(strJobNo));
                                        if (list1 != null)
                                        {
                                            if (list1[0].LineItemNo > 0)
                                            {
                                                intMaxLineItemNo = list1[0].LineItemNo + 1;
                                            }
                                        }
                                        db.Insert(new Jmjm3
                                        {
                                            JobNo          = strJobNo,
                                            DateTime       = DateTime.Now,
                                            UpdateDatetime = DateTime.Now,
                                            LineItemNo     = intMaxLineItemNo,
                                            AutoFlag       = "N",
                                            StatusCode     = "CANCEL",
                                            UpdateBy       = ja[0]["DriverCode"] == null ? "" : Modfunction.SQLSafe(ja[0]["DriverCode"].ToString()),
                                            Remark         = Modfunction.SQLSafe(strRemark),
                                            Description    = ja[0]["CancelDescription"] == null ? "" : Modfunction.SQLSafe(ja[0]["CancelDescription"].ToString())
                                        });
                                        db.Update(strTableName,
                                                  " Note = '" + Modfunction.SQLSafe(strRemark) + "', OnBehalfName = '" + Modfunction.SQLSafe(strOnBehalfName) + "'",
                                                  " BookingNo='" + strKey + "'");
                                    }
                                }
                                else
                                {
                                    db.Update(strTableName,
                                              " Note = '" + Modfunction.SQLSafe(strRemark) + "',StatusCode = '" + strStatusCode + "', OnBehalfName = '" + Modfunction.SQLSafe(strOnBehalfName) + "'",
                                              " BookingNo='" + strKey + "'");
                                }
                            }
                            Result = 1;
                        }
                    }
                }
            }
            catch { throw; }
            return(Result);
        }
Example #5
0
        public void loadData()
        {
            if (Login.jsonResult != null)
            {
                Cursor.Current = Cursors.WaitCursor;
                AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
                string token = "";
                foreach (var x in Login.jsonResult)
                {
                    if (x.Key.Equals("token"))
                    {
                        token = x.Value.ToString();
                    }
                }
                if (!token.Equals(""))
                {
                    var client = new RestClient(utilityc.URL);
                    client.Timeout = -1;
                    //string branch = "A1-S";
                    var request = new RestRequest("/api/report/customer/sales_summary");
                    request.AddHeader("Authorization", "Bearer " + token);
                    var     response = client.Execute(request);
                    JObject jObject  = new JObject();
                    if (response.ErrorMessage == null)
                    {
                        if (response.Content.ToString().Substring(0, 1).Equals("{"))
                        {
                            jObject = JObject.Parse(response.Content.ToString());
                            dgv.Rows.Clear();
                            bool isSuccess = false;
                            foreach (var x in jObject)
                            {
                                if (x.Key.Equals("success"))
                                {
                                    isSuccess = Convert.ToBoolean(x.Value.ToString());
                                }
                            }
                            if (isSuccess)
                            {
                                foreach (var x in jObject)
                                {
                                    if (x.Key.Equals("data"))
                                    {
                                        if (x.Value.ToString() != "[]")
                                        {
                                            JArray jsonArray = JArray.Parse(x.Value.ToString());
                                            for (int i = 0; i < jsonArray.Count(); i++)
                                            {
                                                JObject data         = JObject.Parse(jsonArray[i].ToString());
                                                double  balance      = 0.00;
                                                string  customerCode = "";
                                                foreach (var q in data)
                                                {
                                                    if (q.Key.Equals("cust_code"))
                                                    {
                                                        customerCode = q.Value.ToString();
                                                        auto.Add(q.Value.ToString());
                                                    }
                                                    else if (q.Key.Equals("balance"))
                                                    {
                                                        balance = Convert.ToDouble(q.Value.ToString());
                                                    }
                                                }

                                                if (!string.IsNullOrEmpty(txtSearch.Text.ToString().Trim()))
                                                {
                                                    if (txtSearch.Text.ToString().Trim().ToLower().Contains(customerCode.ToLower()))
                                                    {
                                                        dgv.Rows.Add(customerCode, Convert.ToDecimal(string.Format("{0:0.00}", balance)));
                                                        break;
                                                    }
                                                }
                                                else
                                                {
                                                    dgv.Rows.Add(customerCode, Convert.ToDecimal(string.Format("{0:0.00}", balance)));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string msg = "No message response found";
                                foreach (var x in jObject)
                                {
                                    if (x.Key.Equals("message"))
                                    {
                                        msg = x.Value.ToString();
                                    }
                                }
                                MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                        else
                        {
                            MessageBox.Show(response.Content.ToString(), "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        MessageBox.Show(response.ErrorMessage, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                txtSearch.AutoCompleteCustomSource = auto;
                Cursor.Current = Cursors.Default;
            }
        }
Example #6
0
        public void loadData()
        {
            if (Login.jsonResult != null)
            {
                Cursor.Current = Cursors.WaitCursor;
                string token = "";
                foreach (var x in Login.jsonResult)
                {
                    if (x.Key.Equals("token"))
                    {
                        token = x.Value.ToString();
                    }
                }
                if (!token.Equals(""))
                {
                    AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
                    dgv.Rows.Clear();
                    var client = new RestClient(utilityc.URL);
                    client.Timeout = -1;
                    var request = new RestRequest("/api/inv/warehouse/report?branch=" + findCode(cmbBranches.Text, "Branch") + "&from_date=" + dtDate.Value.ToString("yyyy-MM-dd") + "&to_date=" + dtDate.Value.ToString("yyyy-MM-dd") + "&whse=" + findCode(cmbWarehouse.Text, "Warehouse"));
                    //Console.WriteLine("/api/inv/warehouse/report?branch=" + cmbBranches.Text + "&from_date=" + dtDate.Value.ToString("yyyy-MM-dd") + "&to_date=" + dtDate.Value.ToString("yyyy-MM-dd") + "&whse=" + cmbWarehouse.Text);
                    request.AddHeader("Authorization", "Bearer " + token);
                    var     response = client.Execute(request);
                    JObject jObject  = new JObject();
                    jObject = JObject.Parse(response.Content.ToString());
                    //Console.WriteLine(jObject);
                    bool isSuccess = false;
                    foreach (var x in jObject)
                    {
                        if (x.Key.Equals("success"))
                        {
                            isSuccess = Convert.ToBoolean(x.Value.ToString());
                            break;
                        }
                    }
                    if (isSuccess)
                    {
                        foreach (var x in jObject)
                        {
                            if (x.Key.Equals("data"))
                            {
                                if (x.Value.ToString() != "[]")
                                {
                                    JArray jsonArray = JArray.Parse(x.Value.ToString());
                                    for (int i = 0; i < jsonArray.Count(); i++)
                                    {
                                        JObject data = JObject.Parse(jsonArray[i].ToString());
                                        string  itemCode = "";
                                        double  beginning = 0.00, received = 0.00, transferred = 0.00, sold = 0.00, available = 0.00, adjin = 0.00, adjout = 0.00, pullout = 0.00, transferIn = 0.00, totalIn = 0.00, totalOut = 0.00;
                                        foreach (var q in data)
                                        {
                                            if (q.Key.Equals("item_code"))
                                            {
                                                itemCode = q.Value.ToString();
                                                auto.Add(itemCode);
                                            }
                                            else if (q.Key.Equals("Beginning"))
                                            {
                                                beginning = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("Received"))
                                            {
                                                received = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("TransferIn"))
                                            {
                                                transferIn = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("TotalIn"))
                                            {
                                                totalIn = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("Transferred"))
                                            {
                                                transferred = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("Sold"))
                                            {
                                                sold = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("TotalOut"))
                                            {
                                                totalOut = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("Available"))
                                            {
                                                available = Convert.ToDouble(q.Value.ToString());
                                            }

                                            else if (q.Key.Equals("AdjIn"))
                                            {
                                                adjin = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("AdjOut"))
                                            {
                                                adjout = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("PullOut"))
                                            {
                                                pullout = Convert.ToDouble(q.Value.ToString());
                                            }
                                        }
                                        if (!string.IsNullOrEmpty(txtSearch.Text.ToString().Trim()))
                                        {
                                            if (txtSearch.Text.ToString().Trim().Contains(itemCode))
                                            {
                                                dgv.Rows.Add(itemCode, Convert.ToDecimal(string.Format("{0:0.00}", beginning)), Convert.ToDecimal(string.Format("{0:0.00}", received)), Convert.ToDecimal(string.Format("{0:0.00}", transferIn)), Convert.ToDecimal(string.Format("{0:0.00}", adjin)), Convert.ToDecimal(string.Format("{0:0.00}", totalIn)), Convert.ToDecimal(string.Format("{0:0.00}", transferred)), Convert.ToDecimal(string.Format("{0:0.00}", adjout)), Convert.ToDecimal(string.Format("{0:0.00}", pullout)), Convert.ToDecimal(string.Format("{0:0.00}", sold)), Convert.ToDecimal(string.Format("{0:0.00}", totalOut)), Convert.ToDecimal(string.Format("{0:0.00}", available)));
                                            }
                                        }
                                        else
                                        {
                                            dgv.Rows.Add(itemCode, Convert.ToDecimal(string.Format("{0:0.00}", beginning)), Convert.ToDecimal(string.Format("{0:0.00}", received)), Convert.ToDecimal(string.Format("{0:0.00}", transferIn)), Convert.ToDecimal(string.Format("{0:0.00}", adjin)), Convert.ToDecimal(string.Format("{0:0.00}", totalIn)), Convert.ToDecimal(string.Format("{0:0.00}", transferred)), Convert.ToDecimal(string.Format("{0:0.00}", adjout)), Convert.ToDecimal(string.Format("{0:0.00}", pullout)), Convert.ToDecimal(string.Format("{0:0.00}", sold)), Convert.ToDecimal(string.Format("{0:0.00}", totalOut)), Convert.ToDecimal(string.Format("{0:0.00}", available)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string msg = "No message response found";
                        foreach (var x in jObject)
                        {
                            if (x.Key.Equals("message"))
                            {
                                msg = x.Value.ToString();
                            }
                        }
                        if (msg.Equals("Token is invalid"))
                        {
                            MessageBox.Show("Your login session is expired. Please login again", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    txtSearch.AutoCompleteCustomSource = auto;
                }
                Cursor.Current = Cursors.Default;
            }
            colors();
        }
Example #7
0
        public void CreateJTokenTree()
        {
            JObject o =
                new JObject(
                    new JProperty("Test1", "Test1Value"),
                    new JProperty("Test2", "Test2Value"),
                    new JProperty("Test3", "Test3Value"),
                    new JProperty("Test4", null)
                    );

            Assert.AreEqual(4, o.Properties().Count());

            Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

            JArray a =
                new JArray(
                    o,
                    new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
                    55,
                    new JArray(
                        "1",
                        2,
                        3.0,
                        new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
                        ),
                    new JConstructor(
                        "ConstructorName",
                        "param1",
                        2,
                        3.0
                        )
                    );

            Assert.AreEqual(5, a.Count());
            Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""\/Date(971136000000)\/"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""\/Date(-62030076711000)\/""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
        }
    public void Replace()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      a[0].Replace(new JValue(int.MaxValue));
      Assert.AreEqual(int.MaxValue, (int)a[0]);
      Assert.AreEqual(4, a.Count());

      a[1][0].Replace(new JValue("Test"));
      Assert.AreEqual("Test", (string)a[1][0]);

      a[2].Replace(new JValue(int.MaxValue));
      Assert.AreEqual(int.MaxValue, (int)a[2]);
      Assert.AreEqual(4, a.Count());

      Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
    }
        public async Task <string> UpdateAttributes([FromBody]   JObject json, int productId)
        {
            JArray product_subtype_ids = new JArray();
            string user_id             = await _LoginHelper.GetLoginUserId();

            List <Fabric> _fabrics = new List <Fabric>();
            JObject       product  = new JObject();

            product.Add("size_and_fit_id", json.Value <string>("size_fit"));
            product.Add("product_retail", json.Value <string>("product_retail"));
            product.Add("product_name", json.Value <string>("product_name"));
            product.Add("product_cost", json.Value <string>("product_cost"));
            product.Add("product_discount", json.Value <string>("product_discount"));
            product.Add("product_detail_1", json.Value <string>("product_detail_1"));
            product.Add("product_detail_2", json.Value <string>("product_detail_2"));
            product.Add("product_detail_3", json.Value <string>("product_detail_3"));
            product.Add("product_detail_4", json.Value <string>("product_detail_4"));
            product.Add("is_ready", json.Value <bool>("is_ready"));
            product.Add("pairProductIds", json.Value <string>("pairProductIds"));
            product.Add("RemovePairWithProductIds", json.Value <string>("RemovePairWithProductIds"));
            product.Add("otherColorsProductIds", json.Value <string>("otherColorsProductIds"));
            product.Add("RemoveOtherColorProductIds", json.Value <string>("RemoveOtherColorProductIds"));


            product.Add("photoshootStatus", json.Value <string>("photoshootStatus"));
            product.Add("photoshootStatusOld", json.Value <string>("photoshootStatusOld"));

            product.Add("updated_by", user_id);
            product.Add("updated_at", _common.GetTimeStemp());

            _fabrics = json.Value <JArray>("fabricArray").ToObject <List <Fabric> >();


            string returnStatus = await _BadgerApiHelper.GenericPutAsyncString <string>(product.ToString(Formatting.None), "/Product/UpdateAttributes/" + productId.ToString());

            if (json["product_subtype_ids"] != null)
            {
                product_subtype_ids = (JArray)json["product_subtype_ids"];
            }
            for (int i = 0; i < product_subtype_ids.Count(); i++)
            {
                string category_id = product_subtype_ids[i].Value <string>("category_id");
                string action      = product_subtype_ids[i].Value <string>("action");

                JObject productCategories = new JObject();
                productCategories.Add("product_id", productId);
                productCategories.Add("category_id", category_id);
                productCategories.Add("action", action);
                productCategories.Add("created_by", user_id);
                productCategories.Add("created_at", _common.GetTimeStemp());

                var temp_product_category_id = await _BadgerApiHelper.GenericPostAsyncString <String>(productCategories.ToString(Formatting.None), "/product/UpdateProductCategory");
            }
            string sku         = "";
            string tagAddedIds = json.Value <string>("tagAddedIds");

            if (tagAddedIds != "")
            {
                int countComma = tagAddedIds.Count(c => c == ',');
                if (countComma > 0)
                {
                    var ids = tagAddedIds.Split(",");
                    foreach (var tagId in ids)
                    {
                        JObject product_attr = new JObject();
                        Int16   attribute_id = Int16.Parse(tagId);

                        product_attr.Add("attribute_id", attribute_id);
                        product_attr.Add("product_id", productId);
                        product_attr.Add("value", "");

                        product_attr.Add("created_by", user_id);
                        product_attr.Add("created_at", _common.GetTimeStemp());
                        String attr_value_id = await _BadgerApiHelper.GenericPostAsyncString <String>(product_attr.ToString(Formatting.None), "/attributevalues/create");


                        JObject product_attr_value = new JObject();
                        product_attr_value.Add("product_id", productId);
                        product_attr_value.Add("attribute_id", attribute_id);
                        product_attr_value.Add("value_id", attr_value_id);

                        product_attr_value.Add("created_by", user_id);
                        // product_attr_value.Add("created_at", _common.GetTimeStemp()); need to create in DB
                        String product_attribute_value_id = await _BadgerApiHelper.GenericPostAsyncString <String>(product_attr_value.ToString(Formatting.None), "/product/createAttributesValues");

                        JObject product_attribute_obj = new JObject();
                        product_attribute_obj.Add("product_id", productId);
                        product_attribute_obj.Add("attribute_id", attribute_id);
                        product_attribute_obj.Add("value_id", attr_value_id);
                        product_attribute_obj.Add("sku", sku);

                        product_attribute_obj.Add("created_by", user_id);
                        //product_attribute_obj.Add("created_at", _common.GetTimeStemp()); need to create in DB
                        String product_attribute_id = await _BadgerApiHelper.GenericPostAsyncString <String>(product_attribute_obj.ToString(Formatting.None), "/product/createProductAttribute");
                    }
                }
                else
                {
                }
            }
            if (_fabrics.Count() > 0)
            {
                await _ProductHelper.UpdateFabric(_fabrics, int.Parse(user_id));
            }



            if (json.Value <string>("photoshootStatus") != json.Value <string>("photoshootStatusOld"))
            {
                JObject photoshoot = new JObject();
                photoshoot.Add("product_shoot_status_id", json.Value <string>("photoshootStatus"));
                photoshoot.Add("updated_by", user_id);
                photoshoot.Add("updated_at", _common.GetTimeStemp());
                await _BadgerApiHelper.GenericPutAsyncString <string>(photoshoot.ToString(Formatting.None), "/Photoshoots/UpdatePhotoshootProductStatus/" + productId.ToString());
            }

            if (json.Value <string>("oldInternalNotes") != json.Value <string>("internalNotes"))
            {
                JObject productNote = new JObject();
                productNote.Add("ref_id", productId);
                productNote.Add("note", json.Value <string>("internalNotes"));
                productNote.Add("created_by", Int32.Parse(user_id));

                await _BadgerApiHelper.GenericPostAsyncString <String>(productNote.ToString(Formatting.None), "/product/notecreate");
            }
            return("success");
        }
Example #10
0
        public async Task <String> CreateNewStyle([FromBody]   JObject json)
        {
            int user_id = Int32.Parse(await _ILoginHelper.GetLoginUserId());

            String product_id = "";

            JObject product       = new JObject();
            JObject vendorProduct = new JObject();

            JObject allData = JObject.Parse(json.ToString());

            JArray vendor_style_sku_data = new JArray();
            JArray product_subtype_ids   = new JArray();

            if (allData["vendor_style_sku"] != null)
            {
                vendor_style_sku_data = (JArray)allData["vendor_style_sku"];
            }

            if (allData["product_subtype_ids"] != null)
            {
                product_subtype_ids = (JArray)allData["product_subtype_ids"];
            }



            Int32  product_id_current = json.Value <Int32>("product_id");
            Int32  po_id            = json.Value <Int32>("po_id");
            Int32  vendor_id        = json.Value <Int32>("vendor_id");
            string product_name     = json.Value <string>("product_name");
            bool   IsLineItemExists = json.Value <bool>("IsLineItemExists");
            bool   UpdateVendorType = json.Value <bool>("UpdateVendorType");
            string first_sku_family = json.Value <string>("sku_family");


            string vendor_color_name  = json.Value <string>("vendor_color_name");
            string product_cost       = json.Value <string>("product_cost");
            string product_name_no    = json.Value <string>("product_name_no");
            string product_color_code = json.Value <string>("product_color_code");

            string product_retail     = json.Value <string>("product_retail");
            string product_url_handle = product_name.Replace(' ', '-').ToLower();
            string product_type_id    = json.Value <string>("product_type_id");



            //default values FIXED hardcoded

            int    size_and_fit_id     = 0;
            int    wash_type_id        = 0;
            int    product_discount    = 20;
            int    published_status    = 0;
            int    is_on_site_status   = 0;
            String attr_value_id_color = "15"; // blank entry for color
            int    color_attribute_id  = 1;    // color attribute id


            // item insert default values
            string item_status_id = "1"; // Not Recieved

            int ra_status   = 0;
            int barcode     = 0;
            int slot_number = 0;
            int bag_code    = 0;



            product.Add("vendor_id", vendor_id);
            product.Add("product_name", product_name);
            product.Add("vendor_color_name", vendor_color_name);
            product.Add("product_cost", product_cost);
            product.Add("product_retail", product_retail);
            product.Add("product_url_handle", product_url_handle);
            product.Add("product_type_id", product_type_id);

            product.Add("product_description", "");
            product.Add("sku_family", first_sku_family);
            product.Add("size_and_fit_id", size_and_fit_id);
            product.Add("wash_type_id", wash_type_id);
            product.Add("product_discount", product_discount);
            product.Add("published_status", published_status);
            product.Add("is_on_site_status", is_on_site_status);

            product.Add("created_by", user_id);
            product.Add("created_at", _common.GetTimeStemp());
            product.Add("po_id", po_id.ToString());


            vendorProduct.Add("vendor_id", vendor_id);
            vendorProduct.Add("vendor_color_code", product_color_code);
            vendorProduct.Add("vendor_color_name", vendor_color_name);
            vendorProduct.Add("vendor_product_code", product_name_no);
            vendorProduct.Add("vendor_product_name", product_name);
            vendorProduct.Add("created_by", user_id);
            vendorProduct.Add("created_at", _common.GetTimeStemp());


            if (product_id_current > 0)
            {
                product_id = product_id_current.ToString(); //update on selected product id

                // add new product in product table
                var a = await _BadgerApiHelper.GenericPutAsyncString <String>(product.ToString(Formatting.None), "/product/updatespecific/" + product_id);

                if (!string.IsNullOrEmpty(product_id))
                {   //update vendor product
                    vendorProduct.Add("product_id", Convert.ToInt64(product_id));
                    var result = await _BadgerApiHelper.GenericPutAsyncString <String>(vendorProduct.ToString(Formatting.None), "/vendor/vendorproductUpdatespecific");
                }
            }
            else
            {
                try
                {
                    // add new product in product table
                    product_id = await _BadgerApiHelper.GenericPostAsyncString <String>(product.ToString(Formatting.None), "/product/create");

                    if (!string.IsNullOrEmpty(product_id))
                    {
                        vendorProduct.Add("product_id", Convert.ToInt64(product_id));
                        // add new vendor product in vendor product table
                        var temp_product_id = await _BadgerApiHelper.GenericPostAsyncString <String>(vendorProduct.ToString(Formatting.None), "/vendor/createvendorproduct");
                    }
                }
                catch (Exception ex)
                {
                    var logger = _loggerFactory.CreateLogger("internal_error_log");
                    logger.LogInformation("Problem happened in making new Product, no product id genrated ");
                }
            }

            if (UpdateVendorType)
            {
                JObject _vendor = new JObject();
                _vendor.Add("vendor_type", 3);
                _vendor.Add("updated_by", user_id);
                _vendor.Add("updated_at", _common.GetTimeStemp());

                String vendorStatus = await _BadgerApiHelper.GenericPutAsyncString <String>(_vendor.ToString(Formatting.None), "/vendor/updatespecific/" + vendor_id.ToString());
            }

            if (Int32.Parse(product_id) > 1)
            {
                JObject productPhotoshoot = new JObject();
                productPhotoshoot.Add("photoshoot_id", 0);
                productPhotoshoot.Add("product_id", product_id);
                productPhotoshoot.Add("product_shoot_status_id", 0);
                productPhotoshoot.Add("updated_by", 0);
                productPhotoshoot.Add("updated_at", 0);
                productPhotoshoot.Add("created_by", user_id);
                productPhotoshoot.Add("created_at", _common.GetTimeStemp());
                await _BadgerApiHelper.GenericPostAsyncString <String>(productPhotoshoot.ToString(Formatting.None), "/photoshoots/addNewPhotoshootProduct");

                String product_attribute_value_id_color = await _productHelper.createProductAttributesValuesAsync(Int32.Parse(product_id), color_attribute_id, int.Parse(attr_value_id_color));

                String product_attribute_id_color = await _productHelper.createProductAttributesAsync(Int32.Parse(product_id), color_attribute_id, "", product_attribute_value_id_color);



                JObject used_in_obj = new JObject();
                used_in_obj.Add("product_id", product_id);
                used_in_obj.Add("po_id", po_id);
                used_in_obj.Add("created_at", _common.GetTimeStemp());
                String used_in_id = await _BadgerApiHelper.GenericPostAsyncString <String>(used_in_obj.ToString(Formatting.None), "/product/createUsedIn");
            }

            for (int i = 0; i < product_subtype_ids.Count(); i++)
            {
                string category_id = product_subtype_ids[i].Value <string>("category_id");
                string action      = product_subtype_ids[i].Value <string>("action");

                JObject productCategories = new JObject();
                productCategories.Add("product_id", product_id);
                productCategories.Add("category_id", category_id);
                productCategories.Add("action", action);
                productCategories.Add("created_by", user_id);
                productCategories.Add("created_at", _common.GetTimeStemp());

                var temp_product_category_id = await _BadgerApiHelper.GenericPostAsyncString <String>(productCategories.ToString(Formatting.None), "/product/UpdateProductCategory");
            }

            //Checking If line items need to be deleted and is it a possibility to delete line items , if not - stop everything and return
            if (IsLineItemExists)
            {
                var OldSkuList = vendor_style_sku_data.Where(x => x.Value <bool>("IsNewSku") == false && x.Value <int>("style_qty") < x.Value <int>("original_qty")).ToList();
                for (int i = 0; i < OldSkuList.Count; i++)
                {
                    string sku       = OldSkuList[i].Value <string>("style_sku");
                    int    style_qty = vendor_style_sku_data[i].Value <int>("style_qty");
                    var    itemCount = await _BadgerApiHelper.GenericGetsAsync("/product/getitems/" + po_id + "/" + sku);

                    if (int.Parse(itemCount) < style_qty)
                    {
                        // -3 for indicating error in javascript : cannot decrease quantity of sku.
                        return("-3");
                    }
                }
            }
            else
            {
                var newSkus = vendor_style_sku_data.Where(x => x.Value <bool>("IsNewSku") == true).ToList();
                for (int i = 0; i < newSkus.Count; i++)
                {
                    string sku = newSkus[i].Value <string>("style_sku");

                    bool SkuFound = await _BadgerApiHelper.GenericGetAsync <Boolean>("/Sku/checkskuexist/" + sku);

                    if (SkuFound)
                    {
                        // -4 for indicating error in javascript : sku already exists.
                        return("-4");
                    }
                }
            }


            for (int i = 0; i < vendor_style_sku_data.Count; i++)
            {
                string style_vendor_size = vendor_style_sku_data[i].Value <string>("style_vendor_size");
                string style_size        = vendor_style_sku_data[i].Value <string>("style_size");
                string style_qty         = vendor_style_sku_data[i].Value <string>("style_qty");
                string sku          = vendor_style_sku_data[i].Value <string>("style_sku");
                bool   IsNewSku     = vendor_style_sku_data[i].Value <bool>("IsNewSku");
                int    original_qty = vendor_style_sku_data[i].Value <int>("original_qty");

                string sku_family = json.Value <string>("sku_family");


                Int16 attribute_id = Int16.Parse(style_size);

                String attr_value_id = await _productHelper.createProductAttributesAsync(Int32.Parse(product_id), attribute_id, style_vendor_size, user_id, _common.GetTimeStemp());

                String product_attribute_value_id = await _productHelper.createProductAttributesValuesAsync(Int32.Parse(product_id), attribute_id, int.Parse(attr_value_id));

                String product_attribute_id = await _productHelper.createProductAttributesAsync(Int32.Parse(product_id), attribute_id, sku, attr_value_id);


                //// size attribute ends here



                JObject Sku_obj = new JObject();
                Sku_obj.Add("sku", sku);
                Sku_obj.Add("vendor_id", vendor_id);
                Sku_obj.Add("product_id", Int32.Parse(product_id));
                String sku_id = await _BadgerApiHelper.GenericPostAsyncString <String>(Sku_obj.ToString(Formatting.None), "/sku/create");

                JObject lineitem_obj = new JObject();
                lineitem_obj.Add("po_id", po_id);
                lineitem_obj.Add("vendor_id", vendor_id);
                lineitem_obj.Add("sku", sku);
                lineitem_obj.Add("product_id", Int32.Parse(product_id));
                lineitem_obj.Add("line_item_cost", product_cost);
                lineitem_obj.Add("line_item_retail", product_retail);
                lineitem_obj.Add("line_item_type_id", product_type_id);
                lineitem_obj.Add("line_item_ordered_quantity", style_qty);
                lineitem_obj.Add("IsQtyIncreased", int.Parse(style_qty) < original_qty ? false : true);
                lineitem_obj.Add("originalQty", original_qty);

                JObject items = new JObject();
                items.Add("barcode", barcode);               // 0
                items.Add("slot_number", slot_number);       // 0
                items.Add("bag_code", bag_code);             // 0
                items.Add("item_status_id", item_status_id); // 1
                items.Add("ra_status", ra_status);           // 0
                items.Add("sku", sku);
                items.Add("sku_id", sku_id);
                items.Add("sku_family", sku_family);
                items.Add("product_id", product_id);
                items.Add("vendor_id", vendor_id);
                items.Add("PO_id", po_id);
                items.Add("original_qty", original_qty);


                if (!IsLineItemExists || IsNewSku)
                {
                    //for item when they are created
                    items.Add("created_at", _common.GetTimeStemp());
                    items.Add("created_by", user_id);
                    //for po line item when they are created
                    lineitem_obj.Add("created_by", user_id);
                    lineitem_obj.Add("created_at", _common.GetTimeStemp());

                    String item_id = await _BadgerApiHelper.GenericPostAsyncString <String>(items.ToString(Formatting.None), "/product/createitems/" + style_qty);

                    String line_item_id = await _BadgerApiHelper.GenericPostAsyncString <String>(lineitem_obj.ToString(Formatting.None), "/product/createLineitems");
                }
                else
                {
                    //for item when they are updated
                    items.Add("updated_at", _common.GetTimeStemp());
                    items.Add("updated_by", user_id);
                    //for po line item when they are updated
                    lineitem_obj.Add("updated_by", user_id);
                    lineitem_obj.Add("updated_at", _common.GetTimeStemp());

                    int _style_qty = int.Parse(style_qty);
                    if (original_qty != _style_qty)
                    {
                        //Adding new items in existing Line items
                        String item_id = await _BadgerApiHelper.GenericPostAsyncString <String>(items.ToString(Formatting.None), "/product/updateitems/" + style_qty);

                        String line_item_id = await _BadgerApiHelper.GenericPostAsyncString <String>(lineitem_obj.ToString(Formatting.None), "/product/updateLineitems");
                    }
                }
            }
            return(product_id);
        }
        public void PrintSlip(object sender, PrintPageEventArgs e)
        {
            float yPos = 40;//2018.04.05 출력 위치 조정 20->40

            try
            {
                //2018.04.03 원본데이터 출력
                Encoding enc = Encoding.Default;
                //출력데이터 이용 m_slipData
                //Image head_logo = Bitmap.FromFile(Constants.filePath_LOGO);

                //Image head_logo_Resize = new Bitmap(head_logo, new Size(head_logo.Width * 50 / 100, head_logo.Height * 50 / 100));

                //e.Graphics.DrawImage((Image)head_logo_Resize, new Rectangle(nStartPoint, (int)yPos, head_logo_Resize.Width, head_logo_Resize.Height));
                //yPos += head_logo_Resize.Height;
                //yPos = PrintImg(e, head_logo_Resize, yPos, StringAlignment.Center);

                //StringAlignment.Near   - 왼쪽
                //StringAlignment.Center - 가운데
                //StringAlignment.Far    - 오른쪽

                yPos = PrintText(e, "        GLOBAL         ", yPos, StringAlignment.Near, false, false, 15);
                yPos = PrintText(e, "                   TAX FREE", yPos, StringAlignment.Near, true, true, 15);

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);
                yPos = PrintText(e, "숙 박 용 역", yPos, StringAlignment.Center, true, true, 15);
                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);


                //strFormat.Alignment = StringAlignment.Center;//왼쪽
                //strFont = new Font(m_Font, nNomalSize, FontStyle.Bold);
                //rect = new Rectangle(nStartPoint, (int)yPos, nPageWidthHalf, strFont.Height);
                //e.Graphics.DrawString("----------------------------------------------------", strFont, Brushes.Black, rect, strFormat);
                //e.Graphics.DrawRectangle(Pens.White, rect);
                //yPos += strFont.Height;


                yPos = PrintText(e, "Hotel Tax Refund", yPos, StringAlignment.Center);
                yPos = PrintText(e, "This Document is authorized by Korea NTS", yPos, StringAlignment.Center);
                yPos = PrintText(e, "국세청장이 인정한 서식임", yPos, StringAlignment.Center);

                Image qrImg = Bitmap.FromFile(Constants.filePath_Combine);
                //Image qrImg_Resize = new Bitmap(qrImg, new Size(qrImg.Width * 60 / 100, qrImg.Height * 60 / 100));
                yPos = PrintImg(e, qrImg, yPos, StringAlignment.Center);

                qrImg.Dispose();

                yPos = PrintText(e, "[email protected]            www.global-taxfree.com", yPos, StringAlignment.Center, true, true, nSmallSize);
                yPos = PrintText(e, "Contact Us : +82 2 518 0837", yPos, StringAlignment.Near, false);
                yPos = PrintText(e, "단말기 ID " + slipData["tml_id"].ToString(), yPos, StringAlignment.Near, false);

                string strBuySerialNo = slipData["buy_serial_no"].ToString();
                yPos = PrintText(e, "구매일련번호", yPos, StringAlignment.Near, false, false);

                yPos = PrintText(e, strBuySerialNo.Substring(0, 2)
                                 + "-" + strBuySerialNo.Substring(2, 5)
                                 + "-" + strBuySerialNo.Substring(7, 5)
                                 + "-" + strBuySerialNo.Substring(12, 2)
                                 + "-" + strBuySerialNo.Substring(14), yPos, StringAlignment.Far, false);

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);
                yPos = PrintText(e, "호텔/Hotel", yPos, StringAlignment.Near, true);

                yPos = PrintText(e, "사업자번호 ", yPos, StringAlignment.Near, false, false);
                //yPos = PrintText(e, slipData["biz_permit_no"].ToString().PadLeft(nPaddingLen_big - 11, ' '), yPos, StringAlignment.Far);
                String strBizPermitNo = slipData["biz_permit_no"].ToString();
                strBizPermitNo = strBizPermitNo.Substring(0, 3) + "-" + strBizPermitNo.Substring(3, 2) + "-" + strBizPermitNo.Substring(5);
                yPos           = PrintText(e, strBizPermitNo, yPos, StringAlignment.Far);

                yPos = PrintText(e, "관광사업등록번호", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, slipData["company_reg_no"].ToString(), yPos, StringAlignment.Far);

                yPos = PrintText(e, "상호 ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, slipData["shop_name"] != null ? slipData["shop_name"].ToString() : " ", yPos, StringAlignment.Far);

                yPos = PrintText(e, "대표자 ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, slipData["ceo_name"] != null ? slipData["ceo_name"].ToString()  : " ", yPos, StringAlignment.Far);

                yPos = PrintText(e, "주소 ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, slipData["shop_addr"] != null ? slipData["shop_addr"].ToString() : " ", yPos, StringAlignment.Far);

                yPos = PrintText(e, "연락처", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, slipData["shop_phone"] != null ? slipData["shop_phone"].ToString() : " ", yPos, StringAlignment.Far);

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);
                string strDate = slipData["sale_date"].ToString();
                strDate = strDate.Substring(0, 4) + "-" + strDate.Substring(4, 2) + "-" + strDate.Substring(6, 2);

                yPos = PrintText(e, "Date of sale ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, strDate, yPos, StringAlignment.Far);


                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);
                yPos = PrintText(e, "숙박내역 / Description of Accommodation", yPos, StringAlignment.Near, true);

                if (slipData["buyList"] != null)
                {
                    if (slipData["buyList"] is JArray)
                    {
                        JArray arrBuyData = (JArray)slipData["buyList"];
                        for (int i = 0; i < arrBuyData.Count(); i++)
                        {
                            yPos = PrintText(e, (i + 1) + ". " + arrBuyData[i]["goods_name"].ToString(), yPos, StringAlignment.Near, false, false);
                            yPos = PrintText(e, (arrBuyData[i]["qty"].ToString() + " Nights"), yPos, StringAlignment.Far);

                            yPos = PrintText(e, "  공급가격 Payment(Inc.Tax)", yPos, StringAlignment.Near, false, false);
                            yPos = PrintText(e, string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:n0}", Int64.Parse(arrBuyData[i]["sales_amount"].ToString())), yPos, StringAlignment.Far);

                            yPos = PrintText(e, "  부가세    V.A.T ", yPos, StringAlignment.Near, false, false);
                            yPos = PrintText(e, string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:n0}", Int64.Parse(arrBuyData[i]["tax_amount"].ToString())), yPos, StringAlignment.Far);
                        }
                    }
                }

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);
                yPos = PrintText(e, "합계        Total ", yPos, StringAlignment.Near, true);

                yPos = PrintText(e, "공급가격   Payment(Inc.Tax) ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:n0}", Int64.Parse(slipData["sales_amount"].ToString())), yPos, StringAlignment.Far);

                yPos = PrintText(e, "부가세      V.A.T", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:n0}", Int64.Parse(slipData["tax_amount"].ToString())), yPos, StringAlignment.Far);

                yPos = PrintText(e, "환급액      Refund Amount", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, string.Format(CultureInfo.CreateSpecificCulture("en-US"), "{0:n0}", Int64.Parse(slipData["refund_amount"].ToString())), yPos, StringAlignment.Far);

                System.DateTime sd = new System.DateTime(Int32.Parse(slipData["sale_date"].ToString().Substring(0, 4)),
                                                         Int32.Parse(slipData["sale_date"].ToString().Substring(4, 2))
                                                         , Int32.Parse(slipData["sale_date"].ToString().Substring(6, 2)));
                sd = sd.AddMonths(3);

                yPos = PrintText(e, "환급유효기간/Refund Expiry date: ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, sd.ToString("yyyy-MM-dd"), yPos, StringAlignment.Far);

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);

                yPos = PrintText(e, "투숙객 / GUEST Your Passport Info in English", yPos, StringAlignment.Near, true);

                String passportName = slipData["passport_name"] != null ? slipData["passport_name"].ToString() : "";
                String passportNat  = slipData["passport_nat"] != null ? slipData["passport_nat"].ToString() : "";
                String passportNo   = slipData["passport_no"] != null ? slipData["passport_no"].ToString() : "";

                yPos = PrintText(e, "Passport Full Name ", yPos, StringAlignment.Near, false);
                yPos = PrintText(e, passportName, yPos, StringAlignment.Far);

                yPos = PrintText(e, "Passport No ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, passportNo, yPos, StringAlignment.Far);

                yPos = PrintText(e, "Nationality ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, passportNat, yPos, StringAlignment.Far);

                yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5);

                yPos = PrintText(e, "환급수단/Refund Option", yPos, StringAlignment.Near, true);
                yPos = PrintText(e, "[  ]Credit Card (Visa/Master/JCB/CUP)", yPos, StringAlignment.Near);
                yPos = PrintText(e, "Card No. ", yPos, StringAlignment.Near);
                yPos = PrintText(e, "", yPos, StringAlignment.Near, false, true, 4);
                yPos = PrintText(e, "[  ]QQ Number", yPos, StringAlignment.Near);
                yPos = PrintText(e, "", yPos, StringAlignment.Near, false, true, 4);
                yPos = PrintText(e, "[  ]Alipay ", yPos, StringAlignment.Near, false);
                yPos = PrintText(e, "(Alipay Mobile phone number 11digits) ", yPos, StringAlignment.Near, false);
                yPos = PrintText(e, " ", yPos, StringAlignment.Near, false, true, 5);

                yPos = PrintText(e, "", yPos, StringAlignment.Near, false, true, 4);

                float nMaxHeight = yPos - 3;
                //yPos = PrintText(e, lineText, yPos, StringAlignment.Center, false, true, 5); //삭제처리


                //yPos = PrintText(e, "ver." + Properties.Resources.appVer, yPos, StringAlignment.Near, true,true , nSmallSize);

                System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Black, 2);
                e.Graphics.DrawRectangle(myPen, new Rectangle(nStartPoint - 3, 23, nPageWidthHalf + 6, (int)yPos - 3));
                myPen.Dispose();


                //2018.04.03 추가 데이터 출력
                yPos        = 40;                                //2018.04.05 출력 위치 조정 20->40
                nStartPoint = nStartPoint + nPageWidthHalf + 10; //시작 좌표 위치 변경
                yPos        = PrintText(e, "Consent to collect, use and disclose", yPos, StringAlignment.Center, false, true, -1, "맑은고딕", true);
                yPos        = PrintText(e, "of personal information", yPos, StringAlignment.Center, false, true, -1, "맑은고딕", true);
                yPos        = PrintText(e, "1. Personal Information Recipients", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  Hotel Tax Refund Processing Government ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  organizations", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " 2. Purpose of collection and use of personal", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  information", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - To confirm identification and check departure ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  for V.A.T. refund of foreign tourists received ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  hotel accommodation.", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " 3. Categories for collecting personal information", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - Personal Information : Name, Date of Birth, ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  Nationality, Passport No., Date of Departure,", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  Date of arrival", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - Unique Identification Information : Passport ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  No.", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " 4. Period of holding and using personal ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  information", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - The taxation period which includes The date ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  when the V.A.T. refund or remittance is ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  received", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " 5. Withdrawal of consent and contents of ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  disadvantage", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - You have right to withdraw consents.However, ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " consequence follows(You may only receive V.A.T. ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  refund at the refund counter within the airport  ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  or port of departure)", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  - Personal information will not be disclosed ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, "  for any other collected purpose", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " I will consent to disclosure of personal ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " information.", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " I will consent to disclosure of unique ", yPos, StringAlignment.Near);
                yPos        = PrintText(e, " identification information. ", yPos, StringAlignment.Near);

                String strCurrntDate = slipData["sale_date"].ToString().Substring(0, 4) + "." + slipData["sale_date"].ToString().Substring(4, 2) + "." + slipData["sale_date"].ToString().Substring(6, 2);
                yPos = PrintText(e, strCurrntDate, yPos, StringAlignment.Center);

                //서명란
                //yPos = PrintText(e, "I agree to voluntarily provide personal INFO.", yPos, StringAlignment.Near);
                //yPos = PrintText(e, "Guest's Signature", yPos, StringAlignment.Near, true);

                yPos = PrintText(e, "Name ", yPos, StringAlignment.Near, false, false);
                yPos = PrintText(e, passportName, yPos, StringAlignment.Far);
                yPos = PrintText(e, "Signature", yPos, StringAlignment.Near, false);

                if (slipData["sign_img"] != null && !"".Equals(slipData["sign_img"].ToString().Trim()))
                {
                    byte[]         sign_buff      = System.Convert.FromBase64String(slipData["sign_img"].ToString());
                    ImageConverter imageConverter = new ImageConverter();
                    Image          image          = (Image)imageConverter.ConvertFrom(sign_buff);
                    Image          resizeImage    = new Bitmap(image, new Size(240, 64));
                    resizeImage.Save(Constants.filePath_Sign, ImageFormat.Jpeg);
                    yPos = PrintImg(e, resizeImage, yPos, StringAlignment.Center);
                    image.Dispose();
                    resizeImage.Dispose();
                }
                else
                {
                    yPos = PrintText(e, "  ", yPos, StringAlignment.Near);
                    yPos = PrintText(e, "  ", yPos, StringAlignment.Near);
                    yPos = PrintText(e, "  ", yPos, StringAlignment.Near);
                    yPos = PrintText(e, "  ", yPos, StringAlignment.Near);
                }

                yPos = PrintText(e, "ver." + Properties.Resources.appVer, nMaxHeight - 16, StringAlignment.Center, true, true, nSmallSize);

                myPen = new System.Drawing.Pen(System.Drawing.Color.Black, 2);
                //e.Graphics.DrawRectangle(myPen, new Rectangle(nStartPoint - 3, 3, nPageWidthHalf + 6, (int)yPos - 3));
                e.Graphics.DrawRectangle(myPen, new Rectangle(nStartPoint - 3, 23, nPageWidthHalf + 6, (int)nMaxHeight));

                myPen.Dispose();
            }
            catch (Exception ex)
            {
                m_Logger.Error(ex.Message, ex);
                Console.WriteLine(ex.Message);
            }
        }
Example #12
0
        /// <summary>
        /// 将返回的json解析为Geometry,不考虑坐标包含M和Z,如果考虑,请改动即可。将ArcObjects的Geometry转为json的代码我正在测试。
        /// 作者:刘宇
        /// 时间2012年
        /// </summary>
        /// <param name="jsonResponse"></param>
        /// <returns></returns>

        public static Geometry ParsefromJson(JObject jsonObject)
        {
            try
            {
                //   JObject jsonObject = JObject.Parse(jsonResponse) as JObject;

                SpatialReference pSpatial = new SpatialReference();
                Geometry         pGeo     = null;

                if (jsonObject.Property("geometries") != null || jsonObject.Property("geometry") != null)
                {
                    //     JArray jsonGArray = jsonObject["geometries"] as JArray;
                    JArray  jsonGArray;
                    JObject jsonObjectGeo;

                    if (jsonObject.Property("geometry") != null)
                    {
                        jsonObjectGeo = jsonObject["geometry"] as JObject;
                    }
                    else
                    {
                        jsonGArray = jsonObject["geometries"] as JArray;
                        if (jsonGArray.Count() < 1)     // 只返回一个GEOM 对象
                        {
                            return(null);
                        }

                        jsonObjectGeo = jsonGArray[0] as JObject;
                    }


                    //空间参考信息
                    if (jsonObjectGeo.Property("spatialReference") != null)
                    {
                        pSpatial = new SpatialReference(4326);


                        //JsonObject pSpatialJson =jsonObjectGeo["spatialReference"] as JsonObject;

                        //   根据需要添加
                    }
                    //点线面对象,不考虑hasz和hasM
                    if (jsonObjectGeo.Property("points") != null)
                    {
                        JArray JsonPoints = jsonObjectGeo["points"] as JArray;

                        if (JsonPoints is JArray)
                        {
                            if (JsonPoints.Count() == 1)
                            {
                                MapPoint pPoint = new MapPoint();

                                //去掉中括号

                                string[] pStrPoints = JsonPoints[0].ToString().Substring(1, JsonPoints[0].ToString().Length - 2).Split(',');

                                pPoint.X = Convert.ToDouble(pStrPoints[0]);
                                pPoint.Y = Convert.ToDouble(pStrPoints[1]);

                                pGeo = pPoint;
                            }
                        }
                    }
                    else if (jsonObjectGeo.Property("paths") != null)
                    {
                        JArray JsonPoints = jsonObjectGeo["paths"] as JArray;

                        ESRI.ArcGIS.Client.Geometry.Polyline pPolyline = new ESRI.ArcGIS.Client.Geometry.Polyline();


                        ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection> pPointCollection = new ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection>();
                        // pPolyline.Paths

                        if (JsonPoints is JArray)
                        {
                            for (int i = 0; i < JsonPoints.Count(); i++)
                            {
                                if (JsonPoints[i] is JArray)
                                {
                                    ESRI.ArcGIS.Client.Geometry.PointCollection pPointCollections = new ESRI.ArcGIS.Client.Geometry.PointCollection();

                                    JArray pInnerPoints = JsonPoints[i] as JArray;
                                    for (int j = 0; j < pInnerPoints.Count; j++)
                                    {
                                        string pStr = pInnerPoints[j].ToString();

                                        string[] pStrPoints = pInnerPoints[j].ToString().Substring(1, pInnerPoints[j].ToString().Length - 2).Split(',');
                                        MapPoint pPoint     = new MapPoint();
                                        pPoint.X = Convert.ToDouble(pStrPoints[0]);
                                        pPoint.Y = Convert.ToDouble(pStrPoints[1]);

                                        pPointCollections.Add(pPoint);
                                    }

                                    pPointCollection.Add(pPointCollections);
                                }
                            }

                            pPolyline.Paths = pPointCollection;

                            pGeo = pPolyline;
                        }
                    }
                    else if (jsonObjectGeo.Property("rings") != null)
                    {
                        JArray JsonPoints = jsonObjectGeo["rings"] as JArray;

                        ESRI.ArcGIS.Client.Geometry.Polygon pPolygon = new ESRI.ArcGIS.Client.Geometry.Polygon();



                        ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection> pPointCollection = new ObservableCollection <ESRI.ArcGIS.Client.Geometry.PointCollection>();


                        if (JsonPoints is JArray)
                        {
                            for (int i = 0; i < JsonPoints.Count(); i++)
                            {
                                if (JsonPoints[i] is JArray)
                                {
                                    ESRI.ArcGIS.Client.Geometry.PointCollection pPointCollections = new ESRI.ArcGIS.Client.Geometry.PointCollection();

                                    JArray pInnerPoints = JsonPoints[i] as JArray;
                                    for (int j = 0; j < pInnerPoints.Count; j++)
                                    {
                                        string pStr = pInnerPoints[j].ToString();

                                        string[] pStrPoints = pInnerPoints[j].ToString().Substring(1, pInnerPoints[j].ToString().Length - 2).Split(',');
                                        MapPoint pPoint     = new MapPoint();
                                        pPoint.X = Convert.ToDouble(pStrPoints[0]);
                                        pPoint.Y = Convert.ToDouble(pStrPoints[1]);

                                        pPointCollections.Add(pPoint);
                                    }

                                    pPointCollection.Add(pPointCollections);
                                }
                            }

                            pPolygon.Rings = pPointCollection;

                            pGeo = pPolygon;
                        }
                    }
                }


                if (pGeo != null)
                {
                    pGeo.SpatialReference = pSpatial;
                }

                return(pGeo);
            }
            catch (Exception)   // 解析出现异常返回空
            {
                return(null);
            }
        }
Example #13
0
 public void loadData()
 {
     if (Login.jsonResult != null)
     {
         Cursor.Current = Cursors.WaitCursor;
         string token = "";
         foreach (var x in Login.jsonResult)
         {
             if (x.Key.Equals("token"))
             {
                 token = x.Value.ToString();
             }
         }
         if (!token.Equals(""))
         {
             var client = new RestClient(utilityc.URL);
             client.Timeout = -1;
             string branch = (cmbBranch.Text.Equals("") || cmbBranch.Text == "All" ? "" : findBranchCode());
             string search = txtSearch.Text.ToString().Trim();
             //string branch = "A1-S";
             var request = new RestRequest("/api/auth/user/get_all?branch=" + branch + "&search=" + search);
             request.AddHeader("Authorization", "Bearer " + token);
             var     response = client.Execute(request);
             JObject jObject  = new JObject();
             jObject = JObject.Parse(response.Content.ToString());
             dgv.Rows.Clear();
             AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
             bool isSuccess = false;
             foreach (var x in jObject)
             {
                 if (x.Key.Equals("success"))
                 {
                     isSuccess = Convert.ToBoolean(x.Value.ToString());
                 }
             }
             if (isSuccess)
             {
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("data"))
                     {
                         if (x.Value.ToString() != "[]")
                         {
                             JArray jsonArray = JArray.Parse(x.Value.ToString());
                             for (int i = 0; i < jsonArray.Count(); i++)
                             {
                                 JObject data     = JObject.Parse(jsonArray[i].ToString());
                                 int     id       = 0;
                                 string  userName = "",
                                         fullName = "";
                                 foreach (var q in data)
                                 {
                                     if (q.Key.Equals("username"))
                                     {
                                         userName = q.Value.ToString();
                                         auto.Add(q.Value.ToString());
                                     }
                                     else if (q.Key.Equals("fullname"))
                                     {
                                         fullName = q.Value.ToString();
                                     }
                                     else if (q.Key.Equals("id"))
                                     {
                                         id = Convert.ToInt32(q.Value.ToString());
                                     }
                                 }
                                 txtSearch.AutoCompleteCustomSource = auto;
                                 dgv.Rows.Add(id, userName, fullName);
                             }
                         }
                     }
                 }
             }
             else
             {
                 string msg = "No message response found";
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("message"))
                     {
                         msg = x.Value.ToString();
                     }
                 }
                 MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         Cursor.Current = Cursors.Default;
     }
 }
 public void loadData()
 {
     dgv.Rows.Clear();
     if (Login.jsonResult != null)
     {
         Cursor.Current = Cursors.WaitCursor;
         string token = "";
         foreach (var x in Login.jsonResult)
         {
             if (x.Key.Equals("token"))
             {
                 token = x.Value.ToString();
             }
         }
         if (!token.Equals(""))
         {
             bool isSuccess = false;
             var  client    = new RestClient(utilityc.URL);
             client.Timeout = -1;
             var request = new RestRequest("/api/report/customer/sales_summary/details/" + lblCustomerCode.Text + "?from_date=" + dtFromDate.Value.ToString("yyyy-MM-dd") + "&to_date=" + dtToDate.Value.ToString("yyyy-MM-dd"));
             Console.WriteLine("/api/report/customer/sales_summary/details/" + lblCustomerCode.Text + "?from_date=" + dtFromDate.Value.ToString("yyyy-MM-dd") + "&to_date=" + dtToDate.Value.ToString("yyyy-MM-dd"));
             request.AddHeader("Authorization", "Bearer " + token);
             request.Method = Method.GET;
             var response = client.Execute(request);
             if (response.ErrorMessage == null)
             {
                 if (response.Content.ToString().Substring(0, 1).Equals("{"))
                 {
                     JObject jObject = JObject.Parse(response.Content.ToString());
                     foreach (var x in jObject)
                     {
                         if (x.Key.Equals("success"))
                         {
                             if (Convert.ToBoolean(x.Value.ToString()))
                             {
                                 isSuccess = true;
                                 break;
                             }
                         }
                     }
                     if (isSuccess)
                     {
                         double totalRunningBalance = 0.00;
                         foreach (var x in jObject)
                         {
                             if (x.Key.Equals("data"))
                             {
                                 if (x.Value.ToString() != "{}")
                                 {
                                     JObject  data = JObject.Parse(x.Value.ToString());
                                     string   ref1 = "", ref2 = "", transType = "", remarks = "";
                                     double   amtIn = 0.00, amtOut = 0.00;
                                     DateTime dtTransDate = new DateTime();
                                     foreach (var q in data)
                                     {
                                         if (q.Key.Equals("bal_result"))
                                         {
                                             JObject balResult = JObject.Parse(q.Value.ToString());
                                             foreach (var w in balResult)
                                             {
                                                 totalRunningBalance = string.IsNullOrEmpty(w.Value.ToString().Trim()) ? 0.00 : Convert.ToDouble(w.Value.ToString());
                                                 lblBalance.Text     = totalRunningBalance.ToString("n2");
                                             }
                                         }
                                         else if (q.Key.Equals("row_result"))
                                         {
                                             JArray jsonArray = JArray.Parse(q.Value.ToString());
                                             for (int i = 0; i < jsonArray.Count(); i++)
                                             {
                                                 JObject rowResult = JObject.Parse(jsonArray[i].ToString());
                                                 foreach (var w in rowResult)
                                                 {
                                                     if (w.Key.Equals("reference"))
                                                     {
                                                         ref1 = w.Value.ToString();
                                                     }
                                                     else if (w.Key.Equals("reference2"))
                                                     {
                                                         ref2 = w.Value.ToString();
                                                     }
                                                     else if (w.Key.Equals("transtype"))
                                                     {
                                                         transType = w.Value.ToString();
                                                     }
                                                     else if (w.Key.Equals("amount_in"))
                                                     {
                                                         amtIn = string.IsNullOrEmpty(w.Value.ToString().Trim()) ? 0.00 : Convert.ToDouble(w.Value.ToString());
                                                     }
                                                     else if (w.Key.Equals("amount_out"))
                                                     {
                                                         amtOut = string.IsNullOrEmpty(w.Value.ToString().Trim()) ? 0.00 : Convert.ToDouble(w.Value.ToString());
                                                     }
                                                     else if (w.Key.Equals("transdate"))
                                                     {
                                                         dtTransDate = Convert.ToDateTime(w.Value.ToString());
                                                     }
                                                     else if (w.Key.Equals("remarks"))
                                                     {
                                                         remarks = w.Value.ToString();
                                                     }
                                                 }
                                                 totalRunningBalance += amtIn;
                                                 totalRunningBalance -= amtOut;
                                                 dgv.Rows.Add(dtTransDate.ToString("yyyy-MM-dd"), ref1, ref2, transType, Convert.ToDecimal(string.Format("{0:0.00}", amtIn)), Convert.ToDecimal(string.Format("{0:0.00}", amtOut)), Convert.ToDecimal(string.Format("{0:0.00}", totalRunningBalance)), remarks);
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                     else
                     {
                         MessageBox.Show(response.Content.ToString(), "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     }
                 }
                 else
                 {
                     JObject jObject = JObject.Parse(response.Content.ToString());
                     string  msg     = "";
                     foreach (var x in jObject)
                     {
                         if (x.Key.Equals("message"))
                         {
                             msg = x.Value.ToString();
                         }
                     }
                     if (msg.Equals("Token is invalid"))
                     {
                         MessageBox.Show("Your login session is expired. Please login again", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     }
                     else
                     {
                         MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     }
                 }
             }
             else
             {
                 MessageBox.Show(response.ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
     }
 }
Example #15
0
    public void Remove()
    {
      JToken t;
      JArray a =
        new JArray(
          5,
          6,
          new JArray(7, 8),
          new JArray(9, 10)
        );

      a[0].Remove();

      Assert.AreEqual(6, (int)a[0]);

      a[1].Remove();

      Assert.AreEqual(6, (int)a[0]);
      Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
      Assert.AreEqual(2, a.Count());

      t = a[1];
      t.Remove();
      Assert.AreEqual(6, (int)a[0]);
      Assert.IsNull(t.Next);
      Assert.IsNull(t.Previous);
      Assert.IsNull(t.Parent);

      t = a[0];
      t.Remove();
      Assert.AreEqual(0, a.Count());

      Assert.IsNull(t.Next);
      Assert.IsNull(t.Previous);
      Assert.IsNull(t.Parent);
    }
Example #16
0
    public void AddFirst()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      a.AddFirst("First");

      Assert.AreEqual("First", (string)a[0]);
      Assert.AreEqual(a, a[0].Parent);
      Assert.AreEqual(a[1], a[0].Next);
      Assert.AreEqual(5, a.Count());

      a.AddFirst("NewFirst");
      Assert.AreEqual("NewFirst", (string)a[0]);
      Assert.AreEqual(a, a[0].Parent);
      Assert.AreEqual(a[1], a[0].Next);
      Assert.AreEqual(6, a.Count());

      Assert.AreEqual(a[0], a[0].Next.Previous);
    }
Example #17
0
        public string Save_ykiensaodautao(string DataJson, string nguoitao, string matiepnhan)
        {
            logger.Start("Save_ykiensaodautao");
            string matiepnhanid = "";

            try
            {
                sqlMap.BeginTransaction();
                Hashtable param = new Hashtable();
                JObject   json  = JObject.Parse(DataJson);
                param["malop"]         = json["data1"]["malop"].ToString();
                param["manv"]          = json["data1"]["manv"].ToString();
                param["email"]         = json["data1"]["email"].ToString();
                param["hovaten"]       = json["data1"]["hovaten"].ToString();
                param["maphongban"]    = json["data1"]["maphongban"].ToString();
                param["tieudekhoahoc"] = json["data1"]["tieudekhoahoc"].ToString();
                param["tengiaovien"]   = json["data1"]["tengiaovien"].ToString();
                param["ngaydaotao"]    = json["data1"]["ngaydaotao"].ToString();
                param["nguoitao"]      = nguoitao;

                param["matiepnhan"] = json["data1"]["matiepnhan"].ToString();

                if (param["matiepnhan"].ToString().Trim() == "0")
                {
                    param["matiepnhan"] = GetSequence_All("dm_seq", "daotao_ykiensaodaotao");
                    sqlMap.Insert("Saudaotao.InsertRow_Saudaotao", param);
                }
                else
                {
                    param["matiepnhan"] = param["matiepnhan"].ToString().Trim();
                    sqlMap.Update("Saudaotao.UpdateRow_Saudaotao", param);
                }
                matiepnhanid = param["matiepnhan"].ToString();
                Hashtable   param1           = new Hashtable();
                JArray      json_vpp_chitiet = (JArray)json["data2"];
                FunctionXML function         = new FunctionXML(Functions.MapPath("~/Xml/Config/encryptionkeyEncodeLink.config"));
                for (int i = 0; i < json_vpp_chitiet.Count(); i++)
                {
                    param1 = new Hashtable();

                    param1["matiepnhan_tieuchidaotao"] = AES.DecryptText(json_vpp_chitiet[i]["matiepnhan_tieuchidaotao"].ToString().Trim(), function.ReadXMLGetKeyEncrypt());
                    param1["matieuchi"]  = AES.DecryptText(json_vpp_chitiet[i]["matieuchi"].ToString().Trim(), function.ReadXMLGetKeyEncrypt());
                    param1["matiepnhan"] = matiepnhanid;

                    param1["tentieuchi"] = json_vpp_chitiet[i]["tentieuchi"].ToString().Trim();// ["kem"] = "undefined"

                    if (json_vpp_chitiet[i]["kem"].ToString().Trim() == "true")
                    {
                        param1["kem"] = "1";
                    }
                    else
                    {
                        param1["kem"] = "0";
                    }

                    if (json_vpp_chitiet[i]["trungbinh"].ToString().Trim() == "true")
                    {
                        param1["trungbinh"] = "1";
                    }
                    else
                    {
                        param1["trungbinh"] = "0";
                    }

                    if (json_vpp_chitiet[i]["kha"].ToString().Trim() == "true")
                    {
                        param1["kha"] = "1";
                    }
                    else
                    {
                        param1["kha"] = "0";
                    }

                    if (json_vpp_chitiet[i]["tot"].ToString().Trim() == "true")
                    {
                        param1["tot"] = "1";
                    }
                    else
                    {
                        param1["tot"] = "0";
                    }

                    if (json_vpp_chitiet[i]["rattot"].ToString().Trim() == "true")
                    {
                        param1["rattot"] = "1";
                    }
                    else
                    {
                        param1["rattot"] = "0";
                    }

                    param1["danhmuccha"] = json_vpp_chitiet[i]["danhmuccha"].ToString().Trim();
                    param1["danhmucgoc"] = json_vpp_chitiet[i]["danhmucgoc"].ToString().Trim();

                    param1["nguoitao"] = nguoitao;
                    if (param1["matiepnhan_tieuchidaotao"].ToString() == "" || param1["matiepnhan_tieuchidaotao"].ToString() == "0" || param1["matiepnhan_tieuchidaotao"].ToString() == null)
                    {
                        sqlMap.Insert("Saudaotao.InsertRow_Saudaotao_chitiet", param1);
                    }
                    else
                    {
                        sqlMap.Update("Saudaotao.UpdateRow_Saudaotao_chitiet", param1);
                    }
                }
                sqlMap.CommitTransaction();
            }
            catch (Exception ex)
            {
                sqlMap.RollbackTransaction();
                logger.Error(ex.Message);
            }
            logger.End("Save_ykiensaodautao");
            return(matiepnhanid);
        }
Example #18
0
    public void AddBeforeSelf()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      a[1].AddBeforeSelf("pie");

      Assert.AreEqual(5, (int)a[0]);
      Assert.AreEqual("pie", (string)a[1]);
      Assert.AreEqual(a, a[1].Parent);
      Assert.AreEqual(a[2], a[1].Next);
      Assert.AreEqual(5, a.Count());

      a[0].AddBeforeSelf("firstpie");

      Assert.AreEqual("firstpie", (string)a[0]);
      Assert.AreEqual(5, (int)a[1]);
      Assert.AreEqual("pie", (string)a[2]);
      Assert.AreEqual(a, a[0].Parent);
      Assert.AreEqual(a[1], a[0].Next);
      Assert.AreEqual(6, a.Count());

      a.Last.AddBeforeSelf("secondlastpie");

      Assert.AreEqual("secondlastpie", (string)a[5]);
      Assert.AreEqual(7, a.Count());
    }
Example #19
0
        private static void DrawFeaturedImageFromDisplayAssetProperty(JArray AssetProperties, JArray displayAssetProperties)
        {
            JToken resourceObjectOuterImportToken = AssetsUtility.GetPropertyTagOuterImport <JToken>(displayAssetProperties, "ResourceObject");
            JToken resourceObjectImportToken      = AssetsUtility.GetPropertyTagImport <JToken>(displayAssetProperties, "ResourceObject");

            if (resourceObjectOuterImportToken != null && resourceObjectOuterImportToken.Value <string>() != null)
            {
                string texturePath = FoldersUtility.FixFortnitePath(resourceObjectOuterImportToken.Value <string>());
                if (texturePath.Contains("/FortniteGame/Content/Athena/Prototype/Textures/"))
                {
                    DrawIconImage(AssetProperties, false);
                }
                else
                {
                    using (Stream image = AssetsUtility.GetStreamImageFromPath(texturePath))
                    {
                        if (image != null)
                        {
                            BitmapImage bmp = new BitmapImage();
                            bmp.BeginInit();
                            bmp.CacheOption  = BitmapCacheOption.OnLoad;
                            bmp.StreamSource = image;
                            bmp.EndInit();
                            bmp.Freeze();

                            IconCreator.ICDrawingContext.DrawImage(bmp, new Rect(3, 3, 509, 509));
                        }
                    }

                    if (AssetsLoader.ExportType == "AthenaItemWrapDefinition" && texturePath.Contains("WeaponRenders"))
                    {
                        DrawAdditionalWrapImage(AssetProperties);
                    }
                }
            }
            else if (resourceObjectImportToken != null)
            {
                //this will catch the full path if asset exists to be able to grab his PakReader and List<FPakEntry>
                string renderSwitchPath = AssetEntries.AssetEntriesDict.Where(x => x.Key.Contains("/" + resourceObjectImportToken.Value <string>())).Select(d => d.Key).FirstOrDefault();
                if (!string.IsNullOrEmpty(renderSwitchPath) && (renderSwitchPath.Contains("MI_UI_FeaturedRenderSwitch_") ||
                                                                renderSwitchPath.Contains("M-Wraps-StreetDemon") ||
                                                                renderSwitchPath.Contains("/FortniteGame/Content/UI/Foundation/Textures/Icons/Wraps/FeaturedMaterials/")))
                {
                    string jsonData = AssetsUtility.GetAssetJsonDataByPath(renderSwitchPath.Substring(0, renderSwitchPath.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase)));
                    if (jsonData != null && AssetsUtility.IsValidJson(jsonData))
                    {
                        JToken AssetMainToken = AssetsUtility.ConvertJson2Token(jsonData);
                        if (AssetMainToken != null)
                        {
                            JArray renderSwitchProperties = AssetMainToken["properties"].Value <JArray>();
                            if (renderSwitchProperties != null)
                            {
                                JArray textureParameterArray = AssetsUtility.GetPropertyTagText <JArray>(renderSwitchProperties, "TextureParameterValues", "data");
                                textureParameterArray = textureParameterArray[textureParameterArray.Count() > 1 && !AssetsLoader.ExportType.Equals("AthenaItemWrapDefinition") ? 1 : 0]["struct_type"]["properties"].Value <JArray>();
                                if (textureParameterArray != null)
                                {
                                    JToken parameterValueToken = AssetsUtility.GetPropertyTagOuterImport <JToken>(textureParameterArray, "ParameterValue");
                                    if (parameterValueToken != null)
                                    {
                                        string texturePath = FoldersUtility.FixFortnitePath(parameterValueToken.Value <string>());
                                        using (Stream image = AssetsUtility.GetStreamImageFromPath(texturePath))
                                        {
                                            if (image != null)
                                            {
                                                BitmapImage bmp = new BitmapImage();
                                                bmp.BeginInit();
                                                bmp.CacheOption  = BitmapCacheOption.OnLoad;
                                                bmp.StreamSource = image;
                                                bmp.EndInit();
                                                bmp.Freeze();

                                                IconCreator.ICDrawingContext.DrawImage(bmp, new Rect(3, 3, 509, 509));
                                            }
                                        }

                                        if (AssetsLoader.ExportType == "AthenaItemWrapDefinition" && texturePath.Contains("WeaponRenders"))
                                        {
                                            DrawAdditionalWrapImage(AssetProperties);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #20
0
        public void changeVal()
        {
            int i = 0;

            Controls.Remove(panel);
            panel.Location    = new System.Drawing.Point(50, 20);
            panel.Size        = new Size(800, 400);
            panel.MaximumSize = new Size(800, 400);
            panel.AutoScroll  = true;

            panel.ColumnCount = 4;
            panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F));
            panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35F));
            panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20.5F));
            panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 25.5F));

            panel.RowCount = json.Count() + 1;
            panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));

            panel.Controls.Clear();

            Label orden = new Label();

            orden.Text      = "Orden";
            orden.AutoSize  = true;
            orden.Font      = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            orden.TextAlign = ContentAlignment.MiddleCenter;

            Label emp = new Label();

            emp.Text      = "Empresa";
            emp.AutoSize  = true;
            emp.Font      = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            emp.TextAlign = ContentAlignment.MiddleCenter;

            Label fecha = new Label();

            fecha.Text      = "Fecha";
            fecha.AutoSize  = true;
            fecha.Font      = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            fecha.TextAlign = ContentAlignment.MiddleCenter;

            Label pmde = new Label();

            pmde.Text      = "Plazo maximo de entrega";
            pmde.AutoSize  = true;
            pmde.Font      = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            pmde.TextAlign = ContentAlignment.MiddleCenter;

            panel.Controls.Add(orden, 0, 0);
            panel.Controls.Add(emp, 1, 0);
            panel.Controls.Add(fecha, 2, 0);
            panel.Controls.Add(pmde, 3, 0);

            for (i = 1; i < panel.RowCount; i++)
            {
                int    d   = 0;
                string inx = i.ToString();
                if (db)
                {
                    d = (int)json[i - 1]["db"];
                }

                string ordn = (String)json[i - 1]["orden"];

                Label ordText = new Label();
                if (db)
                {
                    ordText.Click += (sender2, e2) => ConfirmOrder(sender2, e2, ordn, d, inx);
                }

                ordText.Text      = ordn;
                ordText.AutoSize  = false;
                ordText.TextAlign = ContentAlignment.MiddleCenter;
                panel.Controls.Add(ordText, 0, i);


                Label empText = new Label();
                if (db)
                {
                    empText.Click += (sender2, e2) => ConfirmOrder(sender2, e2, ordn, d, inx);
                }


                empText.Text      = (String)json[i - 1]["emp"];
                empText.AutoSize  = true;
                empText.TextAlign = ContentAlignment.MiddleCenter;
                panel.Controls.Add(empText, 1, i);

                Label dateText = new Label();
                if (db)
                {
                    dateText.Click += (sender2, e2) => ConfirmOrder(sender2, e2, ordn, d, inx);
                }



                dateText.Text      = (String)json[i - 1]["fecha"];
                dateText.AutoSize  = true;
                dateText.TextAlign = ContentAlignment.MiddleCenter;
                panel.Controls.Add(dateText, 2, i);


                Label pmdeText = new Label();

                if (db)
                {
                    pmdeText.Click += (sender2, e2) => ConfirmOrder(sender2, e2, ordn, d, inx);
                }

                if (json[i - 1]["pmde"] != null)
                {
                    pmdeText.Text = (String)json[i - 1]["pmde"];
                }
                else
                {
                    pmdeText.Text = "-";
                }

                pmdeText.AutoSize  = false;
                pmdeText.TextAlign = ContentAlignment.MiddleCenter;
                panel.Controls.Add(pmdeText, 3, i);
            }

            Controls.Add(panel);
        }
Example #21
0
        protected override JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getapplicationlog":
            {
                UInt256 hash = UInt256.Parse(_params[0].AsString());
                string  path = Path.Combine(Settings.Default.Paths.ApplicationLogs, $"{hash}.json");
                return(File.Exists(path)
                            ? JObject.Parse(File.ReadAllText(path))
                            : throw new RpcException(-100, "Unknown transaction"));
            }

            case "getbalance":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    JObject json = new JObject();
                    switch (UIntBase.Parse(_params[0].AsString()))
                    {
                    case UInt160 asset_id_160:         //NEP-5 balance
                        json["balance"] = Program.Wallet.GetAvailable(asset_id_160).ToString();
                        break;

                    case UInt256 asset_id_256:         //Global Assets balance
                        IEnumerable <Coin> coins = Program.Wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256));
                        json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                        json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        break;
                    }
                    return(json);
                }

            case "balance":     // 使用address查询余额 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    JObject json = new JObject();
                    if (_params.Count() == 1)
                    {
                        // 查询NEO和GAS资产
                        string address = _params[0].AsString();
                        try
                        {
                            Wallet.ToScriptHash(address);
                        }
                        catch
                        {
                            json["code"]    = -1;
                            json["message"] = "NEO地址错误";
                            return(json);
                        }
                        IEnumerable <Coin> coins = Program.Wallet.GetCoins(address);
                        // NEO
                        var neoCoins = coins.Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(UInt256.Parse(Settings.Default.Asset.NEOAsset)));
                        json["balance"]   = neoCoins.Sum(p => p.Output.Value).ToString();
                        json["confirmed"] = neoCoins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        // GAS
                        var gasCoins = coins.Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(UInt256.Parse(Settings.Default.Asset.GASAsset)));
                        json["gasbalance"]   = gasCoins.Sum(p => p.Output.Value).ToString();
                        json["gasconfirmed"] = gasCoins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        return(json);
                    }
                    else     // 查询指定资产余额
                    {
                        string address = _params[1].AsString();

                        switch (UIntBase.Parse(_params[0].AsString()))
                        {
                        case UInt160 asset_id_160:         //NEP-5 balance
                            json["balance"] = Program.Wallet.GetAvailable(asset_id_160, address).ToString();
                            break;

                        case UInt256 asset_id_256:         //Global Assets balance
                            IEnumerable <Coin> coins = Program.Wallet.GetCoins(address).Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256));
                            json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                            json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                            break;
                        }
                        return(json);
                    }
                }

            case "listaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    return(Program.Wallet.GetAccounts().Select(p =>
                    {
                        JObject account = new JObject();
                        account["address"] = p.Address;
                        account["haskey"] = p.HasKey;
                        account["label"] = p.Label;
                        account["watchonly"] = p.WatchOnly;
                        return account;
                    }).ToArray());
                }

            case "sendfrom":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = Wallet.ToScriptHash(_params[1].AsString());
                    UInt160         to         = Wallet.ToScriptHash(_params[2].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 6 ? Wallet.ToScriptHash(_params[5].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendfromto":     // 从指定账号向指定账号转账 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    // 参数顺序  资产类型  输出账号  输入账号  输出金额  输出账号私钥  手续费    找零地址
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = Wallet.ToScriptHash(_params[1].AsString());
                    UInt160         to         = Wallet.ToScriptHash(_params[2].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    string          privatekey = _params[4].AsString();
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 6 ? Fixed8.Parse(_params[5].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 7 && !string.IsNullOrEmpty(_params[6].AsString()) ? Wallet.ToScriptHash(_params[6].AsString()) : from;// 找零地址
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    //File.AppendAllText("wallet.log", context.ScriptHashes.Count().ToString());
                    //Program.Wallet.Sign(context);
                    Program.Wallet.Sign(context, privatekey);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendtoaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = Wallet.ToScriptHash(_params[1].AsString());
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? Wallet.ToScriptHash(_params[4].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = Wallet.ToScriptHash(to[i]["address"].AsString())
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? Wallet.ToScriptHash(_params[2].AsString()) : null;
                    Transaction tx             = Program.Wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    Program.Wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Scripts = context.GetScripts();
                        Program.Wallet.ApplyTransaction(tx);
                        LocalNode.Relay(tx);
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "getnewaddress":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = Program.Wallet.CreateAccount();
                    if (Program.Wallet is NEP6Wallet wallet)
                    {
                        wallet.Save();
                    }
                    return(account.Address);
                }

            case "newaddress":    // 创建一个账号 AddCode
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = Program.Wallet.CreateAccount();
                    if (Program.Wallet is NEP6Wallet wallet)
                    {
                        wallet.Save();
                    }
                    return(account.OutputJson());
                }

            case "dumpprivkey":
                if (Program.Wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160       scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                    WalletAccount account    = Program.Wallet.GetAccount(scriptHash);
                    return(account.GetKey().Export());
                }

            case "invoke":
            case "invokefunction":
            case "invokescript":
                JObject result = base.Process(method, _params);
                if (Program.Wallet != null)
                {
                    InvocationTransaction tx = new InvocationTransaction
                    {
                        Version = 1,
                        Script  = result["script"].AsString().HexToBytes(),
                        Gas     = Fixed8.Parse(result["gas_consumed"].AsString())
                    };
                    tx.Gas -= Fixed8.FromDecimal(10);
                    if (tx.Gas < Fixed8.Zero)
                    {
                        tx.Gas = Fixed8.Zero;
                    }
                    tx.Gas = tx.Gas.Ceiling();
                    tx     = Program.Wallet.MakeTransaction(tx);
                    if (tx != null)
                    {
                        ContractParametersContext context = new ContractParametersContext(tx);
                        Program.Wallet.Sign(context);
                        if (context.Completed)
                        {
                            tx.Scripts = context.GetScripts();
                        }
                        else
                        {
                            tx = null;
                        }
                    }
                    result["tx"] = tx?.ToArray().ToHexString();
                }
                return(result);

            default:
                return(base.Process(method, _params));
            }
        }
Example #22
0
        public async Task renderTracks()
        {
            JArray tracks = (JArray)this.rt.recentTracks["recenttracks"]["track"];

            JObject track;
            JToken  jToken;

            int imgMargin = 10;
            int tb1Margin = 6;
            int tb2Margin = 35;
            int tb3Margin = 64;

            for (int i = 0; i < tracks.Count(); i++)
            {
                track = (JObject)tracks[i];
                Track t = new Track(
                    (string)track["artist"]["#text"],
                    (string)track["name"],
                    (string)track["album"]["#text"],
                    (string)track["url"],
                    (string)track["image"][2]["#text"],
                    (string)track["date"]["#text"]
                    );

                //<Image HorizontalAlignment="Left" Height="80" Margin="10,10,0,0" VerticalAlignment="Top" Width="80" Source="http://userserve-ak.last.fm/serve/126/100446599.jpg"/>
                //<Image HorizontalAlignment="Left" Height="80" Margin="10,118,0,0" VerticalAlignment="Top" Width="80" Source="http://userserve-ak.last.fm/serve/126/100446599.jpg"/>
                Image img = new Image();
                img.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                img.Height            = 80;
                img.Width             = 80;
                img.Margin            = new Thickness(10, imgMargin, 0, 0);
                img.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                img.Source            = new BitmapImage(new Uri(t.image, UriKind.Absolute));
                ContentPanel.Children.Add(img);

                //<TextBlock HorizontalAlignment="Left" Margin="100,6,-11,0" TextWrapping="Wrap" Text="The Bonzo Dog Doo Dah Band " VerticalAlignment="Top" Width="367" Height="26"/>
                //<TextBlock HorizontalAlignment="Left" Margin="100,114,-11,0" TextWrapping="Wrap" Text="The Bonzo Dog Doo Dah Band " VerticalAlignment="Top" Width="367" Height="26"/>
                TextBlock tb = new TextBlock();
                tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                tb.Height            = 26;
                tb.Width             = 367;
                tb.Margin            = new Thickness(100, tb1Margin, -11, 0);
                tb.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                tb.TextWrapping      = TextWrapping.Wrap;
                tb.Text = t.artist;
                ContentPanel.Children.Add(tb);

                //<TextBlock HorizontalAlignment="Left" Margin="100,35,-11,0" TextWrapping="Wrap" Text="Don't Sit Down Cause I've Moved Your Chair" VerticalAlignment="Top" Width="367" Height="26"/>
                //<TextBlock HorizontalAlignment="Left" Margin="100,143,-11,0" TextWrapping="Wrap" Text="Don't Sit Down Cause I've Moved Your Chair" VerticalAlignment="Top" Width="367" Height="26"/>
                TextBlock tb2 = new TextBlock();
                tb2.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                tb2.Height            = 26;
                tb2.Width             = 367;
                tb2.Margin            = new Thickness(100, tb2Margin, -11, 0);
                tb2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                tb2.TextWrapping      = TextWrapping.Wrap;
                tb2.Text = t.name;
                ContentPanel.Children.Add(tb2);

                //<TextBlock HorizontalAlignment="Left" Margin="100,64,-11,0" TextWrapping="Wrap" Text="1 hour ago" VerticalAlignment="Top" Width="367" Foreground="Gray" Height="26"/>
                //<TextBlock HorizontalAlignment="Left" Margin="100,172,-11,0" TextWrapping="Wrap" Text="1 hour ago" VerticalAlignment="Top" Width="367" Foreground="Gray" Height="26"/>
                TextBlock tb3 = new TextBlock();
                tb3.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                tb3.Height            = 26;
                tb3.Width             = 367;
                tb3.Margin            = new Thickness(100, tb3Margin, -11, 0);
                tb3.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                tb3.TextWrapping      = TextWrapping.Wrap;
                tb3.Text       = t.date;
                tb3.Foreground = new SolidColorBrush(Colors.Gray);
                ContentPanel.Children.Add(tb3);

                imgMargin += 108;
                tb1Margin += 108;
                tb2Margin += 108;
                tb3Margin += 108;
            }

            SystemTray.ProgressIndicator.IsIndeterminate = false;
            SystemTray.ProgressIndicator.IsVisible       = false;
        }
Example #23
0
 public void loadItemGroups()
 {
     if (Login.jsonResult != null)
     {
         Cursor.Current = Cursors.WaitCursor;
         string token = "";
         foreach (var x in Login.jsonResult)
         {
             if (x.Key.Equals("token"))
             {
                 token = x.Value.ToString();
             }
         }
         if (!token.Equals(""))
         {
             var client = new RestClient(utilityc.URL);
             client.Timeout = -1;
             //string branch = "A1-S";
             var request = new RestRequest("/api/item/item_grp/getall");
             request.AddHeader("Authorization", "Bearer " + token);
             var     response = client.Execute(request);
             JObject jObject  = new JObject();
             jObject = JObject.Parse(response.Content.ToString());
             cmbItemGroup.Items.Clear();
             bool isSuccess = false;
             foreach (var x in jObject)
             {
                 if (x.Key.Equals("success"))
                 {
                     isSuccess = Convert.ToBoolean(x.Value.ToString());
                 }
             }
             if (isSuccess)
             {
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("data"))
                     {
                         if (x.Value.ToString() != "[]")
                         {
                             JArray jsonArray = JArray.Parse(x.Value.ToString());
                             for (int i = 0; i < jsonArray.Count(); i++)
                             {
                                 JObject data = JObject.Parse(jsonArray[i].ToString());
                                 string  code = "";
                                 foreach (var q in data)
                                 {
                                     if (q.Key.Equals("code"))
                                     {
                                         code = q.Value.ToString();
                                     }
                                 }
                                 cmbItemGroup.Items.Add(code);
                             }
                         }
                     }
                 }
             }
             else
             {
                 string msg = "No message response found";
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("message"))
                     {
                         msg = x.Value.ToString();
                     }
                 }
                 MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         Cursor.Current = Cursors.Default;
     }
 }
Example #24
0
        public JObject SerialiseToJobject()
        {
            JObject jobject = new JObject();

            if (!string.IsNullOrEmpty(name))
            {
                jobject[HikeConstants.CS_NAME] = name;
            }

            JArray jarray = new JArray();

            if (!string.IsNullOrEmpty(mobileNumber))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_MOBILE_KEY] = mobileNumber;
                jarray.Add(jobj);
            }
            if (!string.IsNullOrEmpty(homePhone))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_HOME_KEY] = homePhone;
                jarray.Add(jobj);
            }
            if (!string.IsNullOrEmpty(workPhone))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_WORK_KEY] = workPhone;
                jarray.Add(jobj);
            }
            if (jarray.Count() > 0)
            {
                jobject[HikeConstants.CS_PHONE_NUMBERS] = jarray;
            }
            jarray = new JArray();
            if (!string.IsNullOrEmpty(personalEmail))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_HOME_KEY] = personalEmail;
                jarray.Add(jobj);
            }

            if (!string.IsNullOrEmpty(workEmail))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_WORK_KEY] = workEmail;
                jarray.Add(jobj);
            }
            if (!string.IsNullOrEmpty(otherEmail))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_OTHERS_KEY] = otherEmail;
                jarray.Add(jobj);
            }
            if (jarray.Count() > 0)
            {
                jobject[HikeConstants.CS_EMAILS] = jarray;
            }

            jarray = new JArray();
            if (!string.IsNullOrEmpty(homeAddress))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_HOME_KEY] = homeAddress;
                jarray.Add(jobj);
            }

            if (!string.IsNullOrEmpty(workAddress))
            {
                JObject jobj = new JObject();
                jobj[HikeConstants.CS_WORK_KEY] = workAddress;
                jarray.Add(jobj);
            }

            if (jarray.Count() > 0)
            {
                jobject[HikeConstants.CS_ADDRESSES] = jarray;
            }

            return(jobject);
        }
Example #25
0
        /// <summary>
        /// Filter the representations and return the result.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown when representations are null.</exception>
        /// <param name="representations">Representations to filter.</param>
        /// <param name="searchParameter">Search parameters.</param>
        /// <param name="totalNumbers">Total number of records</param>
        /// <returns>Filtered response</returns>
        public FilterResult Filter(IEnumerable <Representation> representations, SearchParameter searchParameter, int totalNumbers)
        {
            if (representations == null)
            {
                throw new ArgumentNullException(nameof(representations));
            }

            if (searchParameter == null)
            {
                throw new ArgumentNullException(nameof(searchParameter));
            }

            IEnumerable <string> commonAttrs = new[]
            {
                Common.Constants.MetaResponseNames.ResourceType,
                Common.Constants.MetaResponseNames.Created,
                Common.Constants.MetaResponseNames.LastModified,
                Common.Constants.MetaResponseNames.Version,
                Common.Constants.MetaResponseNames.Location
            };

            var result = new JArray();

            // 1. Sort the representations.
            if (searchParameter.SortBy != null)
            {
                var comparer = new RepresentationComparer(searchParameter.SortBy);
                if (searchParameter.SortOrder == SortOrders.Ascending)
                {
                    representations = representations.OrderBy(repr => repr, comparer);
                }
                else
                {
                    representations = representations.OrderByDescending(repr => repr, comparer);
                }
            }

            // 2. Filter the representations.
            foreach (var representation in representations)
            {
                // 2.1 Exclude & include certains attributes.
                IEnumerable <RepresentationAttribute> attributes = null;
                if (searchParameter.ExcludedAttributes != null && searchParameter.ExcludedAttributes.Any())
                {
                    foreach (var excludedAttrFilter in searchParameter.ExcludedAttributes)
                    {
                        var excludedAttrs = excludedAttrFilter.Evaluate(representation);
                        if (excludedAttrs == null)
                        {
                            continue;
                        }

                        foreach (var excludedAttr in excludedAttrs)
                        {
                            var excludedParent = excludedAttr.Parent as ComplexRepresentationAttribute;
                            if (excludedParent == null)
                            {
                                continue;
                            }

                            excludedParent.Values = excludedParent.Values.Where(v => !excludedAttrs.Contains(v));
                        }
                    }
                }

                if (searchParameter.Attributes != null && searchParameter.Attributes.Any())
                {
                    attributes = new List <RepresentationAttribute>();
                    foreach (var attrFilter in searchParameter.Attributes)
                    {
                        attributes = attributes.Concat(attrFilter.Evaluate(representation));
                    }
                }
                else
                {
                    attributes = representation.Attributes;
                }

                if (attributes == null || !attributes.Any())
                {
                    continue;
                }

                // 2.2 Add all attributes
                var obj = new JObject();
                foreach (JProperty token in attributes.Select(a => (JProperty)GetToken(a, a.SchemaAttribute)))
                {
                    var value = obj[token.Name];
                    if (value != null)
                    {
                        var arr = value as JArray;
                        if (arr != null)
                        {
                            arr.Add(token.Value);
                        }
                        else
                        {
                            obj[token.Name] = new JArray(value, token.Value);
                        }
                    }
                    else
                    {
                        obj.Add(token);
                    }
                }

                result.Add(obj);
            }

            var filterResult = new FilterResult();

            if (result.Count() > searchParameter.Count)
            {
                filterResult.StartIndex   = searchParameter.StartIndex;
                filterResult.ItemsPerPage = searchParameter.Count;
                filterResult.Values       = result;
            }
            else
            {
                filterResult.Values = result;
            }

            filterResult.TotalNumbers = totalNumbers;
            // 3. Paginate the representations.
            return(filterResult);
        }
Example #26
0
        public int Comfirm_Sayg1(Sayg request)
        {
            int Result = -1;

            try
            {
                using (var db = DbConnectionFactory.OpenDbConnection())
                {
                    if (request.UpdateAllString != null && request.UpdateAllString != "")
                    {
                        JArray ja = (JArray)JsonConvert.DeserializeObject(request.UpdateAllString);
                        if (ja != null)
                        {
                            for (int i = 0; i < ja.Count(); i++)
                            {
                                string strSql         = "";
                                string YogaStudioNo   = ja[i]["YogaStudioName"].ToString();
                                string YogaStudioName = ja[i]["YogaStudioName"].ToString();
                                string Name           = ja[i]["Name"].ToString();
                                string AreaCode       = ja[i]["AreaCode"].ToString();
                                string Address        = ja[i]["Address"].ToString();
                                string Sex            = ja[i]["Sex"].ToString();
                                string Remark         = ja[i]["Remark"].ToString();
                                string PhoneNumber    = ja[i]["PhoneNumber"].ToString();
                                string PassWord       = ja[i]["PassWord"].ToString();

                                strSql = "insert into sayg1( " +
                                         "   YogaStudioNo," +
                                         "   YogaStudioName," +
                                         "   Name ," +
                                         "   AreaCode," +
                                         "   Address ," +
                                         "   Sex," +
                                         "   Remark ," +
                                         "   PhoneNumber ," +
                                         "   PassWord ," +
                                         "   CreateDateTime," +
                                         "   UpdateDateTime" +
                                         "  )" +
                                         "values( " +
                                         Modfunction.SQLSafeValue(YogaStudioNo) + " , " +
                                         Modfunction.SQLSafeValue(YogaStudioName) + "," +
                                         Modfunction.SQLSafeValue(Name) + "," +
                                         Modfunction.SQLSafeValue(AreaCode) + "," +
                                         Modfunction.SQLSafeValue(Address) + "," +
                                         Modfunction.SQLSafeValue(Sex) + "," +
                                         Modfunction.SQLSafeValue(Remark) + "," +
                                         Modfunction.SQLSafeValue(PhoneNumber) + "," +
                                         Modfunction.SQLSafeValue(PassWord) + "," +
                                         "GETDATE()," +
                                         "GETDATE()" +
                                         ") ";
                                db.ExecuteSql(strSql);
                            }
                            Result = 1;
                        }
                    }
                }
            }
            catch { throw; }
            return(Result);
        }
Example #27
0
        public DataTable loadData(string status, string type)
        {
            DataTable result = new DataTable();

            result.Columns.Add("id");
            result.Columns.Add("cust_code");
            result.Columns.Add("amount");
            result.Columns.Add("balance");
            result.Columns.Add("remarks");
            result.Columns.Add("sap_number");
            result.Columns.Add("reference");
            result.Columns.Add("status");
            result.Columns.Add("transdate");
            result.Columns.Add("reference2");
            if (Login.jsonResult != null)
            {
                Cursor.Current = Cursors.WaitCursor;
                string token = "";
                foreach (var x in Login.jsonResult)
                {
                    if (x.Key.Equals("token"))
                    {
                        token = x.Value.ToString();
                    }
                }
                if (!token.Equals(""))
                {
                    var client = new RestClient(utilityc.URL);
                    client.Timeout = -1;
                    string sUsedDeposit = type.Equals("In Deposit") ? "&used=" : "&used=1";
                    string sURL         = type.Equals("Summary Deposit") ? "/api/deposit/summary" : "/api/deposit/get_all?&status=" + status + sUsedDeposit;
                    var    request      = new RestRequest(sURL);
                    Console.WriteLine(sURL);
                    request.AddHeader("Authorization", "Bearer " + token);
                    var     response = client.Execute(request);
                    JObject jObject  = new JObject();
                    jObject = JObject.Parse(response.Content.ToString());
                    bool isSuccess = false;
                    foreach (var x in jObject)
                    {
                        if (x.Key.Equals("success"))
                        {
                            isSuccess = Convert.ToBoolean(x.Value.ToString());
                        }
                    }
                    if (isSuccess)
                    {
                        foreach (var x in jObject)
                        {
                            if (x.Key.Equals("data"))
                            {
                                if (x.Value.ToString() != "[]")
                                {
                                    JArray jsonArray = JArray.Parse(x.Value.ToString());
                                    for (int i = 0; i < jsonArray.Count(); i++)
                                    {
                                        JObject data = JObject.Parse(jsonArray[i].ToString());
                                        int     id = 0;
                                        string  custCode = "",
                                                remarks = "", referenceNumber = "", aStatus = "", sapNumber = "", referenceNumber2 = "";
                                        double   amount = 0.00, balance = 0.00;
                                        DateTime dtTransDate = new DateTime();
                                        foreach (var q in data)
                                        {
                                            if (q.Key.Equals("id"))
                                            {
                                                id = Convert.ToInt32(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("cust_code"))
                                            {
                                                custCode = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("amount"))
                                            {
                                                amount = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("balance"))
                                            {
                                                balance = Convert.ToDouble(q.Value.ToString());
                                            }
                                            else if (q.Key.Equals("sap_number"))
                                            {
                                                sapNumber = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("remarks"))
                                            {
                                                remarks = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("reference"))
                                            {
                                                referenceNumber = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("reference2"))
                                            {
                                                referenceNumber2 = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("status"))
                                            {
                                                aStatus = q.Value.ToString();
                                            }
                                            else if (q.Key.Equals("transdate"))
                                            {
                                                string replaceT = q.Value.ToString().Replace("T", "");
                                                dtTransDate = Convert.ToDateTime(replaceT);
                                            }
                                        }
                                        if (aStatus.Equals("O"))
                                        {
                                            aStatus = "Open";
                                        }
                                        else if (aStatus.Equals("C"))
                                        {
                                            aStatus = "Closed";
                                        }
                                        else if (aStatus.Equals("N"))
                                        {
                                            aStatus = "Cancelled";
                                        }
                                        result.Rows.Add(id, custCode, amount, balance, remarks, sapNumber, referenceNumber, aStatus, dtTransDate.ToString("yyyy-MM-dd HH:mm"), referenceNumber2);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string msg = "No message response found";
                        foreach (var x in jObject)
                        {
                            if (x.Key.Equals("message"))
                            {
                                msg = x.Value.ToString();
                            }
                        }
                        if (msg.Equals("Token is invalid"))
                        {
                            MessageBox.Show("Your login session is expired. Please login again", "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
                Cursor.Current = Cursors.Default;
            }
            return(result);
        }
Example #28
0
        private void LoadOSList()
        {
            actbtn.Dispatcher.Invoke(new Action(() =>
            {
                DialogWait.IsOpen = true;
            }));
            try
            {
                string           json    = GetHttpWebRequest("https://kms.kumo.moe/api/digital?list=1");
                JObject          jsonobj = JObject.Parse(json);
                List <Frequency> list    = new List <Frequency>();
                Frequency        freq    = new Frequency();
                ositems = (JArray)jsonobj["OS"];
                for (int i = 0; i < ositems.Count(); i++)
                {
                    freq.ID        = i;
                    freq.DisplayOS = jsonobj["OS"][i].ToString();
                    if (jsonobj["OS"][i].ToString() == SystemEdition)
                    {
                        now_os_index = i;
                        checked_os   = SystemEdition;
                    }
                    if (jsonobj["OS"][i].ToString() == SystemEdition + OSVersionInfo.BuildVersion)
                    {
                        now_os_index = i;
                        checked_os   = SystemEdition + OSVersionInfo.BuildVersion;
                    }
                    list.Add(freq);
                }

                actbtn.Dispatcher.Invoke(new Action(() =>
                {
                    this.SystemEditionText.ItemsSource = list;//控件的ID

                    if (checked_os == "unknow")
                    {
                        this.SystemEditionText.SelectedIndex     = 0;
                        this.DialogWithOKToCloseDialogTitle.Text = "Attention";
                        this.DialogWithOKToCloseDialogText.Text  = "Unable to correctly identify your operating system, may be not be supported.\r\n(System edition: " + SystemEdition + OSVersionInfo.BuildVersion + ")";
                        this.DialogWithOKToCloseDialog.IsOpen    = true;
                    }
                    else
                    {
                        this.SystemEditionText.SelectedIndex = now_os_index;
                    }
                }));

                //this.SystemEditionText.SelectedIndex = now_os_index;
                // 在此点之下插入创建对象所需的代码。
            }
            catch
            {
                actbtn.Dispatcher.Invoke(new Action(() =>
                {
                    DialogWithExit.IsOpen = true;
                }));
            }
            actbtn.Dispatcher.Invoke(new Action(() =>
            {
                DialogWait.IsOpen = false;
            }));
        }
Example #29
0
File: osu.cs Project: Kyuwu/Bott
        public async Task usebest([Remainder] string name)
        {
            try
            {
                EmbedBuilder xd      = new EmbedBuilder();
                var          request =
                    WebRequest.Create(
                        $"https://osu.ppy.sh/api/get_user?k=00b5c6aaae0d1a09091f08fc294836c893c591de&u={name}")
                    as
                    HttpWebRequest;
                if (request == null)
                {
                    return;
                }
                request.Method      = "GET";
                request.ContentType = "application/json";

                var myWebResponse = (HttpWebResponse)request.GetResponse();
                var encoding      = Encoding.ASCII;
                using (var reader =
                           new StreamReader(myWebResponse.GetResponseStream() ?? throw new InvalidOperationException(),
                                            encoding))
                {
                    var result    = reader.ReadToEnd();
                    var container = (JContainer)JsonConvert.DeserializeObject(result);
                    var userid    = container[0]["user_id"].ToString();
                    var username  = container[0]["username"].ToString();

                    try
                    {
                        var request2 =
                            WebRequest.Create(
                                $"https://osu.ppy.sh/api/get_user_recent?k=00b5c6aaae0d1a09091f08fc294836c893c591de&u={userid}&type=id")
                            as
                            HttpWebRequest;
                        if (request2 == null)
                        {
                            return;
                        }
                        request2.Method      = "GET";
                        request2.ContentType = "application/json";

                        var myWebResponse2 = (HttpWebResponse)request2.GetResponse();
                        var encoding2      = Encoding.ASCII;
                        using (var reader2 =
                                   new StreamReader(
                                       myWebResponse2.GetResponseStream() ?? throw new InvalidOperationException(),
                                       encoding2))
                        {
                            var result2 = reader2.ReadToEnd();

                            JArray container2 = (JArray)JsonConvert.DeserializeObject(result2);
                            var    length     = container2.Count();
                            if (length > 0)
                            {
                                for (int xdd = 0; xdd < length; xdd++)
                                {
                                    var date = container2[xdd]["maxcombo"].ToString();
                                    var bmap = container2[xdd]["beatmap_id"].ToString();
                                    var rank = container2[xdd]["rank"].ToString();
                                    var c50  = Convert.ToDouble(container2[xdd]["count50"]);
                                    var c100 = Convert.ToDouble(container2[xdd]["count100"]);
                                    var c300 = Convert.ToDouble(container2[xdd]["count300"]);
                                    var mod  = container2[xdd]["enabled_mods"].ToString();

                                    var cmiss = Convert.ToDouble(container2[xdd]["countmiss"]);
                                    var acc2  = 100.0 * (6 * c300 + 2 * c100 + c50) / (6 * (c50 + c100 + c300 + cmiss));
                                    var acc   = Math.Round(acc2, 2);
                                    if (rank.Contains("A"))
                                    {
                                        rank = "<:rankingAsmall:400920344593956867>";
                                    }
                                    if (rank.Contains("B"))
                                    {
                                        rank = "<:rankingBsmall:400920320925761538>";
                                    }
                                    if (rank.Contains("C"))
                                    {
                                        rank = "<:rankingCsmall:400920375053254656>";
                                    }
                                    if (rank.Contains("D"))
                                    {
                                        rank = "<:rankingDsmall:400920408884510721>";
                                    }
                                    if (rank.Contains("S"))
                                    {
                                        rank = "<:rankingSsmall:400920431344746517>";
                                    }
                                    if (rank.Contains("F"))
                                    {
                                        rank = "<:sectionfail:400920942408368128>";
                                    }
                                    if (rank.Contains("X"))
                                    {
                                        rank = "<:rankingXsmall:400920039479574532>";
                                    }
                                    if (mod.Contains("64"))
                                    {
                                        mods.AppendLine("DT");
                                    }
                                    if (mod.Contains("1024"))
                                    {
                                        mods.AppendLine("FL");
                                    }
                                    if (mod.Contains("512"))
                                    {
                                        mods.AppendLine("NC");
                                    }
                                    if (mod.Contains("16"))
                                    {
                                        mods.AppendLine("HR");
                                    }
                                    if (mod.Contains("8"))
                                    {
                                        mods.AppendLine("RL Pleb");
                                    }
                                    if (mod.Contains("576"))
                                    {
                                        mods.AppendLine("HD");
                                    }
                                    if (mod.Contains("16416"))
                                    {
                                        mods.AppendLine("FC");
                                    }
                                    //------------------------------------------------
                                    var request3 =
                                        WebRequest.Create(
                                            $"https://osu.ppy.sh/api/get_beatmaps?k=00b5c6aaae0d1a09091f08fc294836c893c591de&b={bmap}")
                                        as
                                        HttpWebRequest;
                                    if (request3 == null)
                                    {
                                        return;
                                    }

                                    request3.Method      = "GET";
                                    request3.ContentType = "application/json";
                                    var myWebResponse3 = (HttpWebResponse)request3.GetResponse();
                                    var encoding3      = Encoding.ASCII;
                                    using (var reader3 =
                                               new StreamReader(
                                                   myWebResponse3.GetResponseStream() ?? throw new InvalidOperationException(),
                                                   encoding3))
                                    {
                                        var result3    = reader3.ReadToEnd();
                                        var container3 = (JContainer)JsonConvert.DeserializeObject(result3);

                                        var title = container3[0]["title"].ToString();
                                        var diff  = container3[0]["version"].ToString();
                                        var url   = container3[0]["beatmapset_id"].ToString();
                                        var mc    = container3[0]["max_combo"].ToString();
                                        var ar    = container3[0]["artist"].ToString();

                                        xd.Title        = username;
                                        xd.Description  = $"{length} Recent plays.\n----";
                                        xd.ThumbnailUrl = $"https://s.ppy.sh/a/{userid}";
                                        if (mod == "0")
                                        {
                                            xd.AddField(x =>
                                            {
                                                x.Name  = $"{ar} - {title} ({diff})";
                                                x.Value =
                                                    $"**Rank:** {rank} **Combo**: {date}({mc}) **Accuracy:** {acc}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                                            });
                                        }
                                        else
                                        {
                                            xd.AddField(x =>
                                            {
                                                x.Name  = $"{ar} - {title} ({diff}) +{mods}";
                                                x.Value =
                                                    $"**Rank:** {rank} **Combo**: {date}({mc}) **Accuracy:** {acc}[:arrow_down:](https://osu.ppy.sh/d/{url}) [:information_source:](https://osu.ppy.sh/s/{url})";
                                            });
                                            mods.Clear();
                                        }
                                    }
                                }
                                await ReplyAsync("", false, xd.Build());
                            }
                            else
                            {
                                await Errorrecent();
                            }
                        }
                    }
                    catch (Exception x)
                    {
                        await Errorrecent();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await Erroruser();
            }
        }
Example #30
0
    public void Children()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      Assert.AreEqual(4, a.Count());
      Assert.AreEqual(3, a.Children<JArray>().Count());
    }
Example #31
0
 public void loadData()
 {
     if (Login.jsonResult != null)
     {
         Cursor.Current = Cursors.WaitCursor;
         AutoCompleteStringCollection auto = new AutoCompleteStringCollection();
         string token = "";
         foreach (var x in Login.jsonResult)
         {
             if (x.Key.Equals("token"))
             {
                 token = x.Value.ToString();
             }
         }
         if (!token.Equals(""))
         {
             var client = new RestClient(utilityc.URL);
             client.Timeout = -1;
             //string branch = "A1-S";
             var request = new RestRequest("/api/item/getall");
             request.AddHeader("Authorization", "Bearer " + token);
             var     response = client.Execute(request);
             JObject jObject  = new JObject();
             jObject = JObject.Parse(response.Content.ToString());
             dgv.Rows.Clear();
             bool isSuccess = false;
             foreach (var x in jObject)
             {
                 if (x.Key.Equals("success"))
                 {
                     isSuccess = Convert.ToBoolean(x.Value.ToString());
                 }
             }
             if (isSuccess)
             {
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("data"))
                     {
                         if (x.Value.ToString() != "[]")
                         {
                             JArray jsonArray = JArray.Parse(x.Value.ToString());
                             for (int i = 0; i < jsonArray.Count(); i++)
                             {
                                 JObject data = JObject.Parse(jsonArray[i].ToString());
                                 int     id = 0;
                                 string  itemName = "", itemCode = "", uOm = "", itemGroup = "";
                                 double  pRice = 0.00;
                                 foreach (var q in data)
                                 {
                                     if (q.Key.Equals("item_code"))
                                     {
                                         itemCode = q.Value.ToString();
                                     }
                                     else if (q.Key.Equals("item_name"))
                                     {
                                         itemName = q.Value.ToString();
                                     }
                                     else if (q.Key.Equals("item_group"))
                                     {
                                         itemGroup = q.Value.ToString();
                                     }
                                     else if (q.Key.Equals("id"))
                                     {
                                         id = Convert.ToInt32(q.Value.ToString());
                                     }
                                     else if (q.Key.Equals("uom"))
                                     {
                                         uOm = q.Value.ToString();
                                     }
                                     else if (q.Key.Equals("price"))
                                     {
                                         pRice = Convert.ToDouble(q.Value.ToString());
                                     }
                                 }
                                 auto.Add(itemCode);
                                 auto.Add(itemName);
                                 auto.Add(itemGroup);
                                 if (!string.IsNullOrEmpty(txtSearch.Text.ToString().Trim()))
                                 {
                                     if (txtSearch.Text.ToString().Trim().ToLower().Contains(itemCode.ToLower()))
                                     {
                                         dgv.Rows.Add(id, itemCode, itemName, uOm, itemGroup, Convert.ToDecimal(string.Format("{0:0.00}", pRice)));
                                         break;
                                     }
                                     if (txtSearch.Text.ToString().Trim().ToLower().Contains(itemName.ToLower()))
                                     {
                                         dgv.Rows.Add(id, itemCode, itemName, uOm, itemGroup, Convert.ToDecimal(string.Format("{0:0.00}", pRice)));
                                         break;
                                     }
                                     if (txtSearch.Text.ToString().Trim().ToLower().Contains(itemGroup.ToLower()))
                                     {
                                         dgv.Rows.Add(id, itemCode, itemName, uOm, itemGroup, Convert.ToDecimal(string.Format("{0:0.00}", pRice)));
                                         break;
                                     }
                                 }
                                 else
                                 {
                                     dgv.Rows.Add(id, itemCode, itemName, uOm, itemGroup, Convert.ToDecimal(string.Format("{0:0.00}", pRice)));
                                 }
                             }
                         }
                     }
                 }
             }
             else
             {
                 string msg = "No message response found";
                 foreach (var x in jObject)
                 {
                     if (x.Key.Equals("message"))
                     {
                         msg = x.Value.ToString();
                     }
                 }
                 MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
             }
         }
         txtSearch.AutoCompleteCustomSource = auto;
         Cursor.Current = Cursors.Default;
     }
 }
Example #32
0
    public void CreateWriter()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      JsonWriter writer = a.CreateWriter();
      Assert.IsNotNull(writer);
      Assert.AreEqual(4, a.Count());

      writer.WriteValue("String");
      Assert.AreEqual(5, a.Count());
      Assert.AreEqual("String", (string)a[4]);

      writer.WriteStartObject();
      writer.WritePropertyName("Property");
      writer.WriteValue("PropertyValue");
      writer.WriteEnd();

      Assert.AreEqual(6, a.Count());
      Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
    }
Example #33
0
 public bool hasErrors()
 {
     return(jErrors.Count() > 0);
 }
Example #34
0
    public void RemoveAll()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      JToken first = a.First;
      Assert.AreEqual(5, (int)first);

      a.RemoveAll();
      Assert.AreEqual(0, a.Count());

      Assert.IsNull(first.Parent);
      Assert.IsNull(first.Next);
    }
        /// <summary>
        /// JSON format
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="url"></param>
        /// <param name="pageString"></param>
        /// <param name="imgs"></param>
        /// <param name="sub">站点标记</param>
        private void ProcessJSON(string siteUrl, string url, string pageString, List <Img> imgs, string sub)
        {
            if (string.IsNullOrWhiteSpace(pageString))
            {
                return;
            }
            JArray jArray = JArray.Parse(pageString);

            foreach (JToken obj in jArray)
            {
                string
                            id = "",
                            tags = "",
                            host = "",
                            score = "N/A",
                            source = "",
                            sample = "",
                            jpeg_url = "",
                            file_url = "",
                            created_at = "N/A",
                            preview_url = "",
                            author = "";
                int  width = 0, height = 0, file_size = 0;
                bool skin_parm;

                //域名
                host = url.Substring(0, url.IndexOf('/', 8));

                //图片ID
                if (obj["id"] != null)
                {
                    id = obj["id"].ToString();
                }

                //投稿者
                if (obj["author"] != null)
                {
                    if (sub.Contains("csku"))
                    {
                        JToken jt = JToken.Parse(obj["author"].ToString());
                        if (jt["name"] != null)
                        {
                            author = jt["name"].ToString();
                        }
                    }
                    else
                    {
                        author = obj["author"].ToString();
                    }
                }
                else if (obj["uploader_name"] != null)
                {
                    author = obj["uploader_name"].ToString();
                }

                //图片来源
                if (obj["source"] != null)
                {
                    source = obj["source"].ToString();
                }

                //原图宽高 width height
                try
                {
                    if (obj["width"] != null)
                    {
                        width  = int.Parse(obj["width"].ToString().Trim());
                        height = int.Parse(obj["height"].ToString().Trim());
                    }
                    else if (obj["image_width"] != null)
                    {
                        width  = int.Parse(obj["image_width"].ToString().Trim());
                        height = int.Parse(obj["image_height"].ToString().Trim());
                    }
                }
                catch { }

                //文件大小
                try
                {
                    if (obj["file_size"] != null)
                    {
                        file_size = int.Parse(obj["file_size"].ToString());
                    }
                }
                catch { }

                //上传时间
                if (obj["created_at"] != null)
                {
                    if (sub.Contains("sku"))
                    {
                        JToken objs = JObject.Parse(obj["created_at"].ToString());
                        if (!string.IsNullOrWhiteSpace(objs["s"].ToString()))
                        {
                            created_at = objs["s"].ToString();
                        }
                    }
                    else
                    {
                        created_at = obj["created_at"].ToString();
                    }
                }

                //评级和评分
                if (obj["rating"] != null)
                {
                    score = "Safe ";
                    if (obj["rating"].ToString() == "e")
                    {
                        score = "Explicit ";
                    }
                    else
                    {
                        score = "Questionable ";
                    }
                    if (obj["score"] != null)
                    {
                        score += obj["score"].ToString();
                    }
                    else if (obj["total_score"] != null)
                    {
                        score += obj["total_score"].ToString();
                    }
                }

                //缩略图
                if (obj["preview_url"] != null)
                {
                    sample = obj["preview_url"].ToString();
                }
                else if (obj["preview_file_url"] != null)
                {
                    sample = obj["preview_file_url"].ToString();
                }

                //预览图
                if (obj["sample_url"] != null)
                {
                    preview_url = obj["sample_url"].ToString();
                }
                else if (obj["large_file_url"] != null)
                {
                    preview_url = obj["large_file_url"].ToString();
                }

                //原图
                if (obj["file_url"] != null)
                {
                    file_url = obj["file_url"].ToString();
                }

                //JPG
                jpeg_url = preview_url.Length > 0 ? preview_url : file_url;
                if (obj["jpeg_url"] != null)
                {
                    jpeg_url = obj["jpeg_url"].ToString();
                }

                //Formatted
                skin_parm = sub.Contains("sku");

                sample      = FormattedImgUrl(host, sample, skin_parm);
                preview_url = FormattedImgUrl(host, preview_url, skin_parm);
                file_url    = FormattedImgUrl(host, file_url, skin_parm);
                jpeg_url    = FormattedImgUrl(host, jpeg_url, skin_parm);


                //标签
                if (obj["tags"] != null)
                {
                    if (sub.Contains("sku"))
                    {
                        #region sankaku tags rule
                        try
                        {
                            JArray jary = (JArray)obj["tags"];
                            if (jary.Count > 0)
                            {
                                JArray   ResultTags   = new JArray();
                                JArray   TagGroup     = new JArray();
                                string   TagTypeGroup = "3,2,4,1,8,0,9";
                                string[] TTGarr       = TagTypeGroup.Split(',');

                                foreach (string tts in TTGarr)
                                {
                                    foreach (JToken tjt in jary)
                                    {
                                        if (((JObject)tjt)["type"].ToString().Equals(tts, StringComparison.CurrentCultureIgnoreCase))
                                        {
                                            TagGroup.Add(tjt);
                                        }
                                    }

                                    if (tts.Equals("0"))
                                    {
                                        ResultTags.Add(TagGroup.OrderBy(jo => (string)jo["name"]));
                                    }
                                    else
                                    {
                                        ResultTags.Add(TagGroup.OrderByDescending(jo => Convert.ToInt32((string)jo["count"])));
                                    }

                                    TagGroup.Clear();
                                }

                                int i = 0, RTcount = ResultTags.Count();
                                foreach (JToken tjt in ResultTags)
                                {
                                    i++;
                                    tags += i < RTcount ? ((JObject)tjt)["name"].ToString() + " " : ((JObject)tjt)["name"].ToString();
                                }
                            }
                        }
                        catch {}
                        #endregion
                    }
                    else
                    {
                        tags = obj["tags"].ToString();
                    }
                }
                else if (obj["tag_string"] != null)
                {
                    tags = obj["tag_string"].ToString();
                }

                //恢复konachan删除的图片信息
                if (sub.Contains("konachan") && obj["file_url"] == null)
                {
                    tags = "deleted " + tags;
                    string md5 = string.Empty;
                    if (obj["md5"] != null)
                    {
                        md5 = obj["md5"].ToString();
                    }
                    sample      = $"{siteUrl}/data/preview/{md5.Substring(0, 2)}/{md5.Substring(2, 2)}/{md5}.jpg";
                    preview_url = $"{siteUrl}/sample/{md5}/{sub} - {id} sample.jpg";

                    file_url = $"{siteUrl}/image/{md5}/{sub} - {id} image.#ext"; //下载时会自动判断格式

                    jpeg_url = $"{siteUrl}/jpeg/{md5}/{sub} - {id} jpeg.jpg";
                }
                bool noVerify = sub.Length == 2 && sub.Contains("nv");

                Img img = GenerateImg(siteUrl, url, id, author, source, width, height, file_size, created_at, score, sample, preview_url, file_url, jpeg_url, tags, noVerify);
                if (img != null)
                {
                    imgs.Add(img);
                }
            }
        }
Example #36
0
    public void AddAfterSelf()
    {
      JArray a =
        new JArray(
          5,
          new JArray(1),
          new JArray(1, 2),
          new JArray(1, 2, 3)
        );

      a[1].AddAfterSelf("pie");

      Assert.AreEqual(5, (int)a[0]);
      Assert.AreEqual(1, a[1].Count());
      Assert.AreEqual("pie", (string)a[2]);
      Assert.AreEqual(5, a.Count());

      a[4].AddAfterSelf("lastpie");

      Assert.AreEqual("lastpie", (string)a[5]);
      Assert.AreEqual("lastpie", (string)a.Last);
    }
Example #37
0
        public static bool LoadCfg(string xmlCfgFile, ref string reStr)
        {
            try
            {
                //  string xmlCfgFile = System.AppDomain.CurrentDomain.BaseDirectory + @"data/DevConfigFTYJ.xml";
                if (!File.Exists(xmlCfgFile))
                {
                    reStr = "系统配置文件:" + xmlCfgFile + " 不存在!";
                    return(false);
                }
                cfgFilePath = xmlCfgFile;
                XElement root = XElement.Load(xmlCfgFile);

                XElement sysSetXE              = root.Element("sysSet");
                XElement sysParamXE            = sysSetXE.Element("SysParam");
                XElement qrCodewReqXe          = sysSetXE.Element("QRCodeRequire");
                XElement requireRepairProcssXe = sysSetXE.Element("RepairProcess");
                StartWorkStationID      = requireRepairProcssXe.Attribute("StartWorkStationID").Value.ToString();
                IsRequireRequireFromMes = bool.Parse(requireRepairProcssXe.Attribute("RequireFromMes").Value.ToString());
                ProcessID = requireRepairProcssXe.Attribute("ProcessID").Value.ToString();
                string strParam = sysParamXE.Value.ToString();
                if (!string.IsNullOrWhiteSpace(strParam))
                {
                    JArray jsonParams = (JArray)JsonConvert.DeserializeObject(strParam);
                    if (jsonParams != null && jsonParams.Count() > 0)
                    {
                        foreach (JObject paramObj in jsonParams)
                        {
                            ParamCfgBase.ParamModel param = new ParamCfgBase.ParamModel(paramObj["ParamName"].ToString(), paramObj["ParamVal"].ToString(), paramObj["ParamType"].ToString());
                            SysParamDic[paramObj["ParamName"].ToString()] = param;
                        }
                    }
                }
                if (sysSetXE.Element("WelderParam") != null)
                {
                    string batNum = sysSetXE.Element("WelderParam").Attribute("batteryNumInMod").Value.ToString();
                    batteryNumInMod = int.Parse(batNum);
                }
                XElement runModeXE = root.Element("sysSet").Element("RunMode");
                string   simStr    = runModeXE.Attribute("sim").Value.ToString().ToUpper();

                if (simStr == "TRUE")
                {
                    SimMode = true;
                }
                else
                {
                    SimMode = false;
                }
                //if(runModeXE.Attribute("debugMode") != null)
                //{
                //    string debugModeStr = runModeXE.Attribute("debugMode").Value.ToString().ToUpper();
                //    if(debugModeStr == "TRUE")
                //    {
                //        DebugMode = true;
                //    }
                //    else
                //    {
                //        DebugMode = false;
                //    }
                //}
                if (runModeXE.Attribute("manualMode1") != null)
                {
                    string manualModeStr = runModeXE.Attribute("manualMode1").Value.ToString().ToUpper();
                    if (manualModeStr == "TRUE")
                    {
                        ManualMode1 = true;
                    }
                    else
                    {
                        ManualMode1 = false;
                    }
                }
                if (runModeXE.Attribute("manualMode3") != null)
                {
                    string manualModeStr = runModeXE.Attribute("manualMode3").Value.ToString().ToUpper();
                    if (manualModeStr == "TRUE")
                    {
                        ManualMode3 = true;
                    }
                    else
                    {
                        ManualMode3 = false;
                    }
                }
                XElement printerXE = root.Element("sysSet").Element("Printer");
                string   str       = printerXE.Attribute("Enable").Value.ToString().ToUpper();
                if (str == "TRUE")
                {
                    PrienterEnable = true;
                }
                else
                {
                    PrienterEnable = false;
                }
                XElement mesXE = root.Element("sysSet").Element("Mes");
                if (mesXE.Attribute("LineID") != null)
                {
                    mesLineID = mesXE.Attribute("LineID").Value.ToString();
                }
                else
                {
                    reStr = "MES产线ID未定义";
                    return(false);
                }
                str = mesXE.Attribute("Enable").Value.ToString().ToUpper();
                if (str == "TRUE")
                {
                    MesCheckEnable = true;
                }
                else
                {
                    MesCheckEnable = false;
                }
                str = mesXE.Attribute("OfflineMode").Value.ToString().ToUpper();
                if (str == "TRUE")
                {
                    MesOfflineMode = true;
                }
                else
                {
                    MesOfflineMode = false;
                }
                str = mesXE.Attribute("MesAutodown").Value.ToString().ToUpper();
                if (str == "TRUE")
                {
                    MesAutodownEnabled = true;
                }
                else
                {
                    MesAutodownEnabled = false;
                }
                XElement mesTimeOutXE = root.Element("sysSet").Element("MesDownTimeout");
                MesTimeout = int.Parse(mesTimeOutXE.Value.ToString());

                XElement rfidTimeOutXE = root.Element("sysSet").Element("RfidTimeout");
                RfidDelayTimeout = int.Parse(rfidTimeOutXE.Value.ToString());

                return(true);
            }
            catch (Exception ex)
            {
                reStr = ex.ToString();
                return(false);
            }
        }
Example #38
0
    public void CreateJTokenTree()
    {
      JObject o =
        new JObject(
          new JProperty("Test1", "Test1Value"),
          new JProperty("Test2", "Test2Value"),
          new JProperty("Test3", "Test3Value"),
          new JProperty("Test4", null)
        );

      Assert.AreEqual(4, o.Properties().Count());

      Assert.AreEqual(@"{
  ""Test1"": ""Test1Value"",
  ""Test2"": ""Test2Value"",
  ""Test3"": ""Test3Value"",
  ""Test4"": null
}", o.ToString());

      JArray a =
        new JArray(
          o,
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
          55,
          new JArray(
            "1",
            2,
            3.0,
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
          ),
          new JConstructor(
            "ConstructorName",
            "param1",
            2,
            3.0
          )
        );

      Assert.AreEqual(5, a.Count());
      Assert.AreEqual(@"[
  {
    ""Test1"": ""Test1Value"",
    ""Test2"": ""Test2Value"",
    ""Test3"": ""Test3Value"",
    ""Test4"": null
  },
  ""2000-10-10T00:00:00Z"",
  55,
  [
    ""1"",
    2,
    3.0,
    ""0004-05-06T07:08:09Z""
  ],
  new ConstructorName(
    ""param1"",
    2,
    3.0
  )
]", a.ToString());
    }
Example #39
0
        public void loadData()
        {
            if (Login.jsonResult != null)
            {
                Cursor.Current = Cursors.WaitCursor;
                string token = "";
                foreach (var x in Login.jsonResult)
                {
                    if (x.Key.Equals("token"))
                    {
                        token = x.Value.ToString();
                    }
                }
                if (!token.Equals(""))
                {
                    var client = new RestClient(utilityc.URL);
                    client.Timeout = -1;
                    string whseCode = findWarehouseCode();
                    string sWhse    = string.IsNullOrEmpty(whseCode) ? "" : "&whsecode=" + whseCode;
                    string sDate    = "?transdate=" + dtDate.Value.ToString("yyyy-MM-dd");
                    string sSAP     = gAdjTrans.Equals("Done") ? "&sap_number=1" : "&sap_number=";
                    var    request  = new RestRequest("/api/inv_adj/" + gAdjType + "/get_all" + sDate + sWhse + sSAP);
                    Console.WriteLine("/api/inv_adj/" + gAdjType + "/get_all" + sDate + sWhse + sSAP);
                    request.AddHeader("Authorization", "Bearer " + token);
                    var response = client.Execute(request);
                    //MessageBox.Show(response.Content.ToString());
                    if (response.ErrorMessage == null)
                    {
                        JObject jObject   = JObject.Parse(response.Content.ToString());
                        bool    isSuccess = false;
                        string  msg       = "";
                        foreach (var x in jObject)
                        {
                            if (x.Key.Equals("success"))
                            {
                                isSuccess = Convert.ToBoolean(x.Value.ToString());
                            }
                            if (x.Key.Equals("message"))
                            {
                                msg = x.Value.ToString();
                            }
                        }
                        string sapNumber = "";
                        if (isSuccess)
                        {
                            foreach (var x in jObject)
                            {
                                if (x.Key.Equals("data"))
                                {
                                    if (x.Value.ToString() != "[]")
                                    {
                                        JArray jsonArray = JArray.Parse(x.Value.ToString());
                                        for (int i = 0; i < jsonArray.Count(); i++)
                                        {
                                            JObject data = JObject.Parse(jsonArray[i].ToString());
                                            foreach (var q in data)
                                            {
                                                if (q.Key.Equals("sap_number"))
                                                {
                                                    sapNumber = q.Value.ToString();
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            panel1.Controls.Clear();
                            foreach (var x in jObject)
                            {
                                if (x.Key.Equals("data"))
                                {
                                    if (x.Value.ToString() != "[]")
                                    {
                                        int    labelY = 13, lineY = 65;
                                        JArray jsonArray = JArray.Parse(x.Value.ToString());
                                        for (int i = 0; i < jsonArray.Count(); i++)
                                        {
                                            JObject data           = JObject.Parse(jsonArray[i].ToString());
                                            Label   labelReference = new Label();
                                            labelReference.AutoSize = true;
                                            labelReference.Location = new Point(16, labelY);
                                            labelReference.Cursor   = Cursors.Hand;
                                            labelReference.Font     = new Font("Arial", 15, FontStyle.Bold);
                                            Panel panelLine = new Panel();
                                            panelLine.BackColor = Color.Black;
                                            panelLine.Anchor    = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
                                            panelLine.Size      = new Size(734, 3);
                                            panelLine.Location  = new Point(4, lineY);
                                            string reference = "";
                                            int    id        = 0;
                                            foreach (var q in data)
                                            {
                                                if (q.Key.Equals("reference"))
                                                {
                                                    labelReference.Text = q.Value.ToString() + Environment.NewLine + "#: " + sapNumber;
                                                    reference           = q.Value.ToString();
                                                }
                                                else if (q.Key.Equals("id"))
                                                {
                                                    id = Convert.ToInt32(q.Value.ToString());
                                                    labelReference.Tag = q.Value.ToString();
                                                }
                                            }


                                            labelReference.Click += new EventHandler(labelReference_click);

                                            panel1.Controls.Add(labelReference);
                                            panel1.Controls.Add(panelLine);
                                            labelY += 46;
                                            lineY  += 60;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(msg, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        MessageBox.Show(response.ErrorMessage, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }