Esempio n. 1
1
        public override HttpRequest Build(string path)
        {
            var request = base.Build(path);
            request.Method = HttpMethod.POST;
            request.Headers.Accept = "application/json-rpc, application/json";
            request.Headers.ContentType = "application/json-rpc";

            var message = new Dictionary<string, object>();
            message["jsonrpc"] = "2.0";
            message["method"] = Method;
            message["params"] = Parameters;
            message["id"] = CreateNextId();

            request.Body = message.ToJson();

            return request;
        }
Esempio n. 2
0
        public void SendLetter(UpdateLetter updateLetter)
        {
            var letter = updateLetter.CreateLetter();
            letter.ReplyTime = SqlDateTime.MinValue.Value;
            using (var content = new DefaultContext())
            {
                content.Letters.Add(letter);
                content.SaveChanges();
            }
            var dic = new Dictionary<string, string>();
            dic.Add("ActionName", "Reply");
            dic.Add("letter", letter.ToJson());

            var resString = HttpWebResponseUtility.CreatePostHttpResponse("http://second.eagle.com/api/Message", dic.ToJson(), 30000);
            if (string.IsNullOrEmpty(resString) || resString == "0")
            {
                Flag = false;
                Message = "消息无响应";
                return;
            }
            var result = resString.ToDeserialize<Cells>();
            if (!result.Flag)
            {
                Flag = false;
                Message = result.Message;
                return;
            }
            Flag = true;
        }
Esempio n. 3
0
        public static void Test_Serialize_Dictionary_02(DictionaryRepresentation dictionaryRepresentation)
        {
            // json Dictionary
            // DictionaryRepresentation.Dynamic or DictionaryRepresentation.Document
            // { "toto1" : "tata1", "toto2" : "tata2" }
            // DictionaryRepresentation.ArrayOfArrays
            // [["toto1", "tata1"], ["toto2", "tata2"]]
            // DictionaryRepresentation.ArrayOfDocuments
            // [{ "k" : "toto1", "v" : "tata1" }, { "k" : "toto2", "v" : "tata2" }]
            Trace.WriteLine();
            Trace.WriteLine("Test_Serialize_Dictionary_02");
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("toto1", "tata1");
            dictionary.Add("toto2", "tata2");
            //DictionaryRepresentation dictionaryRepresentation = DictionaryRepresentation.ArrayOfDocuments;
            Trace.WriteLine("DictionaryRepresentation : {0}", dictionaryRepresentation);
            Trace.WriteLine("Dictionary json :");
            string json = dictionary.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json);

            Trace.WriteLine("Deserialize json :");
            Dictionary<string, string> dictionary2 = BsonSerializer.Deserialize<Dictionary<string, string>>(json);
            string json2 = dictionary2.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json2);
            Trace.WriteLine("comparison of Dictionary json and Deserialize json : {0}", json == json2 ? "identical" : "different");
        }
 public void BroadcastMessage(string message)
 {
     var args = new Dictionary<string, object>() { { "clientId", ClientId }, { "message", message } };
     var subscriber = _multiplexer.GetSubscriber();
     subscriber.Publish("RedisNotifier.serverMessage", args.ToJson());
     log(Logging.LoggingLevel.Detailed, "Broadcasting Message: " + message);
 }
 public void BroadcastExpireCache(string cacheName, string key, string itemKey)
 {
     var args = new Dictionary<string, object>() { { "clientId", ClientId }, { "cacheName", cacheName }, { "key", key }, { "itemKey", itemKey } };
     var subscriber = _multiplexer.GetSubscriber();
     subscriber.Publish("RedisNotifier.expireItemCache", args.ToJson());
     log(Logging.LoggingLevel.Detailed, "Broadcasting ExpireCache: {0}:{1}", key, itemKey);
 }
        protected virtual void SendCancelResult()
        {
            var dictionary = new Dictionary<string, object>();
            dictionary[Constants.CancelledKey] = true;
            if (!string.IsNullOrEmpty(this.CallbackID))
            {
                dictionary[Constants.CallbackIdKey] = this.CallbackID;
            }

            this.Callback(new ResultContainer(dictionary.ToJson()));
        }
Esempio n. 7
0
 public static void Test_Serialize_Dictionary_01()
 {
     // json Dictionary
     // { "toto1" : "tata1", "toto2" : "tata2" }
     Trace.WriteLine();
     Trace.WriteLine("Test_Serialize_Dictionary_01");
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary.Add("toto1", "tata1");
     dictionary.Add("toto2", "tata2");
     Trace.WriteLine("Dictionary json :");
     string json = dictionary.ToJson();
     Trace.WriteLine(json);
 }
Esempio n. 8
0
        public static void RegisterControlPresenter(this HtmlHelper helper, Models.IClientControl model, string clientType, string instanceName, Dictionary<string, object> properties = null)
        {
            properties = properties == null ? new Dictionary<string, object>() : properties;
            RegisterCoreScripts(helper);

            if (!string.IsNullOrEmpty(model.ScriptPath))
                HtmlExtensions.RegisterScript(helper, model.ScriptPath + clientType + ".js", true);

            properties["id"] = model.ClientId;  //todo: not necessary now... same as ns?
            properties["ns"] = model.ClientId;

            //Properties["user"] = Services.Account.GetClientUser();
            //var ser = new System.Web.Script.Serialization.JavaScriptSerializer();   //no binders for date conversions...
            HtmlExtensions.RegisterDocumentReadyScript(helper, model.ClientId + "Presenter", string.Format("videre.widgets.register('{0}', {1}, {2});", model.ClientId, clientType, properties.ToJson(ignoreType: "client")));
        }
Esempio n. 9
0
        public void ToJsonTest()
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("Name", "11");
            data.Add("Teacher", new { Name = "theacher", Couse = "English" });
            data.Add("Family", new Dictionary<string, object>()
                                    {
                                        {"facther",new {Name="john",Birthday=new DateTime(1979,1,1)}},
                                        {"mother",new {Name="Hellen",Birthday=new DateTime(1979,1,1)}},
                                    });
            var expect = "{\"Name\":\"11\",\"Teacher\":{\"Name\":\"theacher\",\"Couse\":\"English\"},\"Family\":{\"facther\":{\"Name\":\"john\",\"Birthday\":\"\\/Date(283968000000)\\/\"},\"mother\":{\"Name\":\"Hellen\",\"Birthday\":\"\\/Date(283968000000)\\/\"}}}";

            var target = data.ToJson(false);
            Assert.AreEqual(expect, target);
        }
        internal static JsonObject Generate(IEnumerable<FieldInput> fields)
        {
            var jsonObject = new JsonObject();
            var list = new Dictionary<string, object>();

            if (fields != null)
            {
                foreach (var f in fields.Where(f => f.Value != null))
                {
                    list.Add(f.Id, ComplexIssueInputFieldValueJsonGenerator.GenerateFieldValueForJson(f.Value));
                }
            }

            jsonObject.Add("fields", list.ToJson());
            return jsonObject;
        }
Esempio n. 11
0
        public XDocument Call(string url, HttpMethod method, Dictionary<string, object> data, bool requiresAuthentication)
        {
            if (requiresAuthentication && (string.IsNullOrEmpty(this.publicKey) || string.IsNullOrEmpty(this.privateKey)))
            {
                throw new MyGengoException("This API requires authentication. Both a public and private key must be specified.");
            }

            var parameters = new Dictionary<string, string>();
                        parameters.Add("api_key", this.publicKey);

                        if (requiresAuthentication)
                        {
                            parameters.Add("ts", DateTime.UtcNow.SecondsSinceEpoch().ToString());
                            parameters.Add("api_sig", Sign(parameters["ts"]));
                        }

                        if (data != null)
                        {
                            parameters.Add("data", data.ToJson());
                        }

            string queryString = MakeQueryString(parameters);
            string xml = SendRequest(method, url, queryString);

            XDocument doc;
            try
            {
                doc = XDocument.Parse(xml);
            }
            catch (Exception x)
            {
                var mgx = new MyGengoException("The response returned by myGengo is not valid XML", x);
                mgx.Data.Add("url", url);
                mgx.Data.Add("response", xml);
                throw mgx;
            }

            if (doc.Root.Element("opstat").Value == "error")
            {
                XElement error = doc.Root.Element("err");
                throw new MyGengoException(string.Format("{0} (error code {1})", error.Element("msg").Value, error.Element("code").Value));
            }

            return doc;
        }
