Example #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;
        }
Example #2
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 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);
 }
 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);
 }
Example #5
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;
        }
        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()));
        }
Example #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);
 }
Example #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")));
        }
Example #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;
        }
Example #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;
        }
Example #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);

            }
        }
Example #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());
 }
Example #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;
 }
Example #15
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();
        }
Example #16
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();
        }
        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());
        }
Example #18
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());
        }
        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);
        }
Example #20
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();
 }
Example #21
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;
        }
Example #22
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());
        }
Example #23
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));
 }
        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()));
        }
Example #25
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();
 }
Example #26
0
 public void Work()
 {
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     //dictionary.Add("CommandType", ((int)CommandType).ToString());
     PushCommandToRest(dictionary.ToJson());
 }
Example #27
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;
 }
Example #28
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());
        }
Example #29
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 "";
     }
 }
Example #30
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 );
        }