コード例 #1
0
 private void OnSaveGameGettingSaved()
 {
     sapi.WorldManager.SaveGame.StoreData("playerMapMarkers", JsonUtil.ToBytes(Waypoints));
 }
コード例 #2
0
        public static void Load()
        {
            // Load defaults
            LANGS.ForEach(l => {
                var lpath = $"{UEssentials.TranslationFolder}lang_{l}.json";
                if (!File.Exists(lpath))
                {
                    LoadDefault(l);
                }
            });

            var locale          = UEssentials.Config.Locale.ToLowerInvariant();
            var translationPath = $"{UEssentials.TranslationFolder}lang_{locale}.json";

            if (!File.Exists(translationPath))
            {
                if (LANGS.Contains(locale))
                {
                    LoadDefault(locale);
                }
                else
                {
                    UEssentials.Logger.LogError($"Invalid locale '{locale}', " +
                                                $"File not found '{translationPath}'");
                    UEssentials.Logger.LogError("Switching to default locale (en)...");
                    locale          = "en";
                    translationPath = $"{UEssentials.TranslationFolder}lang_{locale}.json";
                }
            }

            JObject json;

            try {
                json = JObject.Parse(File.ReadAllText(translationPath));

                /*
                 *  Update translation
                 */
                var defaultJson = JObject.Load(new JsonTextReader(new StreamReader(
                                                                      GetDefaultStream(locale), Encoding.UTF8, true)));

                if (defaultJson.Count != json.Count)
                {
                    foreach (var key in  defaultJson)
                    {
                        JToken outVal;
                        if (json.TryGetValue(key.Key, out outVal))
                        {
                            defaultJson[key.Key] = outVal;
                        }
                    }

                    File.WriteAllText(translationPath, string.Empty);
                    JsonUtil.Serialize(translationPath, defaultJson);
                    json = defaultJson;
                }
            } catch (JsonReaderException ex) {
                UEssentials.Logger.LogError($"Invalid translation ({translationPath})");
                UEssentials.Logger.LogError(ex.Message);

                // Load default
                json = JObject.Load(new JsonTextReader(new StreamReader(
                                                           GetDefaultStream(locale), Encoding.UTF8, true)));
            }

            _translations.Clear();
            foreach (var entry in json)
            {
                _translations.Add(entry.Key, entry.Value.Value <string>());
            }
        }
コード例 #3
0
    public void SetHeatmapData(string json)
    {
//		Debug.Log("json:"+json);
        SimpleJSON.JSONArray hms = (SimpleJSON.JSONArray)SimpleJSON.JSONArray.Parse(json).AsArray;         // get list of objects from string memory and convert to json array
        Debug.Log("heatmap obj:" + hms.ToString());
        foreach (SimpleJSON.JSONClass n in hms)
        {
            // Create a new heatmap avatar data class and populate it
            HeatmapData data = new HeatmapData();
            // Instantaite and
            data.avatar     = (HeatmapAvatar)Instantiate(avatarPrefab).GetComponent <HeatmapAvatar>() as HeatmapAvatar;
            data.avatarJson = n["avatarJson"];
            foreach (SimpleJSON.JSONClass nn in n["positions"]["points"].AsArray.Childs)
            {
                // Add all the heatmap posiitons to the avatar class list so we can iterate through them and move the 3d avatar around
                if (nn["pos"].ToString().Contains(","))
                {
                    data.avatar.positions.Add(JsonUtil.GetRealPositionFromTruncatedPosition(nn["pos"]));
                }
            }
            data.name = n["name"];
            data.cls  = n["class"];
            heatmaps.Add(data);


            // set costume and colors of 3d Avatar object
            data.avatar.transform.position = data.avatar.positions[1];
            SimpleJSON.JSONClass avatarJson = (SimpleJSON.JSONClass)SimpleJSON.JSONClass.Parse(data.avatarJson);
            Color bodyColor = PlayerCostumeController.inst.allMaterials[avatarJson["BodyColorIndex"].AsInt].color;

            data.avatar.SetHeatmapAvatarProperties(bodyColor, data.name);
            data.avatar.gameObject.name = "instnaced avatar ata time;" + Time.time;
            data.avatar.GetComponentInChildren <PlayerCostumeController>().SetCharacterMaterials(data.avatarJson);

            // Instantaite a 2d legend item for managing this avatar
            GameObject legendObj = (GameObject)Instantiate(legendObjectPrefab);
//			Debug.Log("made legend.:"+data.avatar.name);
            // Was a class already existing for this legend object?
            bool       parentWasSet   = false;
            GameObject legendObjClass = null;
            foreach (HeatmapLegendItemClass clss in FindObjectsOfType <HeatmapLegendItemClass>())
            {
                if (clss.className == data.cls)
                {
                    legendObjClass = clss.gameObject;
                    legendObj.transform.SetParent(clss.transform); // all avatar legend objs are children of classes
                    parentWasSet = true;                           // We are done, no need to create cls object
                }
            }
            if (!parentWasSet)
            {
                // no cls obj found, create cls object
                legendObjClass = (GameObject)Instantiate(legendObjectPrefabClass);
                HeatmapLegendItemClass clss = legendObjClass.GetComponent <HeatmapLegendItemClass>();
                clss.className          = data.cls;             // set the name of this class object (there will only be one class object with this name)
                clss.classNameText.text = data.cls;             // redundant but is the visiable 2d text obj not the hidden string ..lol
                legendObjClass.transform.SetParent(legendList); // classes are a child of the master legend list, all avatar legend objs are children of classes
                legendObj.transform.SetParent(legendObjClass.transform);
            }

            // Finally set the height of the class item based on number of items in that class, so that heights all line up
            if (legendObjClass)              // should have been set from either finidng the pre-existing class obj in the foreach, or creating on if !parentWasSet
            {
                legendObjClass.GetComponent <HeatmapLegendItemClass>().UpdateRectHeight();
            }

            HeatmapLegendItem legendItem = legendObj.GetComponent <HeatmapLegendItem>();
            string            totalTime  = Utils.DisplayAsTimeFromSeconds(data.avatar.positions.Count * heatmapTimeInterval);
            Color             hairColor  = PlayerCostumeController.inst.allMaterials[avatarJson["HairColorIndex"].AsInt].color;
            Color             headColor  = PlayerCostumeController.inst.allMaterials[avatarJson["HeadColorIndex"].AsInt].color;
            legendItem.SetHeatmapLegendProperties(data.avatar, data.name, data.cls, totalTime, bodyColor, headColor, hairColor);
            data.legendObject = legendObj;

            if (!snappedThisPlay)              //only do once.
            {
                snappedThisPlay = true;
                LevelBuilder.inst.SnapPanToPosition(data.avatar.transform.position);
            }
            if (debug)
            {
                WebGLComm.inst.Debug("Created;" + data.avatar.name);
            }

            // Create the objects from string memory.

            // Note that this creates the peice wherever it was in world space when the copy was made, so we'll reposition the items to current mouse pos after creation.
        }

        // Whew, we're done populating heatmap data and 2d and corresponding map 3d objects!
        // Now calculate how high the 2d content is so it all fits in the scrollRect!

        float avgChildHeight = 40f;
        float heatmapsHeight = 500 + Mathf.Max(0, (heatmaps.Count - 8) * avgChildHeight);    // each heatmap avatar 2d has a height about 40
        float classesHeight  = FindObjectsOfType <HeatmapLegendItemClass>().Length * 100f;   // classes have height too
        float totalHeight    = heatmapsHeight + classesHeight;

        legendScroll.content.sizeDelta = new Vector2(0, heatmapsHeight + classesHeight);
//		EnableControls();
    }