Esempio n. 12
0
        internal void IncrementVotableVersion()
        {

            foreach (var subscriber in subscribedUsers)
            {
                var votablePropsDict = new Dictionary<string, dynamic>() { 
                    { "Id", Id }, 
                    { "PositiveVotesCount", PositiveVotesCount }, 
                    { "NegativeVotesCount", NegativeVotesCount }
                };
                var opDict = new Dictionary<string, object>() { { "operation", 'u' }, { "entity", votablePropsDict } };

                var socket = subscriber.Value.connection;
                var serialized = opDict.ToJson();
                socket.Send(serialized);

            }
        }
Esempio n. 13
0
 public void Work(string sqlText)
 {
     var restPace = new RestPace();
     restPace.ID = Guid.NewGuid();
     restPace.SqlCommand = sqlText;
     restPace.SendTime = DateTime.Now;
     restPace.ReceiveTime = SqlDateTime.MinValue.Value;
     restPace.RestaurantId = RestaurantId;
     restPace.ReceiptText = new List<List<string>>().ToJson();
     using (var restContext = new DefaultContext())
     {
         restContext.RestPaces.Add(restPace);
         restContext.SaveChanges();
     }
     var dic = new Dictionary<string, string>();
     dic.Add("messageID", restPace.ID.ToString());
     dic.Add("text", sqlText);
     PushCommandToRest(dic.ToJson());
 }
Esempio n. 14
0
 /// <summary>
 /// Executes the scripted event.
 /// </summary>
 /// <param name="eventType">Type of the event.</param>
 /// <param name="taskId">The task id.</param>
 /// <param name="name">The name.</param>
 /// <param name="sourceCode">The source code.</param>
 /// <param name="language">The language.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="scriptArguments">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 /// <param name="preview">if set to <c>true</c> [preview].</param>
 /// <returns></returns>
 public static Dictionary<string, object> ExecuteScriptedEvent(string eventType, Guid taskId, string name, string sourceCode, string language, object sender, EventArgs scriptArguments, bool preview)
 {
     ("EVENT " + eventType + " > delegate " + name + "(" + taskId.ToString() + ")").Debug(10);
     Dictionary<string, object> j = new Dictionary<string, object>();
     string consoleOutput = "";
     string errorNumber = "";
     string errorJSON = "";
     DateTime startDate = DateTime.Now;
     List<object> errors = new List<object>();
     object[] args = { sender, scriptArguments };
     object obj = Admin.ExecuteScript(sourceCode, language, "script", "main", ref args, ref errors);
     if(errors.Count == 0) {
         if(consoleOutput.Length > 0) {
             if(obj.GetType() == typeof(string)) {
                 consoleOutput = (string)obj;
             }
             Dictionary<string, object> err = new Dictionary<string, object>();
             err.Add("errorNumber", 0);
             err.Add("errorText", "EVENT " + eventType + " > delegate " + name + " completed without error.");
             (" --------------------------------------------------").Debug(6);
             (" |		MESSAGE FROM " + name).Debug(6);
             (" --------------------------------------------------").Debug(6);
             (consoleOutput).Debug(6);/*MESSAGE!*/
             (" --------------------------------------------------").Debug(6);
             err.Add("line", 0);
             errorNumber = "0";
             errorJSON = err.ToJson();
             err["errorText"].Debug(6);
         }
     } else {
         errorJSON = errors.ToJson();
         errorNumber = (string)((Dictionary<string, object>)(errors[0]))["errorNumber"].ToString();
         errorJSON.Debug(6);
     }
     if(!preview) {
         updateEventTaskStatus(taskId, startDate, false, DateTime.Now, errorNumber, errorJSON);
     }
     j.Add("error", errorNumber);
     j.Add("errors", errors);
     j.Add("console", consoleOutput);
     return j;
 }
Esempio n. 15
0
        private async Task <string> BuildRevocationRegistryDetlasAsync(Pool pool,
                                                                       IEnumerable <ProofIdentifier> proofIdentifiers)
        {
            var result = new Dictionary <string, Dictionary <string, JObject> >();

            foreach (var identifier in proofIdentifiers)
            {
                var delta = await LedgerService.LookupRevocationRegistryDeltaAsync(pool,
                                                                                   identifier.RevocationRegistryId,
                                                                                   -1,
                                                                                   long.Parse(identifier.Timestamp));

                result.Add(identifier.RevocationRegistryId,
                           new Dictionary <string, JObject>
                {
                    { identifier.Timestamp, JObject.Parse(delta.ObjectJson) }
                });
            }

            return(result.ToJson());
        }
Esempio n. 16
0
        /// <summary>
        /// 重新生成缓存和token
        /// </summary>
        /// <param name="userCache"></param>
        private static void CreateTokenCache(UserCacheBo userCache)
        {
            // 将某些信息存到token的payload中,此处是放的内存缓存信息  可替换成其它的
            // aes加密的原因是避免直接被base64反编码看见
            //var encryptMsg = userCache.ToJson().EncryptAES();
            userCache.SessionId = Guid.NewGuid().ToString("N");
            var dic = new Dictionary <string, string>()
            {
                { "uid", userCache.UserId.ToString() },
                { "tenantId", userCache.TenantId.ToString() },
                { "sessionId", userCache.SessionId } //一个账号仅允许在一个地方登录
            };
            var token = TokenManager.GenerateToken(dic.ToJson(), 3 * 24);

            LionWeb.HttpContext.Response.Headers["token"] = token;
            userCache.UserToken = token;
            LionWeb.HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "token"; //多个以逗号分隔 eg:token,sid

            LionUser.CurrentUser = userCache;
            //LionUserCache.CreateUserCache(userCache);
        }