コード例 #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="spId"></param>
        /// <param name="spCount"></param>
        /// <param name="token"></param>
        /// <param name="isSC">是否来自于购物车</param>
        /// <returns></returns>
        public string WapPay(string spId, string spCount, string token, int isSC, int cityId, int exId, string exName,
                             string addres, string consignee, string phone, int isInvoice, int payid, string payName, string ramrk,
                             string invoicePayable, string businessName, string taxpayerNumber, string billContactPhone, string billContactEmail, string billContent, int IsSample)
        {
            var user = UserService.CkToken(token);

            if (user != null)
            {
                OrderListModel        orderList = new OrderListModel();
                long                  orderId   = 0;
                var                   idList    = spId.Split(',').Select(x => int.Parse(x)).ToList();
                var                   spcList   = spCount.Split(',').Select(x => int.Parse(x)).ToList();
                List <CommodityModel> comDtl    = new List <CommodityModel>();
                #region 获取基础数据
                if (isSC == 1)
                {
                    //获取购物车信息
                    var comStr = CommodityService.Instance.GetShoppingInId(token, spId);
                    comDtl = JsonUtil.Deserialize <List <CommodityModel> >(comStr);
                }
                else
                {
                    var data = CommodityService.Instance.GetCommodityInfo(Convert.ToInt32(spId));
                    comDtl.Add(JsonUtil.Deserialize <CommodityModel>(data));
                }
                #endregion
                //生成订单
                List <OrderDtlModel> oderDtl = new List <OrderDtlModel>();
                double orderAmount           = 0;
                #region 订单明细
                int weight = 0; //订单重量
                foreach (var cm in comDtl)
                {
                    int           cIndex = idList.FindIndex(o => o == cm.CommodityId);
                    OrderDtlModel dtl    = new OrderDtlModel();
                    dtl.CommodityId        = cm.CommodityId;
                    dtl.CommodityName      = cm.CommodityName;
                    dtl.CommodityGeneral   = cm.CommodityGeneral;
                    dtl.CommodityPrice     = cm.CommodityPrice;
                    dtl.CommodityUnitName  = cm.UnitIdName;
                    dtl.CommoditySpec      = cm.CommoditySpec;
                    dtl.CommodityBrandId   = cm.CommodityBrandId;
                    dtl.CommodityBrandName = cm.BrandName;
                    dtl.CommodityFamilyId  = cm.CommodityFamilyId;
                    dtl.CommodityImg       = cm.CommodityImg;
                    dtl.CommodityIndex     = cm.CommodityIndex;
                    dtl.CommodityCode      = cm.CommodityCode;
                    dtl.CommodityRH        = cm.CommodityRH;
                    dtl.CommodityRM        = cm.CommodityRM;
                    dtl.CommodityFL        = cm.CommodityFL;
                    dtl.UserId             = user.Uid;
                    dtl.CommNumber         = spcList[cIndex];
                    dtl.OriginalTotalPrice = spcList[cIndex] * (cm.CommodityPrice * cm.CommoditySpec);
                    orderAmount            = orderAmount + spcList[cIndex] * (cm.CommodityPrice * cm.CommoditySpec);
                    weight = weight + cm.CommoditySpec * dtl.CommNumber;
                    oderDtl.Add(dtl);
                }
                #endregion
                orderList.OrdrList   = oderDtl;
                orderList.OrderPrice = orderAmount;
                orderList.IsSample   = IsSample;
                //计算运费
                string cityStr  = CityExLogisticsAmountService.Instance.GetCityExLogisticsAmount(cityId, exId);
                var    cityData = JsonUtil.Deserialize <CityExLogisticsAmountModel>(cityStr);
                if (IsSample == 1)
                {
                    orderList.OrderAmount = 0;
                    orderList.NameExpress = string.Empty;
                }
                else
                {
                    orderList.Weight        = weight;
                    orderList.ExpressAmount = cityData.Amount * weight;
                    orderList.OrderAmount   = orderList.OrderPrice + orderList.ExpressAmount;
                    orderList.NameExpress   = exName;
                }
                orderList.ReceivingAddress  = addres;
                orderList.Consignee         = consignee;
                orderList.Telephone         = phone;
                orderList.IsInvoice         = isInvoice;
                orderList.PaymentMethod     = payid;
                orderList.PaymentMethodName = payName;
                orderList.Remarks           = ramrk;
                //保存发票抬头信息
                #region 发票
                OrderInvoiceModel invoice = new OrderInvoiceModel();
                invoice.InvoicePayable   = invoicePayable;
                invoice.BusinessName     = businessName;
                invoice.TaxpayerNumber   = taxpayerNumber;
                invoice.BillContactPhone = billContactPhone;
                invoice.BillContactEmail = billContactEmail;
                invoice.BillContent      = billContent;
                invoice.UserId           = user.Uid;
                invoice.InvoiceAmount    = orderList.OrderAmount;
                #endregion
                InsertOrderList(orderList, user.Uid, invoice, ref orderId);
                if (isSC == 1)
                {
                    //删除购物车
                    CommodityService.Instance.DeleteShopping(spId, token);
                }
                string key     = CryptoUtil.GetRandomAesKey();
                string wapSpId = CryptoUtil.AesEncryptHex(orderId.ToString(), key);
                CacheHelp.Set(wapSpId, DateTimeOffset.Now.AddDays(1), orderId.ToString());
                return(wapPay(orderList, orderId, IsSample, wapSpId));
            }
            else
            {
                return(UserService.ckTokenState());
            }
        }