Esempio n. 17
0
        public void Register(IEventSubscription sub, Dictionary <string, string> connectArgs = null)
        {
            if (sub == null)
            {
                throw new ArgumentNullException("subscription");
            }

            var info = sub.GetInfo();

            using (var redis = clientsManager.GetClient())
            {
                StoreSubscriptionInfo(redis, info);
            }

            if (connectArgs != null)
            {
                sub.Publish("cmd.onConnect", connectArgs.ToJson());
            }

            local.Register(sub);
        }
        public HttpResponseMessage GetTopicList(int ForumId)
        {
            var portalSettings = PortalSettings;
            var userInfo       = portalSettings.UserInfo;

            DataSet ds = DataProvider.Instance().UI_TopicsView(portalSettings.PortalId, ActiveModule.ModuleID, ForumId, userInfo.UserID, 0, 20, userInfo.IsSuperUser, SortColumns.ReplyCreated);

            if (ds.Tables.Count > 0)
            {
                DataTable dtTopics = ds.Tables[3];

                Dictionary <string, string> rows = new Dictionary <string, string>();;
                foreach (DataRow dr in dtTopics.Rows)
                {
                    rows.Add(dr["TopicId"].ToString(), dr["Subject"].ToString());
                }

                return(Request.CreateResponse(HttpStatusCode.OK, rows.ToJson()));
            }
            return(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        public ActionResult ExportKPICompareResult(int cdrId1, int cdrId2, string startTime, string endTime, string cdr1Name, string cdr2Name)
        {
            var data = new Dictionary <string, List <KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL> >();

            try
            {
                _unitValueLockService = new UnitKPIValueLockService(startTime, endTime);
                var temp = _unitValueLockService.GetCompareResult(cdrId1, cdrId2);// _itemCompareService.GetCompareResult(cdrId1, cdrId2, startTime, endTime, itemList);
                if (temp.Count == 0)
                {
                    return(Content(new KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL().ToJson()));
                }
                var title = new KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL
                {
                    指标ID = "指标ID",
                    指标名称 = "指标名称",
                    左分子  = "左分子",
                    左分母  = "左分母",
                    左比率  = "左比率",
                    右分子  = "右分子",
                    右分母  = "右分母",
                    右比率  = "右比率",
                    差异   = "差异"
                };
                var result = new List <KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL>();
                temp.ForEach(r =>
                             result.Add(new KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL(r))
                             );
                data.Add("title", new List <KPI_COMPARE_FOR_DOWNLOAD_VIEWMODEL>()
                {
                    title
                });
                data.Add("data", result);
            }
            catch (Exception ex)
            {
                data.Add("data", null);
            }
            return(Content(data.ToJson()));
        }
Esempio n. 20
0
        /// <summary>
        /// 通过下游卖家mobile获取信息
        /// </summary>
        /// <param name="mobile">卖家mobile</param>
        /// <returns>大于0成功,否则失败</returns>
        /// <remarks>
        /// <list type="bullet">
        /// <item></item>
        /// </list>
        /// </remarks>
        public IResultResponse CheckDownConnector(string mobile, int upConnectorId)
        {
            //检查信息是否存在
            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add("Mobile", mobile);
            List <ConnectorEntity> entConnectors = DbAccess.GetEntitys <ConnectorEntity>(ConnectorBusiness._TableName, dic, 0);

            if (entConnectors == null || entConnectors.Count == 0)
            {
                return(ResultResponse.ExceptionResult("您尚未成为连接器合作商"));
            }
            IResultResponse resultResponse = null;

            foreach (ConnectorEntity entConnector in entConnectors)
            {
                Dictionary <string, object> dic2 = new Dictionary <string, object>();
                dic2.Add("DownConnectorId", entConnector.Id);
                RelationEntity relate = DbAccess.GetEntity <RelationEntity>(TableName, dic2);
                if (relate != null && relate.Id > 0)
                {
                    if (relate.UpConnectorId == upConnectorId)
                    {
                        resultResponse = ResultResponse.ExceptionResult("您已成为该合作商的下游合作商");
                    }
                    else
                    {
                        resultResponse = ResultResponse.ExceptionResult("您已拥有上游合作商,不能再添加");
                    }
                    continue;
                }
                GroupEntity group = (GroupEntity) new GroupBusiness().GetEntity("Id=" + entConnector.GroupId);
                Dictionary <string, object> result = new Dictionary <string, object>();
                result.Add("Id", entConnector.Id);
                result.Add("Domain", group.Domain);
                resultResponse = ResultResponse.GetSuccessResult(result.ToJson());
                break;
            }
            return(resultResponse);
        }
Esempio n. 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="idCard"></param>
        /// <param name="realName"></param>
        /// <param name="mobilePhone"></param>
        /// <returns></returns>
        public IDictionary <string, string> SendQueryRequest(string idCard, string realName, string mobilePhone)
        {
            var postData = new Dictionary <string, object>();

            postData["header"] = new Dictionary <string, object>()
            {
                { "orgno", this.orgno },
                { "usrid", this.usrid },
                { "datori", this.datori },
                { "queryreason", this.datori }
            };
            postData["body"] = new Dictionary <string, object>()
            {
                { "trninfo",
                  new Dictionary <string, object>()
                  {
                      { "prsnnam", realName },
                      { "idcard", idCard },
                      { "mobile", mobilePhone }
                  } }
            };

            var postBody = postData.ToJson();

            var apiUrl          = string.Format(ApiUri, this.chnlcod, this.prdcod);
            var responseContent = this.SendApiRequest(apiUrl, postBody);


            LogManager.GetLogger().Info(" Sinoway Query : {0}", responseContent);

            if (!string.IsNullOrEmpty(responseContent))
            {
                var responseData = responseContent.ConvertEntity <Dictionary <string, object> >();
                if (responseData.ContainsKey("header"))
                {
                    return(responseData["header"].ToString().ConvertEntity <Dictionary <string, string> >());
                }
            }
            return(null);
        }
Esempio n. 22
0
        /// <summary>
        /// Returns the environment data as json.
        /// </summary>
        /// <returns>a JSON formatted string</returns>
        public static string GetEnvDataAsJson(System.Web.HttpRequest request, string rockUrl)
        {
            var envData = new Dictionary <string, string>();

            envData.Add("AppRoot", rockUrl);
            envData.Add("Architecture", (IntPtr.Size == 4) ? "32bit" : "64bit");
            envData.Add("AspNetVersion", GetDotNetVersion());
            envData.Add("IisVersion", request.ServerVariables["SERVER_SOFTWARE"]);
            envData.Add("ServerOs", Environment.OSVersion.ToString());

            try
            { envData.Add("SqlVersion", Rock.Data.DbService.ExecuteScaler("SELECT SERVERPROPERTY('productversion')").ToString()); }
            catch { }

            try
            {
                using (var rockContext = new RockContext())
                {
                    var entityType = EntityTypeCache.Get("Rock.Security.BackgroundCheck.ProtectMyMinistry", false, rockContext);
                    if (entityType != null)
                    {
                        var pmmUserName = new AttributeValueService(rockContext)
                                          .Queryable().AsNoTracking()
                                          .Where(v =>
                                                 v.Attribute.EntityTypeId.HasValue &&
                                                 v.Attribute.EntityTypeId.Value == entityType.Id &&
                                                 v.Attribute.Key == "UserName")
                                          .Select(v => v.Value)
                                          .FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(pmmUserName))
                        {
                            envData.Add("PMMUserName", pmmUserName);
                        }
                    }
                }
            }
            catch { }

            return(envData.ToJson());
        }
Esempio n. 23
0
        /// <summary>
        /// Post方法
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paras"></param>
        /// <param name="urlPrex"></param>
        /// <returns></returns>
        public async Task<string> Post(string url, Dictionary<string, string> param, string urlPrex = "https://")
        {
            try
            {
                if (!url.StartsWith("http") && !url.StartsWith("https")) url = urlPrex + url;

                var ret = "";
                if (param.Count == 0) return "";
                //遍历参数集合

                var buffer = new StringBuilder();
                var i = 0;
                foreach (var key in param.Keys)
                {
                    buffer.AppendFormat(i > 0 ? "&{0}={1}" : "{0}={1}", key, param[key]);
                    i++;
                }
                var data = Encoding.UTF8.GetBytes(buffer.ToString());

                Log.Info($"转发Post请求url: {url}, 参数:{buffer}");

                var result = await HttpRequest(url, HttpMethodEnum.POST, "application/x-www-form-urlencoded", data);
       
                if (result != null) ret = Encoding.UTF8.GetString(result);

                Log.Info($"Post转发返回结果: {ret}, 请求url: {url}, 参数:{buffer}");
                return ret;
            }
            catch (Exception ex)
            {
                var mess = new StringBuilder();
                mess.AppendLine("转发Post方法调用时发生错误,数据内容如下:");
                mess.AppendLine($"urlPrex: {urlPrex} url: {url} param: {param.ToJson()}");
                mess.AppendLine("错误内容如下:");
                mess.AppendLine("");
                mess.AppendLine(ex.Message);
                Log.Error(mess);
                return "";
            }
        }
Esempio n. 24
0
        private Dictionary <string, string> AuthAuthenticate(HttpRequestBuilder requestBuilder, FloodSettings settings, bool force = false)
        {
            var cachedCookies = _authCookieCache.Find(BuildCachedCookieKey(settings));

            if (cachedCookies == null || force)
            {
                var authenticateRequest = requestBuilder.Resource("/auth/authenticate").Post().Build();

                var body = new Dictionary <string, object>
                {
                    { "username", settings.Username },
                    { "password", settings.Password }
                };
                authenticateRequest.SetContent(body.ToJson());

                var response = HandleRequest(authenticateRequest, settings);
                cachedCookies = response.GetCookies();
                _authCookieCache.Set(BuildCachedCookieKey(settings), cachedCookies);
            }

            return(cachedCookies);
        }
Esempio n. 25
0
        private static StringContent CreateSaveContent(CompositeData data)
        {
            var content = new Dictionary <string, object>(
                ApplicationBehaviorDispatcher.OnBeforeUpload(data.Composite, data.Application));

            foreach (var components in data.Components)
            {
                var closuredComponents = components;

                // All component data maps served by the
                // same application are nested inside an
                // array named by the application.
                content[components.Key.ApplicationName] = components
                                                          .Select(c => ApplicationBehaviorDispatcher.OnBeforeUpload(c, closuredComponents.Key))
                                                          .ToList();
            }

            return(new StringContent(
                       content.ToJson(),
                       Encoding.UTF8,
                       HttpCall.JsonMediaType.MediaType));
        }
Esempio n. 26
0
        /// <summary>
        /// 获取语言包(数据库直接读取)
        /// </summary>
        /// <returns></returns>
        private Result TranslateData()
        {
            IEnumerable <string> contents = JsonConvert.DeserializeObject <string[]>(this.context.QF("Content")).Distinct();
            string token = this.GetToken();

            Language[] languages = this.context.QF("Language").Split(',').Select(t => t.ToEnum <Language>()).ToArray();
            //# Key存入Token
            foreach (string keyword in contents)
            {
                TranslateAgent.Instance().AddKeyword(keyword, token);
            }

            //# 获取目前数据库内的内容
            Dictionary <string, Dictionary <Language, string> > translates = new Dictionary <string, Dictionary <Language, string> >();

            foreach (string keyword in contents)
            {
                translates.Add(keyword, TranslateAgent.Instance().GetTranslate(keyword, languages));
            }

            return(new Result(ContentType.JSON, translates.ToJson()));
        }
Esempio n. 27
0
        private static JsonValue _EncodeEnumKeyDictionary <TKey, TValue>(Dictionary <TKey, TValue> dict, JsonSerializer serializer)
        {
            var encodeDefaults = serializer.Options.EncodeDefaultValues;

            serializer.Options.EncodeDefaultValues = true;
            var enumFormat = serializer.Options.EnumSerializationFormat;

            serializer.Options.EnumSerializationFormat = EnumSerializationFormat.AsName;

            var output = new Dictionary <string, JsonValue>();

            foreach (var kvp in dict)
            {
                var key = serializer.Options.SerializationNameTransform(serializer.Serialize(kvp.Key).String);
                output.Add(key, serializer.Serialize(kvp.Value));
            }

            serializer.Options.EnumSerializationFormat = enumFormat;
            serializer.Options.EncodeDefaultValues     = encodeDefaults;

            return(output.ToJson());
        }
Esempio n. 28
0
        public bool pushAllDevice(string title, string content, int type, int environment, Dictionary <string, object> custom, out string returnStr)
        {
            content = content.Replace("\r", "").Replace("\n", "");
            switch (type)
            {
            case (int)DeviceType.Android:
                Message android = new Message();
                //android.type = Message.TYPE_MESSAGE;
                android.title   = title;
                android.content = content;
                //if (message.custom_content == null)
                //{
                //    message.custom_content = new Dictionary<string, object>();
                //}
                android.custom_content = custom.ToJson();
                returnStr = pushAllDevice(android);
                break;

            //case (int)DeviceType.IOS:
            //    MessageIOS ios = new MessageIOS();
            //    //ios.type = Message.TYPE_NOTIFICATION;
            //    ios.alertStr = content.Length > 20 ? content.Substring(0, 20) : content;
            //    ios.custom = custom;
            //    if (!string.IsNullOrEmpty(account))
            //    {
            //        returnStr = pushSingleAccount(account, ios, environment);
            //    }
            //    else
            //    {
            //        returnStr = pushSingleDevice(deviceToken, ios, environment);
            //    }
            //    break;
            default:

                returnStr = string.Format("找不到指定类型的推送方法,设备类型:{0}", type);
                break;
            }
            return(true);
        }
        public void Does_serialize_StringDictionaryWrapper_line_breaks()
        {
            var prop = new Dictionary <string, string> {
                ["text"] = "line\nbreak"
            };

            Assert.That(prop.ToJson(), Is.EqualTo("{\"text\":\"line\\nbreak\"}"));

            var dto = new StringDictionaryWrapper {
                Prop = prop
            };

            Assert.That(dto.ToJson(), Is.EqualTo("{\"Prop\":{\"text\":\"line\\nbreak\"}}"));

            var nested = new NestedStringDictionaryWrapper {
                Prop = new Dictionary <string, Dictionary <string, string> > {
                    ["a"] = prop
                }
            };

            Assert.That(nested.ToJson(), Is.EqualTo("{\"Prop\":{\"a\":{\"text\":\"line\\nbreak\"}}}"));
        }
Esempio n. 30
0
        async Task FinishTestRun(int testRunId)
        {
            var requestMessage = new Dictionary <string, object>
            {
                { "completedDate", DateTime.UtcNow },
                { "state", "Completed" }
            };

            var bodyString = requestMessage.ToJson();
            var url        = $"{baseUri}/{testRunId}?api-version=1.0";

            try
            {
                var bodyBytes = Encoding.UTF8.GetBytes(bodyString);

                var request = new HttpRequestMessage(PatchHttpMethod, url)
                {
                    Content = new ByteArrayContent(bodyBytes)
                };
                request.Content.Headers.ContentType = JsonMediaType;
                request.Headers.Accept.Add(JsonMediaType);

                using (var tcs = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
                {
                    var response = await client.SendAsync(request, tcs.Token).ConfigureAwait(false);

                    if (!response.IsSuccessStatusCode)
                    {
                        logger.LogWarning($"When sending 'PATCH {url}', received status code '{response.StatusCode}'; request body: {bodyString}");
                        previousErrors = true;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"When sending 'PATCH {url}' with body '{bodyString}', exception was thrown: {ex.Message}");
                throw;
            }
        }
Esempio n. 31
0
        //END-POINT: desde CrudMantenimiento.Ts
        public JsonResult epExportar(string parametrosJson = null)
        {
            var r = new Resultado();
            Dictionary <string, object> parametros = parametrosJson.ToDiccionarioDeParametros();

            parametros[nameof(ElementoDto)] = typeof(TElemento).Name;
            parametros[nameof(Registro)]    = typeof(TRegistro).Name;

            try
            {
                ApiController.CumplimentarDatosDeUsuarioDeConexion(Contexto, Mapeador, HttpContext);

                if (parametros.ContainsKey("sometido") && bool.Parse(parametros["sometido"].ToString()))
                {
                    GestorDocumental.SometerExportacion(Contexto, parametros.ToJson());
                    r.Mensaje = $"Trabajo sometido correctamente";
                }
                else
                {
                    var opcionesDeMapeo = new Dictionary <string, object>();
                    opcionesDeMapeo.Add(ltrParametrosDto.DescargarGestionDocumental, false);
                    var cantidad = !parametros.ContainsKey(ltrFiltros.cantidad) ? -1 : parametros[ltrFiltros.cantidad].ToString().Entero();
                    var posicion = !parametros.ContainsKey(ltrFiltros.posicion) ? 0 : parametros[ltrFiltros.posicion].ToString().Entero();
                    List <ClausulaDeFiltrado>   filtros = !parametros.ContainsKey(ltrFiltros.filtro) || parametros[ltrFiltros.filtro].ToString().IsNullOrEmpty() ? new List <ClausulaDeFiltrado>() : JsonConvert.DeserializeObject <List <ClausulaDeFiltrado> >(parametros["filtro"].ToString());
                    List <ClausulaDeOrdenacion> orden   = !parametros.ContainsKey(ltrFiltros.orden) || parametros[ltrFiltros.orden].ToString().IsNullOrEmpty() ? new List <ClausulaDeOrdenacion>() : JsonConvert.DeserializeObject <List <ClausulaDeOrdenacion> >(parametros["orden"].ToString());

                    var elementos = GestorDeElementos.LeerElementos(posicion, cantidad, filtros, orden, opcionesDeMapeo);
                    r.Datos   = GestorDocumental.DescargarExcel(Contexto, elementos.ToList());
                    r.Mensaje = $"Exportado";
                }
                r.ModoDeAcceso = enumModoDeAccesoDeDatos.Consultor.Render();
                r.Estado       = enumEstadoPeticion.Ok;
            }
            catch (Exception e)
            {
                ApiController.PrepararError(e, r, "Error al exportar.");
            }
            return(new JsonResult(r));
        }
 private static void SaveTestDataMap()
 {
     lock (TestDataJsonFile)
     {
         using (var streamWriter =
                    new StreamWriter(new FileStream(TestDataJsonFile, FileMode.OpenOrCreate, FileAccess.Write)))
         {
             try
             {
                 streamWriter.WriteLine(TestDataMap.ToJson());
             }
             catch (Exception e)
             {
                 Console.WriteLine(e);
             }
             finally
             {
                 streamWriter?.Close();
             }
         }
     }
 }
Esempio n. 33
0
        /// <summary>
        /// Returns the environment data as json.
        /// </summary>
        /// <returns>a JSON formatted string</returns>
        public static string GetEnvDataAsJson( System.Web.HttpRequest request, string rockUrl )
        {
            var envData = new Dictionary<string, string>();
            envData.Add( "AppRoot", rockUrl );
            envData.Add( "Architecture", ( IntPtr.Size == 4 ) ? "32bit" : "64bit" );
            envData.Add( "AspNetVersion", Environment.Version.ToString() );
            envData.Add( "IisVersion", request.ServerVariables["SERVER_SOFTWARE"] );
            envData.Add( "ServerOs", Environment.OSVersion.ToString() );

            try { envData.Add( "SqlVersion", Rock.Data.DbService.ExecuteScaler( "SELECT SERVERPROPERTY('productversion')" ).ToString() ); }
            catch {}

            try
            {
                using ( var rockContext = new RockContext() )
                {
                    var entityType = EntityTypeCache.Read( "Rock.Security.BackgroundCheck.ProtectMyMinistry", false, rockContext );
                    if ( entityType != null )
                    {
                        var pmmUserName = new AttributeValueService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( v =>
                                v.Attribute.EntityTypeId.HasValue &&
                                v.Attribute.EntityTypeId.Value == entityType.Id &&
                                v.Attribute.Key == "UserName" )
                            .Select( v => v.Value )
                            .FirstOrDefault();
                        if ( !string.IsNullOrWhiteSpace( pmmUserName ) )
                        {
                            envData.Add( "PMMUserName", pmmUserName );
                        }
                    }
                }
            }
            catch { }

            return envData.ToJson();
        }
Esempio n. 34
0
        public void Register(IEventSubscription subscription, Dictionary <string, string> connectArgs = null)
        {
            try
            {
                lock (subscription)
                {
                    if (connectArgs != null)
                    {
                        subscription.Publish("cmd.onConnect", connectArgs.ToJson());
                    }

                    subscription.OnUnsubscribe = HandleUnsubscription;
                    foreach (var channel in subscription.Channels ?? EventSubscription.UnknownChannel)
                    {
                        RegisterSubscription(subscription, channel, ChannelSubcriptions);
                    }
                    RegisterSubscription(subscription, subscription.SubscriptionId, Subcriptions);
                    RegisterSubscription(subscription, subscription.UserId, UserIdSubcriptions);
                    RegisterSubscription(subscription, subscription.UserName, UserNameSubcriptions);
                    RegisterSubscription(subscription, subscription.SessionId, SessionSubcriptions);

                    if (OnSubscribe != null)
                    {
                        OnSubscribe(subscription);
                    }
                }

                if (NotifyChannelOfSubscriptions && subscription.Channels != null && NotifyJoin != null)
                {
                    NotifyJoin(subscription);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Register: " + ex.Message, ex);
                throw;
            }
        }
Esempio n. 35
0
        /// <summary>
        /// 保存配置
        /// </summary>
        public void Save()
        {
            var dict = new Dictionary <string, Config_cache>();

            foreach (var item in Dict)
            {
                var o   = item.Value;
                var obj = new Config_cache()
                {
                    State = o.State, OrderBy = o.OrderBy
                };
                dict.Add(item.Key, obj);
            }
            var dir = "./cache/".ToFullName();

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            var file = dir + App + "_plug_cache.json";

            File.WriteAllText(file.ToFullName(), dict.ToJson(true));
        }
Esempio n. 36
0
        /// <summary>
        /// Formats the credential values into a JSON usable with the <see cref="AnonCreds"/> API
        /// </summary>
        /// <returns>The credential values.</returns>
        /// <param name="credentialAttributes">The credential attributes.</param>
        public static string FormatCredentialValues(IEnumerable <CredentialPreviewAttribute> credentialAttributes)
        {
            if (credentialAttributes == null)
            {
                return(null);
            }

            var result = new Dictionary <string, Dictionary <string, string> >();

            foreach (var item in credentialAttributes)
            {
                switch (item.MimeType)
                {
                case CredentialMimeTypes.TextMimeType:
                    result.Add(item.Name, FormatStringCredentialAttribute(item));
                    break;

                default:
                    throw new AgentFrameworkException(ErrorCode.InvalidParameterFormat, $"{item.Name} mime type of {item.MimeType} not supported");
                }
            }
            return(result.ToJson());
        }
Esempio n. 37
0
        public static string CreateDuplicateRequest(ResourceId resourceId, Dictionary <string, object> properties, Dictionary <string, object> otherProperties, Enum param, Enums.ValidDuplicated dupType)
        {
            var strParam = param.GetEnumStringValue();

            DuplicateParam(strParam, properties, otherProperties, dupType);
            var createInfos = new Dictionary <string, object>
            {
                [Parameters.Resource.GetEnumStringValue()]   = resourceId.ToString().ToLower(),
                [Parameters.Properties.GetEnumStringValue()] = properties
            };

            AliasMapperValue[Alias.Max](createInfos);
            DuplicateParam(strParam, createInfos, otherProperties, dupType);
            var request = new Dictionary <string, object>
            {
                [Parameters.Create.GetEnumStringValue()] = new Dictionary <string, object>(createInfos)
            };

            AliasMapperValue[Alias.Missing](createInfos);
            DuplicateParam(strParam, request, createInfos, dupType);

            return(ReplaceDuplicate(request.ToJson(), strParam));
        }
Esempio n. 38
0
        public async Task ShouldDeleteNotifications()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            // Must create a notification.
            var payload = new Dictionary <string, string>
            {
                { "user_id", session.UserId }
            };
            await _client.RpcAsync(session, "clientrpc.send_notification", payload.ToJson());

            // List and delete.
            var result1 = await _client.ListNotificationsAsync(session, 1);

            Assert.NotNull(result1);
            var notification = result1.Notifications.First();
            await _client.DeleteNotificationsAsync(session, new[] { notification.Id });

            var result2 = await _client.ListNotificationsAsync(session, 100);

            Assert.NotNull(result2);
            Assert.That(result2.Notifications, Is.Empty);
        }
Esempio n. 39
0
        public async Task ShouldListNotifications()
        {
            var session = await _client.AuthenticateCustomAsync($"{Guid.NewGuid()}");

            // Must create a notification.
            var payload = new Dictionary <string, string>
            {
                { "user_id", session.UserId }
            };
            await _client.RpcAsync(session, "clientrpc.send_notification", payload.ToJson());

            var result = await _client.ListNotificationsAsync(session, 1);

            Assert.NotNull(result);
            Assert.That(result.Notifications.Count(n => n.SenderId == session.UserId), Is.EqualTo(1));
            var notification = result.Notifications.First();

            Assert.IsTrue(notification.Persistent);
            Assert.NotNull(notification.CreateTime);
            Assert.AreEqual(1, notification.Code);
            Assert.AreEqual("{\"reward_coins\": 1000}", notification.Content);
            Assert.AreEqual("You've unlocked level 100!", notification.Subject);
        }
        private static void fillList()
        {
            Logger.Debug("fillList start");
            _listConfig.Clear();
            var path  = Path.Combine(_path, loadconfig);
            var files = Directory.GetFiles(path);

            foreach (var item in files)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(item))
                    {
                        _listConfig[Path.GetFileName(item).ToLower()] = md5.ComputeHash(stream);
                    }
                }
            }
            var fn = Path.Combine(Path.Combine(_path, checkconfig), "HashFileWithConfig.json");

            File.WriteAllText(fn, _listConfig.ToJson());

            Logger.Trace("fillList start");
        }
        private static void WriteMetaDataFile(Photo photo, string targetFileName, Preferences preferences)
        {
            var metadata            = new Dictionary <string, object>();
            var metadataPreferences = preferences.Metadata;

            if (preferences.NeedLocationMetadata && !metadataPreferences.Contains(PhotoMetadata.Location))
            {
                metadataPreferences.Add(PhotoMetadata.Location);
            }
            foreach (var metadatum in metadataPreferences)
            {
                var metadataValue = photo.GetType().GetProperty(metadatum)?.GetValue(photo, null);
                if (metadataValue != null)
                {
                    metadata.Add(metadatum, metadataValue);
                }
            }

            if (metadata.Count > 0)
            {
                File.WriteAllText(string.Format("{0}.json", targetFileName), metadata.ToJson(), Encoding.UTF8);
            }
        }
        public String make_json_data()
        {
            post_data["customerId"]  = customerID;
            post_data["floorPlanId"] = floorPlanID;

            coordinates["x"] = Double.Parse(selectedX.ToString(), CultureInfo.CreateSpecificCulture("fr-FR"));
            coordinates["y"] = Double.Parse(selectedY.ToString(), CultureInfo.CreateSpecificCulture("fr-FR"));

            foreach (KeyValuePair <String, Int32> item in anchor_table_result)
            {
                post_anchs = new Dictionary <string, object>();
                post_anchs.Add("addr", item.Key);
                post_anchs.Add("rssi", item.Value);
                measurument.Add(post_anchs);
            }


            post_data["measurement"] = measurument;
            post_data["coordinates"] = coordinates;


            return(post_data.ToJson());
        }