コード例 #5
0
 protected internal virtual IList <string> readProcessInstanceIds(JsonObject jsonObject)
 {
     return(JsonUtil.asStringList(JsonUtil.getArray(jsonObject, PROCESS_INSTANCE_IDS)));
 }
        public void FindDeployTaskWithSyncTest()
        {
            _esSession.Open();
            AddDeployTaskTest();
            QueryDeployParam queryDeployParam = new QueryDeployParam();

            queryDeployParam.PageNo         = 1;
            queryDeployParam.PageSize       = 20;
            queryDeployParam.TaskStatus     = "";//ConstMgr.HWESightTask.TASK_STATUS_RUNNING;
            queryDeployParam.TaskSourceName = "t";
            queryDeployParam.Order          = "taskName";
            queryDeployParam.OrderDesc      = true;
            WebOneESightParam <QueryDeployParam> queryParam = new WebOneESightParam <QueryDeployParam>();

            queryParam.ESightIP = _esSession.HWESightHost.HostIP;
            queryParam.Param    = queryDeployParam;
            LogUtil.HWLogger.API.Info("FindDeployTaskWithSyncTest queryParam:" + JsonUtil.SerializeObject(queryParam));

            QueryPageResult <HWESightTask> taskResult = _esSession.DeployWorker.FindDeployTaskWithSync(queryDeployParam);

            LogUtil.HWLogger.API.Info("FindDeployTaskWithSyncTest QueryPageResult:" + JsonUtil.SerializeObject(taskResult));
        }
コード例 #7
0
 public static void Save()
 {
     JsonUtil.Serialize(typeof(DataSetting).Name + ".ds", Default);
 }
コード例 #8
0
        public void FindAllSoftwareSourceTaskWithSyncTest()
        {
            List <HWESightTask> taskList = new List <HWESightTask>(ESightEngine.Instance.FindAllSoftwareSourceTaskWithSync());
            WebReturnResult <List <HWESightTask> > ret = new WebReturnResult <List <HWESightTask> >();

            ret.Code        = 0;
            ret.Description = "";
            ret.Data        = taskList;

            LogUtil.HWLogger.API.InfoFormat("FindAllSoftwareSourceTaskWithSyncTest Result:" + JsonUtil.SerializeObject(taskList));
        }
    public void Redo()
    {
        if (futureEvents.Count > 0)
        {
            LevelBuilderEvent ue = futureEvents[futureEvents.Count - 1];
            if (debug)
            {
                Debug.Log("<color=#9f9>Redo: " + ue.type + "</color> ueos:");
            }
            switch (ue.type)
            {
            case LevelBuilderEventType.Create:
                List <LevelBuilderEventObject> replacementGroup = new List <LevelBuilderEventObject>();
                foreach (LevelBuilderEventObject lbeo in ue.lbeos)
                {
                    if (debug)
                    {
                        Debug.Log("<color=5f5>Creating (</color><color=44f>do</color>): " + lbeo.uuid);
                    }
                    UserEditableObject ueo = LevelBuilderObjectManager.inst.PlaceObject(lbeo.N, SceneSerializationType.Class, lbeo.uuid);
                    replacementGroup.Add(new LevelBuilderEventObject(ueo, ueo.GetUuid(), JsonUtil.GetUeoBaseProps(new SimpleJSON.JSONClass(), ueo, SceneSerializationType.Class)));
                    ReconnectBrokenUuidsForUndeletedObjects(ueo, ueo.GetUuid());
                }
                ue.lbeos = replacementGroup;
                break;

            case LevelBuilderEventType.Delete:
                foreach (LevelBuilderEventObject lbeo in ue.lbeos)
                {
                    if (lbeo.ueo)
                    {
                        Destroy(lbeo.ueo.gameObject);
                    }
                }
                break;

            case LevelBuilderEventType.Modified:
                foreach (LevelBuilderEventObject lbeo in ue.lbeos)
                {
                    lbeo.ueo.SetProperties(lbeo.N);
                    lbeo.ueo.SetTransformProperties(lbeo.N);
                }
                break;

            default: break;
//				Debug.Log("redoing properties of:"+ue.obj.name+", set prop to:"+ue.prop.ToString());
//				ue.obj.GetComponent<UserEditableObject>().SetProperties(ue.prop);
            }
            futureEvents.Remove(ue);
            pastEvents.Add(ue);
        }
    }
コード例 #10
0
        public static async Task SetupAsync(IWebApi webApi, string awsAccessKeyId, string awsSecretAccessKey, string awsTopicArn, string awsEndPoint, string awsBucketName, Func <string, string, string[], Task <string> > handler)
        {
            if (!string.IsNullOrEmpty(awsEndPoint))
            {
                Uri endPointUri = new Uri(awsEndPoint);
                //logger.Debug($"SetupWebApi():endPointUri.PathAndQuery={endPointUri.PathAndQuery}");

                using (AmazonSimpleNotificationServiceClient amazonSimpleNotificationServiceClient = new AmazonSimpleNotificationServiceClient(awsAccessKeyId, awsSecretAccessKey, Amazon.RegionEndpoint.USEast1)) {
                    SubscribeResponse subscribeResponse = await amazonSimpleNotificationServiceClient.SubscribeAsync(new SubscribeRequest {
                        TopicArn = awsTopicArn,
                        Protocol = endPointUri.Scheme,
                        Endpoint = awsEndPoint
                    });
                }

                AmazonS3Client amazonS3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

                webApi.OnPost(
                    endPointUri.PathAndQuery,
                    async(req, res) => {
                    logger.Debug($"{endPointUri.PathAndQuery}");
                    Dict evt = await req.ParseAsJsonAsync <Dict>();
                    logger.Debug($"{endPointUri.PathAndQuery},evt=" + JsonUtil.Serialize(evt));
                    string type = evt.GetAs("Type", (string)null);
                    if (type == "SubscriptionConfirmation")
                    {
                        string subscribeUrl = evt.GetAs("SubscribeURL", (string)null);
                        using (WebClient webClient = new WebClient()) {
                            string result = await webClient.DownloadStringTaskAsync(new Uri(subscribeUrl));
                            logger.Debug($"{endPointUri.PathAndQuery},result=" + result);
                        }
                    }
                    else if (type == "Notification")
                    {
                        //string messageId = evt.GetAs("MessageId", (string)null);
                        string messageJson = evt.GetAs("Message", (string)null);
                        logger.Debug($"{endPointUri.PathAndQuery},messageJson={messageJson}");

                        Dict message = JsonUtil.Deserialize <Dict>(messageJson);
                        Dict mail    = message.GetAs("mail", (Dict)null);

                        Dict[] headers       = mail.GetAs("headers", (Dict[])null);
                        Dict inReplyToHeader = Array.Find(headers, x => x.GetAs("name", "") == "In-Reply-To");
                        string inReplyTo     = inReplyToHeader.GetAs("value", "");
                        logger.Debug($"{endPointUri.PathAndQuery},inReplyTo={inReplyTo}");
                        Match match = IN_REPLY_TO_REGEX.Match(inReplyTo);
                        if (match.Success)
                        {
                            string sentMessageId = match.Groups[1].Value;
                            string bucketKey     = mail.GetAs("messageId", (string)null);
                            logger.Debug($"{endPointUri.PathAndQuery},sentMessageId={sentMessageId},bucketKey={bucketKey}");
                            if (!string.IsNullOrEmpty(bucketKey))
                            {
                                GetObjectResponse getObjectResponse = await amazonS3Client.GetObjectAsync(new GetObjectRequest {
                                    BucketName = awsBucketName,
                                    Key        = bucketKey
                                });
                                logger.Debug($"{endPointUri.PathAndQuery},getObjectResponse={getObjectResponse}");

                                MimeMessage mimeMessage = await MimeMessage.LoadAsync(getObjectResponse.ResponseStream);
                                logger.Debug($"{endPointUri.PathAndQuery},mimeMessage={mimeMessage}");

                                await handler(sentMessageId, mimeMessage.TextBody, new string[] { });
                            }
                        }
                    }
                }
                    );
            }
        }