Esempio n. 43
0
        public void ValidDuplicateSearchMails(string param, Enums.ValidDuplicated validDuplicated)
        {
            var handler = new DefaultManager();
            var request = new Dictionary <string, object>()
            {
                [InvalidMailOthersTestData.PageNumber] = 1,
                [InvalidMailOthersTestData.PageSize]   = 10,
                [InvalidMailOthersTestData.SortOrder]  = 0,
                [InvalidMailOthersTestData.SortField]  = "date",
            };
            var otherValue = new Dictionary <string, object>()
            {
                [InvalidMailOthersTestData.PageNumber] = 2,
                [InvalidMailOthersTestData.PageSize]   = 11,
                [InvalidMailOthersTestData.SortOrder]  = 1,
                [InvalidMailOthersTestData.SortField]  = "to",
            };

            Helpers.DuplicateParam(param, request, otherValue, validDuplicated);
            var response = handler.Send <object>(MailOther.SearchMailsEndpoint, request.ToJson().ReplaceDuplicate(param), HttpMethod.POST);

            PrAssert.That(response, PrIs.SuccessfulResponse().And.HttpCode(System.Net.HttpStatusCode.OK), "Not able to search mails");
        }
Esempio n. 44
0
        /// <summary>
        ///   n1=value1&n2=value2  转Json
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        static public string ToJsonByForm(this string s)
        {
            Dictionary <string, string> dicdata = new Dictionary <string, string>();

            try
            {
                var data = s.Split('&');
                for (int i = 0; i < data.Length; i++)
                {
                    var           dk = data[i].Split('=');
                    StringBuilder sb = new StringBuilder(dk[1]);
                    for (int j = 2; j <= dk.Length - 1; j++)
                    {
                        sb.Append(dk[j]);
                    }
                    dicdata.Add(dk[0], sb.ToString());
                }
            }
            catch
            {
            }
            return(dicdata.ToJson());
        }
Esempio n. 45
0
 public static void Test_Serialize_04(DictionaryRepresentation dictionaryRepresentation)
 {
     Trace.WriteLine("BsonPBSerializationProvider.RegisterProvider()");
     BsonPBSerializationProvider.RegisterProvider();
     PBDictionarySerializer.RegisterGenericDictionarySerializer();
     try
     {
         //PBDictionarySerializer.DefaultDictionaryRepresentation = dictionaryRepresentation;
         DictionarySerializationOptions options = new DictionarySerializationOptions(dictionaryRepresentation);
         Dictionary <string, ZValue>    infos2  = Create_Dictionary_string_ZValue_01();
         //BsonDocument document = infos2.zToBsonDocument(options);
         //Trace.WriteLine(document.zToJson());
         Trace.WriteLine("dictionaryRepresentation : {0}", dictionaryRepresentation);
         string json = infos2.ToJson(options);
         Trace.WriteLine(json);
     }
     finally
     {
         Trace.WriteLine("BsonPBSerializationProvider.UnregisterProvider()");
         BsonPBSerializationProvider.UnregisterProvider();
         PBDictionarySerializer.UnregisterGenericDictionarySerializer();
     }
 }
Esempio n. 46
0
        internal string Parse(string args, DataType dataType, bool disableSpeech) {
            if (args.Contains("{mute}") || args.Contains("{widget}")) {
                args = args.Replace("{mute}", string.Empty).Replace("{widget}", string.Empty);
                disableSpeech = true;
            }

            if (args.Contains("</lock>")) // lock is extension of judo parser. No need for extra parsing
                if (dataType.Equals(DataType.html))
                    return Judoers.JudoParser(args).Replace("\r", string.Empty).Replace("\n", "<br />");
                else
                    return Judoers.JudoParser(args);

            string[] InstructionSets = args.Split(';');
            var results = new Dictionary<string, KeyValuePair<string, string>>();

            foreach (string Instruction in InstructionSets)
                if (Instruction.Trim() != string.Empty) {
                    var exe = Execute(Instruction.Trim(), disableSpeech).Replace("\r", string.Empty);
                    if (exe.EndsWith("\n"))
                        exe = exe.Substring(0, exe.LastIndexOf("\n"));
                    var key = Instruction.Trim().Replace(" ", "_").Replace("%", string.Empty);
                    try {
                        results.Add(key, new KeyValuePair<string, string>(Instruction.Trim(), exe));
                    }
                    catch {
                        // Duplicate keys are not allowed.
                    }
                }

            switch (dataType) {
                case DataType.html:
                    return results.ToDebugString().Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", "<br />");
                case DataType.json:
                    return results.ToJson();
            }
            return results.ToDebugString();
        }