コード例 #11
0
        public void FindAllBasePackageTaskWithSyncTest()
        {
            IList <HWESightTask> taskList = ESightEngine.Instance.FindAllBasePackageTaskWithSync();

            LogUtil.HWLogger.API.InfoFormat("FindAllBasePackageTaskWithSyncTest Result:" + JsonUtil.SerializeObject(taskList));
        }
コード例 #12
0
        public void InitBone(string saveAvatarName = "", string exportAvatarName = "")
        {
            if (bones == null)
            {
                bones = new List <BoneInfo>();
            }

            var ss = this.transform.GetComponentsInChildren <SkinnedMeshRenderer> ();

            foreach (var s in ss)
            {
                if (s.sharedMesh != null)
                {
                    for (int i = 0; i < s.bones.Length; i++)
                    {
                        var  b    = s.bones [i];
                        bool bnew = true;
                        foreach (var _b in bones)
                        {
                            if (_b.bone == b)
                            {
                                bnew = false;
                                break;
                            }
                        }
                        if (bnew)
                        {
                            var binfo = new BoneInfo();
                            binfo.bone  = b;
                            binfo.tpose = s.sharedMesh.bindposes [i];
                            bones.Add(binfo);
                        }
                    }
                }
            }

            //骨骼配置文件操作
            if (!string.IsNullOrEmpty(saveAvatarName) || !string.IsNullOrEmpty(exportAvatarName))
            {
                //先记录下当前骨骼的信息
                Dictionary <string, string> curDic = new Dictionary <string, string> ();
                for (int i = 0; i < bones.Count; i++)
                {
                    curDic.Add(bones [i].bone.name, bones [i].tpose.ToString());
                }

                string avatarInfoName = !string.IsNullOrEmpty(saveAvatarName) ? saveAvatarName : exportAvatarName;
                Dictionary <string, string> allDic;
                string infoPath = AvatarInfoPath + avatarInfoName + ".txt";

                if (!string.IsNullOrEmpty(exportAvatarName))
                {
                    if (File.Exists(infoPath))
                    {
                        string ctx = File.ReadAllText(infoPath);
                        try {
                            allDic = JsonUtil.DeserializeObject <Dictionary <string, string> > (ctx);
                        } catch {
                            allDic = new Dictionary <string, string> ();
                        }

                        //将配置中所有的节点添加进去
                        foreach (KeyValuePair <string, string> item in allDic)
                        {
                            if (!curDic.ContainsKey(item.Key))
                            {
                                if (item.Key == "shoulder_R")
                                {
                                    Debug.Log("aaa");
                                }
                                var binfo = new BoneInfo();
                                binfo.bone  = getTransform(this.transform, item.Key);
                                binfo.tpose = getMatrixByString(item.Value);
                                bones.Add(binfo);
                            }
                        }
                    }
                }
                else
                {
                    StartCoroutine(WaitForSaveConfig(infoPath, curDic));
                }
            }

            //自动添加asbone对象
            var ss2 = this.transform.GetComponentsInChildren <Asbone>();

            foreach (var asb in ss2)
            {
                var  b    = asb.transform;
                bool bnew = true;
                foreach (var _b in bones)
                {
                    if (_b.bone == b)
                    {
                        bnew = false;
                        break;
                    }
                }
                if (bnew)
                {
                    var binfo = new BoneInfo();
                    binfo.bone  = b;
                    binfo.tpose = Matrix4x4.identity;
                    bones.Add(binfo);
                }
            }
        }
コード例 #13
0
        /// <summary>
        ///请求FD接口
        /// </summary>
        public ApiResult <string> GetVersion(object eventData)
        {
            ApiResult <string> ret     = new ApiResult <string>(ErrorCode.SYS_UNKNOWN_ERR, "");
            string             version = "1.0.0.0";

            try
            {
                //1. 获取数据
                string   fileVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                string[] arrVersion  = fileVersion.Split('.');
                if (arrVersion.Length >= 3)
                {
                    version = string.Format("{0}.{1}.{2}", arrVersion[0], arrVersion[1], arrVersion[2]);
                }
                else
                {
                    version = fileVersion;
                }
                //2. 返回数据
                ret.Code = "0";
                ret.Data = version;
                LogUtil.HWLogger.UI.InfoFormat("Get version successful, the ret is [{0}]", JsonUtil.SerializeObject(ret));
            }
            catch (BaseException ex)
            {
                LogUtil.HWLogger.UI.Error("Get version failed: ", ex);
                ret.Code = ex.Code;
            }
            catch (Exception ex)
            {
                LogUtil.HWLogger.UI.Error("Get version failed: ", ex);
                ret.Code = ErrorCode.SYS_UNKNOWN_ERR;
            }
            return(ret);
        }
コード例 #14
0
 public SavedInfo(float time, string command)
 {
     Time = time;
     JsonUtil.TryConvertJson(command, out Command);
 }
コード例 #15
0
 /// <summary>
 /// 从文件里转换为数据
 /// </summary>
 /// <param name="file">文件</param>
 /// <returns>数据</returns>
 protected override T ConvertFromFile(string file) => JsonUtil.DeserializeFromFile <T>(file);