Esempio n. 47
0
        protected override void Write(LogEventInfo logEvent)
        {
            var dictionary = new Dictionary<string, object>();

            if (logEvent.Exception != null)
            {
                dictionary.Add("ex", logEvent.Exception.ToString());
                dictionary.Add("extyp", logEvent.Exception.GetType().Name);
                dictionary.Add("hash", logEvent.GetHash());

                foreach (var key in logEvent.Exception.Data.Keys)
                {
                    dictionary.Add(key.ToString(), logEvent.Exception.Data[key]);
                }
            }

            dictionary.Add("logger", logEvent.LoggerName);
            dictionary.Add("method", Layout.Render(logEvent));
            dictionary.Add("level", logEvent.Level.Name);
            dictionary.Add("message", logEvent.GetFormattedMessage());
            dictionary.Add("ver", BuildInfo.Version.ToString());

            _logger.Log(dictionary.ToJson());
        }
Esempio n. 48
0
        public void TestEmptyDefferedAppLink()
        {
            IAppLinkResult result = null;

            string mockRef = "mockref";
            string mockTargetUrl = "mocktargeturl";
            var mockExtras = new Dictionary<string, object>()
            {
                { "com.facebook.platform.APPLINK_NATIVE_CLASS", string.Empty },
            };

            this.Mock.ResultExtras = new Dictionary<string, object>()
            {
                { Constants.RefKey, mockRef },
                { Constants.TargetUrlKey, mockTargetUrl },
                { Constants.ExtrasKey, mockExtras },
            };

            FB.GetAppLink((r) => (result = r));
            Assert.IsNotNull(result);
            Assert.AreEqual(mockRef, result.Ref);
            Assert.AreEqual(mockTargetUrl, result.TargetUrl);
            Assert.AreEqual(mockExtras.ToJson(), result.Extras.ToJson());
        }
Esempio n. 49
0
        /// <summary>
        /// Executes a scheduled task.
        /// </summary>
        /// <param name="taskId">The task id.</param>
        /// <param name="name">The name.</param>
        /// <param name="interval">The interval.</param>
        /// <param name="sourceCode">The source code.</param>
        /// <param name="language">The language.</param>
        /// <param name="lastRun">The last run.</param>
        /// <param name="lastErrorId">The last error id.</param>
        /// <param name="lastErrorJSON">The last error JSON.</param>
        /// <returns></returns>
        public Admin.Timer ExecuteScheduledTask( Guid taskId, string name, int interval,
		string sourceCode, string language, DateTime lastRun, string lastErrorId, string lastErrorJSON )
        {
            ( "FUNCTION executeScheduledTask (init and start task event timers) /W ADHOC (!PRIVATE!)" ).Debug( 10 );
            Admin.Timer timer = new Admin.Timer();
            /* last time this ran, minus the interval is the starting interval */
            timer.Interval = interval;
            timer.Name = "Compiled DB Timer Event" + Utilities.Iif( name.Length > 0, ":", "" );
            timer.elapsed += new EventHandler( delegate( object e, EventArgs args ) {
                List<object> errors = new List<object>();
                DateTime startDate = new DateTime();
                startDate = DateTime.Now;
                DateTime endDate = new DateTime();
                endDate = DateTime.MinValue;
                string errorJSON = "";
                string errorNumber = "0";
                string consoleOut = "";
                try { /* and and run someone elses code */
                    ( "EVENT DELEGATE Task " + name + " started." ).Debug( 6 );
                    if( timer.Interval != interval ) {
                        timer.Interval = interval;/* now interval should be set to the actual interval */
                    }
                    using( SqlConnection cn = Site.CreateConnection( true, true ) ) {
                        cn.Open();
                        using( SqlTransaction trns = cn.BeginTransaction( "Scheduled Task" ) ) {
                            using( SqlCommand cmd = new SqlCommand( "update eventHandlers set startTime = @startTime, lock = 1 where taskId = @taskId", cn ) ) {
                                cmd.Parameters.Add( "@taskId", SqlDbType.UniqueIdentifier ).Value = new Guid( taskId.ToString() );
                                cmd.Parameters.Add( "@startTime", SqlDbType.DateTime ).Value = startDate;
                                cmd.ExecuteNonQuery();
                                TimerEventArgs evntArgs = new TimerEventArgs( cn, trns, lastRun, taskId, name, lastErrorId, lastErrorJSON );
                                object[] scriptArguments = { Main.Site, evntArgs };
                                object obj = Admin.ExecuteScript( sourceCode, language, "script", "main", ref scriptArguments, ref errors );
                                if( errors.Count == 0 ) {
                                    if( obj.GetType() == typeof( string ) ) {
                                        consoleOut = ( string )obj;
                                    }
                                    Dictionary<string, object> s = new Dictionary<string, object>();
                                    s.Add( "errorNumber", 0 );
                                    s.Add( "errorDesc", "Timer Event " + name + " completed without error." );
                                    s.Add( "console", consoleOut );
                                    errorNumber = "0";
                                    errorJSON = s.ToJson();
                                    trns.Commit();/* no errors occured in the script so commit the transaction */
                                } else {
                                    errorJSON = errors.ToJson();
                                    errorNumber = ( ( Dictionary<string, object> )( errors[ 0 ] ) )[ "errorNumber" ].ToString();
                                    trns.Rollback();/* one or more errors occured so rollback the transaction */
                                }
                                endDate = DateTime.Now;
                                updateEventTaskStatus( taskId, startDate, false, endDate, errorNumber, errorJSON );
                                ( "EVENT DELEGATE Task " + name + " ended." ).Debug( 6 );
                            }
                        }
                    }
                } catch( Exception excp ) {
                    String.Format( "EVENT DELEGATE Task {0} threw and exception. {1}", name, excp.Message ).Debug( 1 );
                }
            } );
            timer.Start();
            return timer;
        }
Esempio n. 50
0
 public void Can_use_enum_as_key_in_map()
 {
     var dto = new Dictionary<AnEnum, int> { { AnEnum.This, 1 } };
     var json = dto.ToJson();
     json.Print();
     
     var map = json.FromJson<Dictionary<AnEnum, int>>();
     Assert.That(map[AnEnum.This], Is.EqualTo(1));
 }
Esempio n. 51
0
 //获取要记录的日志内容
 private string GetLogContent(DbPropertyValues values, IEnumerable<string> properties)
 {
     Dictionary<string, string> result = new Dictionary<string, string>();
     foreach (var propertyName in properties)
     {
         var value = values[propertyName];
         if (value is DbPropertyValues)
         {
             var complexPropertyValues = (DbPropertyValues)value;
             result.Add(propertyName, GetLogContent(complexPropertyValues, complexPropertyValues.PropertyNames));
         }
         else
         {
             result.Add(propertyName, (value ?? "").ToString());
         }
     }
     return result.ToJson();
 }
Esempio n. 52
0
 // Put result of analysis of one subpage to table 'subpages'
 // and link it with report.
 //
 public void PutRules(int reportId, string url,
     Dictionary<string, bool> rules)
 {
     string values = String.Format("'{0}', '{1}', {2}",
         url, rules.ToJson(), reportId.ToString());
     subpages.Insert(values, "url, rules, report_id").All();
 }
Esempio n. 53
0
        public ActionResult Login(string username, string password, string validateCode)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            int msgID = 1;
            if (!ValidateValidateCode(validateCode))
            {
                msgID = -1;
            }
            else
            {
                var user = UserBiz.UserLogin(username, password, ref msgID);
                if (msgID == 1)
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserName, false);
                    //if (user.Status == ItemStatus.Supper)
                    //{
                    //    string checkcode = SupportBiz.SendShortMessageCode(user.UserName, user.HandPhone, CheckCodeType.LoginAdminShortMessageCode);
                    //    if (checkcode == "")
                    //    {
                    //        msgID = -10;
                    //    }
                    //    else
                    //    {
                    //        msgID = 99;
                    //        dic.Add("PHONE", user.HandPhone.Substring(0, 3) + "*****" + user.HandPhone.Substring(8, 3));
                    //    }
                    //}
                    //else
                    //{
                    //    System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserName, false);
                    //}
                }
            }
            dic.Add("RID", msgID.ToString());

            return Content(dic.ToJson());
        }
        protected virtual void SendErrorResult(string errorMessage)
        {
            var dictionary = new Dictionary<string, object>();
            dictionary[Constants.ErrorKey] = errorMessage;
            if (!string.IsNullOrEmpty(this.CallbackID))
            {
                dictionary[Constants.CallbackIdKey] = this.CallbackID;
            }

            this.Callback(new ResultContainer(dictionary.ToJson()));
        }
Esempio n. 55
0
 public void Work()
 {
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     //dictionary.Add("CommandType", ((int)CommandType).ToString());
     PushCommandToRest(dictionary.ToJson());
 }
Esempio n. 56
0
        private void AnalyticsLogFile(string logFile, int datetimelength)
        {
            if (string.IsNullOrEmpty(logFile))
            {
                return;
            }
            Trace.WriteLine(string.Format("{0} {1} {2}", DateTime.Now.TimeOfDay, "开始处理", logFile));

            Dictionary<string, int> dictHeader = null;
            var dictFiles = new Dictionary<string, Dictionary<string, LogEntity>>(100, StringComparer.OrdinalIgnoreCase);
            var time2 = DateTime.Now;
            var index = new LogColumnIndex();

            using (var sr = new StreamReader(logFile))
            {
                string line = null;
                string[] cols;

                while ((line = sr.ReadLine()) != null)
                {

                    if (IISHelper.IsHeader(line))
                    {
                        dictHeader = IISHelper.ParseHeader(line);
                        index.URL = dictHeader["cs-uri-stem"];
                        index.TimeTaken = dictHeader["time-taken"];
                        index.ScWin32Status = dictHeader["sc-win32-status"];
                    }
                    else
                    {
                        if (IISHelper.IsBody(line))
                        {
                            cols = line.Split(' ');

                            if (cols[index.ScWin32Status] == "0")
                            {
                                var url = cols[index.URL];
                                var time = long.Parse(cols[index.TimeTaken]);
                                if (time < numTimes.Value)
                                {
                                    continue;
                                }

                                var keyDateTime = line.Substring(0, datetimelength);//cols[index.Date]+" "+cols[index.Time].Substring(0,5);

                                if (!dictFiles.ContainsKey(url))
                                {
                                    var dict = new Dictionary<string, LogEntity>(StringComparer.OrdinalIgnoreCase);
                                    dictFiles.Add(url, dict);
                                }

                                if (dictFiles[url].ContainsKey(keyDateTime))
                                {
                                    dictFiles[url][keyDateTime].Hits++;
                                    dictFiles[url][keyDateTime].TimeSum += time;
                                }
                                else
                                {
                                    dictFiles[url].Add(keyDateTime, new LogEntity { Hits = 1, TimeSum = time });
                                }
                            }
                        }
                    }
                }
            }
            Trace.WriteLine(string.Format("{0} {1} {2} {3}", DateTime.Now.TimeOfDay, "处理完文件", logFile, DateTime.Now - time2));

            foreach (var item in dictFiles.Keys)
            {
                foreach (var item2 in dictFiles[item].Values)
                {
                    var aaa = item2.TimeSum / item2.Hits;
                    if (aaa>int.MaxValue)
                    {
                        aaa = int.MaxValue;
                    }
                    item2.TimeAvg = Convert.ToInt32(aaa);
                }
            }
            File.WriteAllText(logFile + ".json.txt", dictFiles.ToJson());
        }
Esempio n. 57
0
 /// <summary>
 /// Executes all requets as JSON method/arg pairs
 /// </summary>
 /// <param name="adminMode">if set to <c>true</c> [Admin mode].</param>
 /// <returns></returns>
 internal static string ExecuteJSONResponders(bool adminMode)
 {
     HttpContext current = HttpContext.Current;
     HttpRequest request = HttpContext.Current.Request;
     HttpResponse response = HttpContext.Current.Response;
     string requestContentType = request.ContentType;
     int requestLength = request.TotalBytes;
     int requestCount = 0;
     int querystringCount = 0;
     DateTime start = new DateTime();
     start = DateTime.Now;
     Dictionary<string, object> j = new Dictionary<string, object>();
     requestCount = request.Form.Count;
     querystringCount = request.QueryString.Count;
     for(var x = 0; requestCount > x; x++) {
         string keyName = request.Form.GetKey(x);
         if(keyName.StartsWith(Main.MethodKey)) {
             j.Add(keyName, JsonToMethod(request.Form[x], adminMode));
         }
     }
     for(var x = 0; querystringCount > x; x++) {
         string keyName = request.QueryString.GetKey(x);
         if(keyName != null) {
             if(keyName.StartsWith(Main.MethodKey)) {
                 j.Add(keyName, JsonToMethod(request.QueryString[x], adminMode));
             }
         }
     }
     if(j.Count > 0) {
         /* if there is a file present output the file instead of the json string */
         foreach(KeyValuePair<string, object> field in j) {
             Dictionary<string, object> innerFields = (Dictionary<string, object>)field.Value;
             foreach(KeyValuePair<string, object> innerField in innerFields) {
                 if(innerField.Value != null) {
                     if(innerField.Value.GetType() == typeof(Dictionary<string, object>)) {
                         Dictionary<string, object> iiFields = (Dictionary<string, object>)innerField.Value;
                         if(iiFields.ContainsKey("fileName")) {
                             string content = (string)iiFields["content"].ToString();
                             response.ContentType = (string)iiFields["contentType"];
                             response.Write(content);
                             response.AddHeader("Content-Disposition", "attachment; filename=\"" + (string)iiFields["fileName"] + "\"");
                             response.AddHeader("Content-Length", content.Length.ToString());
                             response.Flush();
                             current.ApplicationInstance.CompleteRequest();
                             /* only allowed to output one file at a time */
                             return "";
                         }
                     }
                 }
             }
         }
         if(Main.Site != null) {
             EndRequestEventArgs f = new EndRequestEventArgs(Main.GetCurrentSession(), current);
             Main.Site.raiseOnendrequest(f);
         }
         return j.ToJson();
     } else {
         if(Main.Site != null) {
             EndRequestEventArgs f = new EndRequestEventArgs(Main.GetCurrentSession(), current);
             Main.Site.raiseOnendrequest(f);
         }
         return "";
     }
 }