コード例 #16
0
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public ActionResult loginvalid(string username, string password, string lan)
        {
            //FileLogUtil.info("username:"******"Username don`t existed");
                //data = JsonUtil.convertToJson(appError, typeof(AppError));
            }
            if (user != null)
            {
                if (!user.depassword.Equals(password))
                {
                    AppError appError = new AppError(AppError.usernameOrpasswordError, "Username or password error");
                    data = JsonUtil.convertToJson(appError, typeof(AppError));
                }
                else
                {
                    MonitorType energyMt    = MonitorType.getMonitorTypeByCode(MonitorType.PLANT_MONITORITEM_ENERGY_CODE);
                    MonitorType powerMt     = MonitorType.getMonitorTypeByCode(MonitorType.PLANT_MONITORITEM_POWER_CODE);
                    UserPlantVO userPlantVO = new UserPlantVO();
                    userPlantVO.totalEnergy      = user.upTotalEnergy;
                    userPlantVO.totalEnergyUnit  = user.TotalEnergyUnit;
                    userPlantVO.todayEnergy      = user.upTotalDayEnergy;
                    userPlantVO.todayEnergyUnit  = user.TotalDayEnergyUnit;
                    userPlantVO.userId           = user.id;
                    userPlantVO.username         = user.username;
                    userPlantVO.co2Reduction     = user.TotalReductiong;
                    userPlantVO.co2ReductionUnit = user.TotalReductiongUnit;
                    userPlantVO.revenue          = Math.Round(user.revenue, 2);
                    userPlantVO.revenueUnit      = user.currencies;
                    userPlantVO.power            = user.upTotalPower;
                    userPlantVO.powerUnit        = user.TotalPowerUnit;
                    userPlantVO.families         = user.TotalFamilies.ToString();
                    IList <int> workYears = CollectorYearDataService.GetInstance().GetWorkYears(user.plants);
                    userPlantVO.warnNums = FaultService.GetInstance().getNewLogNums(user.plants, workYears);
                    userPlantVO.plants   = convertToSPlantVOs(user.plants);

                    data = JsonUtil.convertToJson(userPlantVO, typeof(UserPlantVO));
                }
            }
            else
            {
                AppError appError = new AppError(AppError.usernameOrpasswordError, "Username don`t existed");
                data = JsonUtil.convertToJson(appError, typeof(AppError));
            }
            return(Content(data));
        }