Esempio n. 58
0
        /// <summary>
        /// Handles adding families from the given XML element snippet
        /// </summary>
        /// <param name="elemFamilies">The xml element containing all the families.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddFamilies( XElement elemFamilies, RockContext rockContext )
        {
            if ( elemFamilies == null )
            {
                return;
            }

            // Persist the storage type's settings specific to the photo binary file type
            var settings = new Dictionary<string, string>();
            if ( _personImageBinaryFileType.Attributes == null )
            {
                _personImageBinaryFileType.LoadAttributes();
            }
            foreach ( var attributeValue in _personImageBinaryFileType.AttributeValues )
            {
                settings.Add( attributeValue.Key, attributeValue.Value.Value );
            }
            _personImageBinaryFileTypeSettings = settings.ToJson();

            bool fabricateAttendance = GetAttributeValue( "FabricateAttendance" ).AsBoolean();
            GroupService groupService = new GroupService( rockContext );
            var allFamilies = rockContext.Groups;

            List<Group> allGroups = new List<Group>();
            var attendanceData = new Dictionary<Guid, List<Attendance>>();

            // Next create the family along with its members and related data
            foreach ( var elemFamily in elemFamilies.Elements( "family" ) )
            {
                Guid guid = elemFamily.Attribute( "guid" ).Value.Trim().AsGuid();
                var familyMembers = BuildFamilyMembersFromXml( elemFamily.Element( "members" ), rockContext );

                // Call replica of groupService's SaveNewFamily method in an attempt to speed things up
                Group family = CreateNewFamily( familyMembers, campusId: 1 );
                family.Guid = guid;

                // add the family to the context's list of groups
                allFamilies.Add( family );

                // add the families address(es)
                AddFamilyAddresses( groupService, family, elemFamily.Element( "addresses" ), rockContext );

                // add their attendance data
                if ( fabricateAttendance )
                {
                    AddFamilyAttendance( family, elemFamily, rockContext, attendanceData );
                }

                allGroups.Add( family );

                _stopwatch.Stop();
                AppendFormat( "{0:00}:{1:00}.{2:00} added {3}<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10, family.Name );
                _stopwatch.Start();
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            // Now save each person's attributevalues (who had them defined in the XML)
            // and add each person's ID to a dictionary for use later.
            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} saving attributes for everyone...<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();
            AttributeValueService attributeValueService = new AttributeValueService( rockContext );
            foreach ( var gm in allGroups.SelectMany( g => g.Members ) )
            {
                // Put the person's id into the people dictionary for later use.
                if ( !_peopleDictionary.ContainsKey( gm.Person.Guid ) )
                {
                    _peopleDictionary.Add( gm.Person.Guid, gm.Person.Id );
                }

                // Only save if the person had attributes, otherwise it will error.
                if ( _personWithAttributes.ContainsKey( gm.Person.Guid ) )
                {
                    foreach ( var attributeCache in gm.Person.Attributes.Select( a => a.Value ) )
                    {
                        var newValue = gm.Person.AttributeValues[attributeCache.Key];
                        if ( newValue != null )
                        {
                            var attributeValue = new AttributeValue();
                            attributeValue.AttributeId = newValue.AttributeId;
                            attributeValue.EntityId = gm.Person.Id;
                            attributeValue.Value = newValue.Value;
                            rockContext.AttributeValues.Add( attributeValue );
                        }
                    }
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} attributes saved<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Create person alias records for each person manually since we set disablePrePostProcessing=true on save
            PersonService personService = new PersonService( rockContext );
            foreach ( var person in personService.Queryable( "Aliases", true )
                .Where( p =>
                    _peopleDictionary.Keys.Contains( p.Guid ) &&
                    !p.Aliases.Any() ) )
            {
                person.Aliases.Add( new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid } );
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} added person aliases<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Put the person alias ids into the people alias dictionary for later use.
            PersonAliasService personAliasService = new PersonAliasService( rockContext );
            foreach ( var personAlias in personAliasService.Queryable( "Person" )
                .Where( a =>
                    _peopleDictionary.Keys.Contains( a.Person.Guid ) &&
                    a.PersonId == a.AliasPersonId ) )
            {
                _peopleAliasDictionary.Add( personAlias.Person.Guid, personAlias.Id );
            }

            // Now that person aliases have been saved, save the attendance records
            var attendanceService = new AttendanceService( rockContext );
            var attendanceGuids = attendanceData.Select( a => a.Key ).ToList();
            foreach ( var aliasKeyValue in _peopleAliasDictionary
                .Where( a => attendanceGuids.Contains( a.Key )) )
            {
                foreach ( var attendance in attendanceData[aliasKeyValue.Key] )
                {
                    attendance.PersonAliasId = aliasKeyValue.Value;
                    attendanceService.Add( attendance );
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );

            _stopwatch.Stop();
            AppendFormat( "{0:00}:{1:00}.{2:00} added attendance records<br/>", _stopwatch.Elapsed.Minutes, _stopwatch.Elapsed.Seconds, _stopwatch.Elapsed.Milliseconds / 10 );
            _stopwatch.Start();

            // Now re-process the family section looking for any giving data.
            // We do this last because we need the personAliases that were just added.
            // Persist the storage type's settings specific to the contribution binary file type
            settings = new Dictionary<string, string>();
            if ( _checkImageBinaryFileType.Attributes == null )
            {
                _checkImageBinaryFileType.LoadAttributes();
            }
            foreach ( var attributeValue in _checkImageBinaryFileType.AttributeValues )
            {
                settings.Add( attributeValue.Key, attributeValue.Value.Value );
            }
            _checkImageBinaryFileTypeSettings = settings.ToJson();

            foreach ( var elemFamily in elemFamilies.Elements( "family" ) )
            {
                // add the families giving data
                if ( GetAttributeValue( "EnableGiving" ).AsBoolean() )
                {
                    // Support multiple giving elements per family
                    foreach ( var elementGiving in elemFamily.Elements( "giving" ) )
                    {
                        AddFamilyGiving( elementGiving, elemFamily.Attribute( "name" ).Value, rockContext );
                    }
                }
            }

            if ( GetAttributeValue( "EnableGiving" ).AsBoolean() )
            {
                // Now add the batches to the service to be persisted
                var financialBatchService = new FinancialBatchService( rockContext );
                foreach ( var financialBatch in _contributionBatches )
                {
                    financialBatchService.Add( financialBatch.Value );
                }
            }
            rockContext.ChangeTracker.DetectChanges();
            rockContext.SaveChanges( disablePrePostProcessing: true );
        }
Esempio n. 59
0
        public void Register(IEventSubscription sub, Dictionary<string, string> connectArgs = null)
        {
            if (sub == null)
                throw new ArgumentNullException("subscription");

            var info = sub.GetInfo();
            using (var redis = clientsManager.GetClient())
            {
                StoreSubscriptionInfo(redis, info);
            }

            if (connectArgs != null)
                sub.Publish("cmd.onConnect", connectArgs.ToJson());

            local.Register(sub);
        }
Esempio n. 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Session"/> class.
 /// </summary>
 /// <param name="_site">The _site.</param>
 public Session( Site _site )
 {
     getServerStateInfo();
     Site = _site;
     string sessionid = null;
     bool newsession = false;
     string cookieName = "";
     cookieName = Site.cookie_name;
     HttpCookie http_cookie_sessionid = null;
     if(HttpContext.Current!=null){
         try {
             http_cookie_sessionid = HttpContext.Current.Request.Cookies[ cookieName ];
         } catch( Exception e ) {
             Exception ex = new Exception( "Cannot aquire cookie from client:" + e.Message );
             http_cookie_sessionid = null;
             throw ex;
         }
     }
     if( http_cookie_sessionid == null ) {
         newsession = true;
     }
     Dictionary<string, object> j = new Dictionary<string, object>();
     if( newsession ) {
         CreateNewSession( true );
         j.Add( "newSession", true );
     } else {
         if( Utilities.GuidPattern.IsMatch( http_cookie_sessionid.Value.ToString() ) ) {
             sessionid = http_cookie_sessionid.Value.ToString();
             Id = new Guid( http_cookie_sessionid.Value.ToString() );
             j.Add( "newSession", false );
         }
     }
     j.Add( "ip", Ip );
     j.Add( "sessionId", Id.ToString() );
     j.Add( "URL", Url + Path );
     j.Add( "userAgent", UserAgent );
     j.Add( "referer", Referer );
     j.Add( "host", Host );
     ( "connection>" + j.ToJson() ).Debug( 10 );
     Refresh();
     return;
 }