コード例 #17
0
ファイル: PACServer.cs プロジェクト: keyonchen/sysproxy
        private void UpdatePACFile()
        {
            string gfwlist;

            try
            {
                gfwlist = File.ReadAllText(Path.Combine(directory, gfwlist_file), Encoding.UTF8);
            }
            catch
            {
                gfwlist = Resources.gfwlist;
                File.WriteAllText(Path.Combine(directory, gfwlist_file), gfwlist, Encoding.UTF8);
            }
            string userRule;
            string userPath = Path.Combine(directory, user_rule_file);

            if (!File.Exists(userPath))
            {
                userRule = Resources.user_rule;
                File.WriteAllText(Path.Combine(directory, user_rule_file), userRule, Encoding.UTF8);
            }
            else
            {
                //以只读共享方式打开文件
                using (FileStream fs = new FileStream(userPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    int    length  = (int)fs.Length;
                    byte[] content = new byte[length];
                    fs.Read(content, 0, content.Length);
                    userRule = Encoding.UTF8.GetString(content);
                }
            }
            string abpContent;

            try
            {
                abpContent = File.ReadAllText(Path.Combine(directory, abp_js_file), Encoding.UTF8);
            }
            catch
            {
                FileUtil.UnGzip(Path.Combine(directory, abp_js_file), Resources.abp_js);
                abpContent = File.ReadAllText(Path.Combine(directory, abp_js_file), Encoding.UTF8);
            }
            try
            {
                List <string> lines = FileUtil.ParseResult(gfwlist);
                using (var sr = new StringReader(userRule))
                {
                    foreach (var rule in sr.NonWhiteSpaceLines())
                    {
                        if (rule.BeginWithAny(FileUtil.IgnoredLineBegins))
                        {
                            continue;
                        }
                        lines.Add(rule);
                    }
                }
                abpContent = abpContent.Replace("__PROXY__", $"PROXY 127.0.0.1:{remotePort}");
                abpContent = abpContent.Replace("__RULES__", JsonUtil.SerializeObject(lines));
                if (File.Exists(Path.Combine(directory, pac_file)))
                {
                    string original = File.ReadAllText(Path.Combine(directory, pac_file), Encoding.UTF8);
                    if (original == abpContent)
                    {
                        return;
                    }
                }
                File.WriteAllText(Path.Combine(directory, pac_file), abpContent, Encoding.UTF8);
                BalloonTip tip = new BalloonTip()
                {
                    IconIndex = 1,
                    Message   = "Update PAC file success",
                    timeout   = 3000
                };
                ShowBalloonTip?.Invoke(this, tip);
            }
            catch (Exception)
            {
                BalloonTip tip = new BalloonTip()
                {
                    IconIndex = 1,
                    Message   = "Update PAC file fail",
                    timeout   = 3000
                };
                ShowBalloonTip?.Invoke(this, tip);
            }
        }
コード例 #18
0
        /// <summary>
        /// 取得用户的所有故障列表
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="pagecount">第几页</param>
        /// <param name="pagesize">每页显示数量</param>
        /// <param name="errortype">告警类型:all是所有,error:错误,warning:警告,fault:故障,inf:信息</param>
        /// <param name="errorby">排序字段</param>
        /// <returns></returns>
        public ActionResult ErrorList(int userId, string pagecount, string pagesize, string errortype, string errorby, string lan)
        {
            setlan(lan);
            User        user      = UserService.GetInstance().Get(userId);
            IList <int> years     = CollectorYearDataService.GetInstance().GetWorkYears(user.plants);
            int         manyear   = years.Count > 0 ? years[0] : DateTime.Now.Year;
            DateTime    startTime = Convert.ToDateTime(string.Format("{0}-{1}", manyear, "01-01"));
            DateTime    endTime   = DateTime.Now;
            int         psize     = 0;

            int.TryParse(pagesize, out psize);
            FaultService service = FaultService.GetInstance();

            string inforank = "";

            if (errortype.Equals("all"))
            {
                inforank = ErrorType.ERROR_TYPE_ERROR + "," + ErrorType.ERROR_TYPE_FAULT + "," + ErrorType.ERROR_TYPE_INFORMATRION + "," + ErrorType.ERROR_TYPE_WARN;
            }
            if (errortype.Equals("error"))
            {
                inforank = ErrorType.ERROR_TYPE_ERROR.ToString();
            }
            if (errortype.Equals("warning"))
            {
                inforank = ErrorType.ERROR_TYPE_WARN.ToString();
            }
            if (errortype.Equals("fault"))
            {
                inforank = ErrorType.ERROR_TYPE_FAULT.ToString();
            }
            if (errortype.Equals("info"))
            {
                inforank = ErrorType.ERROR_TYPE_INFORMATRION.ToString();
            }

            Hashtable table = new Hashtable();
            Pager     page  = new Pager()
            {
                PageIndex = int.Parse(pagecount), PageSize = psize
            };

            table.Add("page", page);
            table.Add("user", user);
            table.Add("startTime", startTime);
            table.Add("endTime", endTime);
            table.Add("items", inforank);
            table.Add("state", "0");

            service.GetAllLogs(table);
            IList <Fault> faultList = (IList <Fault>)table["source"];

            FaultVoResult faultResult = new FaultVoResult();

            faultResult.totalpagecount = page.PageCount;

            IList <FaultVO> faults  = new List <FaultVO>();
            FaultVO         faultVO = null;

            PlantUnit tmpunit;

            foreach (Fault fault in faultList)
            {
                faultVO = new FaultVO();
                //faultVO.deviceAddress = fault.address;
                faultVO.deviceAddress = fault.device.xinhaoName + "#" + fault.address; //临时方案,设备地址字段放设备设备型号名称+地址,这样不用修改app
                //faultVO.deviceModel =  fault.device.xinhaoName;
                faultVO.deviceModel = fault.device.typeName;;                          //临时方案,设备型号字段放设备类型,这样不用修改app
                //faultVO.deviceType = fault.device.typeName;
                tmpunit             = PlantUnitService.GetInstance().GetPlantUnitByCollectorId(fault.collectorID);
                faultVO.deviceType  = tmpunit.displayname;//临时方案,设备类型字段放单元名称,这样不用修改app
                faultVO.faultDesc   = fault.content;
                faultVO.faultId     = fault.id;
                faultVO.isConfirmed = fault.confirm ? "true" : "false";
                faultVO.datetime    = fault.sendTime.ToString("yyyy-MM-dd HH:mm:ss");
                faultVO.errorType   = getAppErrorType(fault.errorTypeCode);
                faults.Add(faultVO);
            }

            faultResult.faults = faults;
            string data = JsonUtil.convertToJson(faultResult, typeof(FaultVoResult));

            return(Content(data));
        }
コード例 #19
0
 /// <summary>
 /// 添加Json参数
 /// </summary>
 /// <typeparam name="T">实体类型</typeparam>
 /// <param name="value">值</param>
 /// <returns></returns>
 public TRequest JsonData <T>(T value)
 {
     ContentType(HttpContentType.Json);
     _data = JsonUtil.ToJson(value);
     return(This());
 }
コード例 #20
0
        /// <summary>
        /// 取得设备详细信息
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult Deviceinfo(int did, string lan)
        {
            setlan(lan);

            string data;
            Device device   = DeviceService.GetInstance().get(did);
            int    timezone = 0;

            try
            {
                PlantUnit plantUnit = PlantUnitService.GetInstance().GetPlantUnitByCollectorId(device.collectorID);
                Plant     plant     = PlantService.GetInstance().GetPlantInfoById(plantUnit.plantID);
                timezone = plant.timezone;
            }
            catch (Exception ee)
            {
                LogUtil.error(ee.Message);
            }

            if (device == null)
            {
                AppError appError = new AppError(AppError.devicenoexist, Resources.SunResource.CHART_DEVICE_DONT_EXISTED);
                data = JsonUtil.convertToJson(appError, typeof(AppError));
            }
            else
            {
                DeviceInfoVO vo = new DeviceInfoVO();
                vo.deviceId       = device.id;
                vo.deviceModel    = device.xinhaoName;
                vo.deviceType     = device.typeName;
                vo.deviceName     = device.fullName;
                vo.address        = device.deviceAddress;
                vo.deviceTypeCode = device.deviceTypeCode.ToString();

                if (device.deviceTypeCode == DeviceData.ENVRIOMENTMONITOR_CODE)
                {
                    MonitorType mt  = MonitorType.getMonitorTypeByCode(MonitorType.MIC_DETECTOR_SUNLINGHT);
                    string      str = mt.name + " :" + device.Sunlight + " " + mt.unit;
                    mt = MonitorType.getMonitorTypeByCode(MonitorType.MIC_DETECTOR_ENRIONMENTTEMPRATURE);
                    float tempr = device.runData == null ? 0 : device.runData.getMonitorValue(MonitorType.MIC_DETECTOR_ENRIONMENTTEMPRATURE);
                    str += "," + mt.name + " :" + tempr + " " + mt.unit;
                    mt   = MonitorType.getMonitorTypeByCode(MonitorType.MIC_DETECTOR_WINDSPEED);
                    double windspeed = device.getMonitorValue(MonitorType.MIC_DETECTOR_WINDSPEED);
                    str            += "," + mt.name + " :" + windspeed + " " + mt.unit;
                    vo.displayField = str;
                }
                else if (device.deviceTypeCode == DeviceData.HUILIUXIANG_CODE || device.deviceTypeCode == DeviceData.CABINET_CODE)
                {
                    MonitorType mt           = MonitorType.getMonitorTypeByCode(MonitorType.MIC_BUSBAR_TOTALCURRENT);
                    double      totalCurrent = device.getMonitorValue(mt.code);
                    string      str          = mt.name + " :" + totalCurrent + " " + mt.unit;
                    mt = MonitorType.getMonitorTypeByCode(MonitorType.MIC_BUSBAR_JNTEMPRATURE);
                    double tempr = device.getMonitorValue(mt.code);
                    str            += "," + mt.name + " :" + tempr + " " + mt.unit;
                    vo.displayField = str;
                }
                else if (device.deviceTypeCode == DeviceData.AMMETER_CODE)
                {
                    MonitorType mt           = MonitorType.getMonitorTypeByCode(MonitorType.MIC_AMMETER_POSITIVEACTIVEPOWERDEGREE);
                    float       totalCurrent = device.runData == null ? 0 : device.runData.getMonitorValue(mt.code);
                    string      str          = mt.name + " :" + totalCurrent + " " + mt.unit;
                    //mt = MonitorType.getMonitorTypeByCode(MonitorType.MIC_BUSBAR_JNTEMPRATURE);
                    //float tempr = device.runData == null ? 0 : float.Parse(device.runData.getMonitorValue(mt.code));
                    //str += "," + mt.name + " :" + tempr + " " + mt.unit;
                    vo.displayField = str;
                }
                else
                {
                    MonitorType TotalEmt = MonitorType.getMonitorTypeByCode(MonitorType.MIC_INVERTER_TOTALENERGY);
                    MonitorType TodayEmt = MonitorType.getMonitorTypeByCode(MonitorType.MIC_INVERTER_TODAYENERGY);
                    MonitorType mt       = MonitorType.getMonitorTypeByCode(MonitorType.MIC_INVERTER_TOTALYGPOWER);
                    string      str      = TodayEmt.name + " :" + device.TodayEnergy(timezone) + " " + TodayEmt.unit;
                    str            += "," + TotalEmt.name + " :" + device.TotalEnergy + " " + TotalEmt.unit;
                    str            += "," + mt.name + " :" + device.TotalPower + " " + mt.unit;
                    vo.displayField = str;
                }
                vo.workStatus     = device.status;
                vo.lastUpdateTime = CalenderUtil.formatDate(device.runData.updateTime, "yyyy-MM-dd HH:mm:ss");
                vo.hasChart       = (device.deviceTypeCode == DeviceData.INVERTER_CODE || device.deviceTypeCode == DeviceData.ENVRIOMENTMONITOR_CODE || device.deviceTypeCode == DeviceData.HUILIUXIANG_CODE || device.deviceTypeCode == DeviceData.AMMETER_CODE || device.deviceTypeCode == DeviceData.CABINET_CODE) ? "true" : "false";
                vo.datas          = convertToSPlantVOs(device.runData.convertRunstrToList(true, device.deviceTypeCode));
                data = JsonUtil.convertToJson(vo, typeof(DeviceInfoVO));
            }
            return(Content(data));
        }
コード例 #21
0
        /// <inheritdoc/>
        public IList <WorkType> Query(string query, SortOrder sort, PagingQuery paging)
        {
            var sqlWhere = new StringBuilder();

            if (!string.IsNullOrEmpty(query))
            {
                sqlWhere.AppendLine(" AND ( ");
                sqlWhere.AppendLine("     WorkTypeCode LIKE @Query OR ");
                sqlWhere.AppendLine("     WorkTypeTree LIKE @Query OR ");
                sqlWhere.AppendLine("     Name LIKE @Query OR ");
                sqlWhere.AppendLine("     WorkTypeId IN ( ");
                sqlWhere.AppendLine("         SELECT TargetId ");
                sqlWhere.AppendLine("         FROM   Tag AS TG1 WITH (NOLOCK) ");
                sqlWhere.AppendLine("         WHERE  TG1.TargetTable = 'WorkType' ");
                sqlWhere.AppendLine("         AND    TG1.Value = @TagQuery ");
                sqlWhere.AppendLine("     ) ");
                sqlWhere.AppendLine(" ) ");
            }

            var sqlSort = new StringBuilder();

            if (sort.Count == 0)
            {
                sqlSort.AppendLine(" ORDER BY {0}.SortNo ASC, {0}.WorkTypeTree ASC ");
            }
            else
            {
                sqlSort.AppendLine(" ORDER BY ");
                foreach (var item in sort)
                {
                    if (item.Field.Equals("WorkTypeCode", StringComparison.OrdinalIgnoreCase))
                    {
                        sqlSort.Append(" {0}.WorkTypeCode " + item.SortType.ToString() + ",");
                    }
                    else if (item.Field.Equals("WorkTypeTree", StringComparison.OrdinalIgnoreCase))
                    {
                        sqlSort.Append(" {0}.WorkTypeTree " + item.SortType.ToString() + ",");
                    }
                    else if (item.Field.Equals("SortNo", StringComparison.OrdinalIgnoreCase))
                    {
                        sqlSort.Append(" {0}.SortNo " + item.SortType.ToString() + ",");
                    }
                    else if (item.Field.Equals("Name", StringComparison.OrdinalIgnoreCase))
                    {
                        sqlSort.Append(" {0}.Name " + item.SortType.ToString() + ",");
                    }
                    else if (item.Field.Equals("CreateTime", StringComparison.OrdinalIgnoreCase))
                    {
                        sqlSort.Append(" {0}.CreateTime " + item.SortType.ToString() + ",");
                    }
                }
                sqlSort.Length -= 1;
                sqlSort.AppendLine();
            }

            var param = new
            {
                Query    = DataUtil.EscapeLike(query, LikeMatchType.PrefixSearch),
                TagQuery = query,
                Page     = paging.Page,
                PageSize = paging.PageSize,
            };

            var sqlCount = new StringBuilder();

            sqlCount.AppendLine(" SELECT COUNT(*) FROM WorkType WHERE  1 = 1 ");
            sqlCount.AppendLine(sqlWhere.ToString());

            paging.TotalCount = (int)Connection.ExecuteScalar(
                sqlCount.ToString(),
                param,
                commandTimeout: DBSettings.CommandTimeout);

            var sql = new StringBuilder();

            sql.AppendLine(" SELECT GS1.* ");
            sql.AppendLine("      , (SELECT TG1.Value ");
            sql.AppendLine("           FROM Tag AS TG1 WITH (NOLOCK) ");
            sql.AppendLine("          WHERE TG1.TargetId = GS1.WorkTypeId ");
            sql.AppendLine("          ORDER BY TG1.Value ");
            sql.AppendLine("            FOR JSON PATH ");
            sql.AppendLine("        ) AS WorkTypeTags ");
            sql.AppendLine("   FROM WorkType AS GS1 ");
            sql.AppendLine("  WHERE 1 = 1 ");
            sql.AppendLine(sqlWhere.ToString());
            sql.AppendLine(string.Format(sqlSort.ToString(), "GS1"));
            sql.AppendLine(" OFFSET (@Page - 1) * @PageSize ROWS ");
            sql.AppendLine("  FETCH FIRST @PageSize ROWS ONLY ");

            return(Connection.Query <WorkType, string, WorkType>(
                       sql.ToString(),
                       (workType, workTypeTags) =>
            {
                workType.Tags = JsonUtil.Deserialize <List <string> >(JsonUtil.ToRawJsonArray(workTypeTags, "Value"));
                return workType;
            },
                       param,
                       splitOn: "WorkTypeTags",
                       commandTimeout: DBSettings.CommandTimeout).ToList());
        }
コード例 #22
0
        public void Flash(object flashObject)
        {
            string json = JsonUtil.ToJson(flashObject);

            Session[FLASH_KEY] = json;
        }
コード例 #23
0
        public override DeleteProcessInstanceBatchConfiguration toObject(JsonObject json)
        {
            DeleteProcessInstanceBatchConfiguration configuration = new DeleteProcessInstanceBatchConfiguration(readProcessInstanceIds(json), null, JsonUtil.getBoolean(json, SKIP_CUSTOM_LISTENERS), JsonUtil.getBoolean(json, SKIP_SUBPROCESSES), JsonUtil.getBoolean(json, FAIL_IF_NOT_EXISTS));

            string deleteReason = JsonUtil.getString(json, DELETE_REASON);

            if (!string.ReferenceEquals(deleteReason, null) && deleteReason.Length > 0)
            {
                configuration.DeleteReason = deleteReason;
            }

            return(configuration);
        }
コード例 #24
0
ファイル: Sc2Tv.cs プロジェクト: bibikov505/Ubiquitous2
    public void SetupPollers()
    {
        var oldMessageId = Chat.Config.GetParameterValue("LastMessageId") as long?;

        if (oldMessageId != null)
        {
            lastMessageId = (long)oldMessageId;
        }

        if (!String.IsNullOrWhiteSpace(channelId))
        {
            #region Chatpoller
            chatPoller = new WebPoller()
            {
                Id             = ChannelName,
                Uri            = new Uri(String.Format(@"http://chat.sc2tv.ru/memfs/channel-{0}.json", channelId)),
                IsLongPoll     = false,
                Interval       = 5000,
                TimeoutMs      = 10000,
                TimeoutOnError = false,
                IsAnonymous    = false,
                KeepAlive      = false,
                IsTimeStamped  = true,
            };
            chatPoller.ReadStream = (stream) =>
            {
                if (!Chat.Status.IsConnected)
                {
                    Chat.Status.IsConnected = true;
                    Chat.Status.IsLoggedIn  = !Chat.IsAnonymous;
                    JoinCallback(this);
                }

                if (stream == null)
                {
                    return;
                }

                lock (chatLock)
                {
                    var messagesJson = JsonUtil.DeserializeStream <dynamic>(stream);
                    if (messagesJson == null)
                    {
                        return;
                    }

                    var messages = JsonUtil.Sort(JsonUtil.ParseArray(messagesJson.messages), "id");
                    if (messages == null)
                    {
                        return;
                    }

                    foreach (var message in messages)
                    {
                        var messageId = (long?)message["id"];
                        var userName  = (string)message["name"];
                        var text      = (string)message["message"];
                        var date      = (string)message["date"];
                        var chanId    = (long?)message["channelId"];

                        if (messageId == null ||
                            String.IsNullOrEmpty(userName) ||
                            String.IsNullOrEmpty(text))
                        {
                            return;
                        }

                        if (lastMessageId >= messageId)
                        {
                            continue;
                        }

                        lastMessageId = (long)messageId;

                        Chat.Config.SetParameterValue("LastMessageId", lastMessageId);

                        if (ReadMessage != null)
                        {
                            ReadMessage(new ChatMessage()
                            {
                                Channel         = ChannelName,
                                ChatIconURL     = Chat.IconURL,
                                ChatName        = Chat.ChatName,
                                FromUserName    = userName,
                                HighlyImportant = false,
                                IsSentByMe      = false,
                                Text            = text,
                            });
                        }
                        Chat.UpdateStats();
                        ChannelStats.MessagesCount++;
                    }
                }
            };
            chatPoller.Start();
            #endregion

            ChannelStats.ViewersCount = 0;
            Chat.UpdateStats();
        }
    }
コード例 #25
0
 /// <summary>
 /// Marshals a feature store item into a JSON string. This is a convenience method for
 /// feature store implementations, so that they can use the same JSON library that is used
 /// within the LaunchDarkly SDK rather than importing one themselves. All of the storeable
 /// classes used by the SDK are guaranteed to support this type of serialization.
 /// </summary>
 /// <param name="item">the item to be marshaled</param>
 /// <returns>the JSON string</returns>
 public static string MarshalJson(IVersionedData item)
 {
     return(JsonUtil.EncodeJson(item));
 }
コード例 #26
0
ファイル: Sc2Tv.cs プロジェクト: bibikov505/Ubiquitous2
    public override void DownloadEmoticons(string url)
    {
        var rePattern = @"smiles[\s|=]*(\[.*?\]);";

        if (IsFallbackEmoticons && IsWebEmoticons)
        {
            return;
        }

        lock (iconParseLock)
        {
            var list = new List <Emoticon>();
            if (Emoticons == null)
            {
                Emoticons = new List <Emoticon>();
            }

            var jsonEmoticons = this.With(x => LoginWebClient.Download(url))
                                .With(x => Re.GetSubString(x, rePattern));

            if (jsonEmoticons == null)
            {
                Log.WriteError("Unable to get {0} emoticons!", ChatName);
                return;
            }
            else
            {
                var icons = JsonUtil.ParseArray(jsonEmoticons);
                if (icons == null)
                {
                    return;
                }

                foreach (var icon in icons)
                {
                    var code = (string)icon["code"];
                    var img  = (string)icon["img"];

                    if (String.IsNullOrWhiteSpace(code) || String.IsNullOrWhiteSpace(img))
                    {
                        continue;
                    }

                    var width  = (int?)icon["width"] ?? 30;
                    var height = (int?)icon["height"] ?? 30;

                    var smileUrl = "http://chat.sc2tv.ru/img/" + img;
                    list.Add(new Emoticon(":s" + code, smileUrl, (int)width, (int)height));
                }
                if (list.Count > 0)
                {
                    Emoticons = list.ToList();
                    if (IsFallbackEmoticons)
                    {
                        IsWebEmoticons = true;
                    }

                    IsFallbackEmoticons = true;
                }
            }
        }
    }
コード例 #27
0
ファイル: ioformatter.cs プロジェクト: nataren/DReAM
 public Stream Format(XDoc doc)
 {
     // TODO (steveb): convert XML to JSON without generating a string first
     byte[] bytes;
     if (!string.IsNullOrEmpty(_callback))
     {
         bytes = MimeType.JSON.CharSet.GetBytes(string.Format("{0}{1}({2});{3}", _prefix, _callback, JsonUtil.ToJson(doc), _postfix));
     }
     else
     {
         bytes = MimeType.JSON.CharSet.GetBytes(_prefix + JsonUtil.ToJson(doc) + _postfix);
     }
     return(new MemoryStream(bytes));
 }
コード例 #28
0
 /// <summary>
 /// Executes the script.
 /// </summary>
 /// <param name="function">The function.</param>
 /// <param name="data">The data.</param>
 public void ExecuteScript(string function, object data)
 {
     this.ExecuteScriptAsync($"{function}({JsonUtil.SerializeObject(data)})");
 }
コード例 #29
0
ファイル: DeviceController.cs プロジェクト: codingsf/loosoft
        public ActionResult LoadDevice(int plantid, int unitId, int typeId, int modelId)
        {
            Plant             plant = PlantService.GetInstance().GetPlantInfoById(plantid);
            IList <PlantUnit> units = new List <PlantUnit>(); //电站单元列表

            if (unitId.Equals(-1))                            //如果为-1代表当前电站的所有单元
            {
                units = plant.allFactUnits;
            }
            else
            {
                foreach (PlantUnit unit in plant.allFactUnits)//如果选择单元 则为当前单元
                {
                    if (unit.id.Equals(unitId))
                    {
                        units.Add(unit);
                        break;
                    }
                }
            }
            IList <Device> devices = new List <Device>();

            foreach (PlantUnit unit in units)
            {
                if (unit.devices != null)
                {
                    foreach (Device device in unit.devices)//循环单元中的所有设备
                    {
                        if (typeId > 0 || modelId > 0)
                        {
                            if (modelId > 0)//如果选择了设备型号
                            {
                                if (device.deviceModel != null && device.deviceModel.code == modelId)
                                {
                                    devices.Add(device);//添加指定的设备型号
                                }
                            }
                            else
                            {
                                if (device.deviceTypeCode == typeId)//如果选择了设备类型
                                {
                                    devices.Add(device);
                                }
                            }
                        }
                        else
                        {
                            devices.Add(device);
                        }
                    }
                }
            }

            Hashtable jsonData = new Hashtable();

            foreach (Device model in devices)
            {
                jsonData.Add(model.id, model.deviceAddress);
            }
            string json = JsonUtil.convertToJson(jsonData, typeof(Hashtable));

            return(Content(json));
        }
コード例 #30
0
ファイル: Mono.cs プロジェクト: waelabed/Blazor
        public static TResult InvokeRegisteredMethod <TResult>(string methodName, params object[] jsonSerializableArgs)
        {
            var jsonResult = InvokeRegisteredMethodCore(methodName, jsonSerializableArgs);

            return(JsonUtil.Deserialize <TResult>(jsonResult));
        }