public async Task SynchItemAsync( InventoryItemSubmit item, bool isCreateNew = false, Mark mark = null )
		{
			if( mark.IsBlank() )
				mark = Mark.CreateNew();

			var parameters = new { item, isCreateNew };

			try
			{
				ChannelAdvisorLogger.LogStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) );

				await AP.CreateSubmitAsync( ExtensionsInternal.CreateMethodCallInfo( this.AdditionalLogInfo ) ).Do( async () =>
				{
					ChannelAdvisorLogger.LogTraceRetryStarted( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : parameters.ToJson() ) );
					if( !isCreateNew && !( await this.DoesSkuExistAsync( item.Sku, mark ) ) )
						return;

					var resultOfBoolean = await this._client.SynchInventoryItemAsync( this._credentials, this.AccountId, item ).ConfigureAwait( false );
					CheckCaSuccess( resultOfBoolean.SynchInventoryItemResult );
					ChannelAdvisorLogger.LogTraceRetryEnd( this.CreateMethodCallInfo( mark : mark, methodResult : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : resultOfBoolean.ToJson(), additionalInfo : this.AdditionalLogInfo(), methodParameters : !this.LogDetailsEnum.HasFlag( LogDetailsEnum.LogParametersAndResultForRetry ) ? null : parameters.ToJson() ) );
				} ).ConfigureAwait( false );
				ChannelAdvisorLogger.LogEnd( this.CreateMethodCallInfo( mark : mark, methodResult : "void", additionalInfo : this.AdditionalLogInfo(), methodParameters : parameters.ToJson() ) );
			}
			catch( Exception exception )
			{
				var channelAdvisorException = new ChannelAdvisorException( this.CreateMethodCallInfo( mark : mark, additionalInfo : this.AdditionalLogInfo() ), exception );
				ChannelAdvisorLogger.LogTraceException( channelAdvisorException );
				throw channelAdvisorException;
			}
		}
        public void ShouldHandlerConvertCardFromCheckList()
        {
            // Setup
            var time1 = DateTime.Parse("2012-01-01");
            var list1 = new List {Id = "list-1-id"};
            var card = new Card {Id = "card-id", List = list1};
            var lists = List.CreateLookupFunction(list1);
            var convertCardAction = new
                {
                    type = Action.ConvertToCardFromCheckItem,
                    date = time1.ToString("o")
                };

            var actions = new
                {
                    actions = new[]
                        {
                            convertCardAction
                        }
                };

            // Exercise
            _parser.ProcessCardHistory(card, actions.ToJson(), lists);

            // Verify
            var actualListHistory = GetActualHistory(card);
            var expectedListHistory = new[]
                {
                    new {List = list1, StartTime = (DateTime?)time1, EndTime = (DateTime?) null},
                };
            Assert.That(actualListHistory, Is.EqualTo(expectedListHistory));
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        private void RecieveFile() {
    
            HttpFileCollection files = Request.Files;
            if (files.Count > 0) {
               
                int errCount = 0;

                if (files.Count == 1) {
                    //异步批量上传
                    var file = files[0];
                    errCount += Upload(file);

                    if (errCount == 0) {
                        //成功
                        var obj = new {success = "1"};
                        Response.Write(obj.ToJson());
                    }
                }
                else if (files.Count > 1) {
                    //同步批量上传

                    for (int i = 0; i < files.Count; i++) {
                        var file = files[i];
                        errCount += Upload(file);
                    }

                    if (errCount == 0) {
                        //成功
                        var obj = new {success = "1"};
                        Response.Write(obj.ToJson());
                    }

                }
            }
        }
 public void ShouldNotComplainAboutUnknownCardOrListId()
 {
     var data = new { actions = new [] { new { data = new { card = new { id = "bad-card-id" } } } } ,
                      cards = new object[0] };
     var json = data.ToJson();
     Assert.That(() => _parser.GetCards(json), Throws.Nothing);
 }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            try
            {
                var version = Engine.Persister.Get(int.Parse(context.Request[PathData.ItemQueryKey]));
                if (!version.VersionOf.HasValue)
                {
                    context.Response.Write(new { success = false, message = "Item #" + version.ID + " is not a version." }.ToJson());
                    return;
                }
                if (!version.IsPage)
                {
                    context.Response.Write(new { success = true, master = new { id = version.VersionOf.ID }, message = "Part version removed" }.ToJson());
					Engine.Persister.Delete(version);
                    return;
                }

                var newVersion = Engine.Resolve<UpgradeVersionWorker>().UpgradeVersion(version);
                var result = new { success = true, master = new { id = newVersion.Master.ID }, version = new { id = newVersion.ID, index = newVersion.VersionIndex } };
                context.Response.Write(result.ToJson());
            }
            catch (Exception ex)
            {
                new Logger<UpgradeVersionHandler>().Error("Error migrating #" + context.Request[PathData.ItemQueryKey], ex);
                context.Response.Write(new { success = false, message = ex.Message, stacktrace = ex.ToString() }.ToJson());
            }
        }
 public void TestSerializeAnonymousClass()
 {
     object a = new { X = 1 };
     var json = a.ToJson();
     var expected = "{ 'X' : 1 }".Replace("'", "\"");
     Assert.AreEqual(expected, json);
 }
    public void JsonPCallback()
    {
        string Callback = Request.QueryString["jsonp"];
        if (!string.IsNullOrEmpty(Callback))
        {
            var sessionsQuery = new SessionsQuery();
            if (HttpContext.Current.Request["query"] != null)
            {
                sessionsQuery = HttpContext.Current.Request["query"].FromJson<SessionsQuery>();
            }
            sessionsQuery.CodeCampYearId = Utils.CurrentCodeCampYear;

            sessionsQuery.WithTags = true;

            if (HttpContext.Current.Request["start"] != null && HttpContext.Current.Request["limit"] != null)
            {
                sessionsQuery.Start = Convert.ToInt32(HttpContext.Current.Request["start"]);
                sessionsQuery.Limit = Convert.ToInt32(HttpContext.Current.Request["limit"]);
            }

            var listData1 = new List<SessionsResult>();
            var sessionsManager = new SessionsManager();
            //if (HttpContext.Current.User.Identity.IsAuthenticated
            // && Utils.CheckUserIsAdmin())
            {
                listData1 = sessionsManager.Get(sessionsQuery);
                for (int i = 0; i < listData1.Count; i++)
                {
                    listData1[i].AdminComments = null;
                    listData1[i].InterestCount = "";
                    listData1[i].InterestedCount = 0;
                    listData1[i].NotInterestedCount = 0;
                    listData1[i].PlanAheadCount = "";
                    listData1[i].PlanAheadCountInt = 0;
                    listData1[i].SessionEvalsResults = null;
                    listData1[i].SpeakerPictureUrl = "http://www.siliconvalley-codecamp.com/" + listData1[i].SpeakerPictureUrl;
                    listData1[i].TitleWithPlanAttend = "";
                    listData1[i].Username = "";
                    listData1[i].WillAttendCount = 0;
                    listData1[i].WikiURL = "";
                    listData1[i].SpeakersList = null;

                }
            }

            var listData2 = (from data in listData1 orderby data.SessionTime, data.Title.ToUpper() select data).ToList();

            var ret = new { success = true, rows = listData2, total = sessionsQuery.OutputTotal };
            //HttpContext.Current.Response.ContentType = "text/plain";
            //HttpContext.Current.Response.Write(ret.ToJson());

            // *** Do whatever you need
            //Response.Write(Callback + "( {\"x\":10 , \"y\":100} );");

            Response.Write(Callback + "( " + ret.ToJson() + " );");
        }

        Response.End();
    }
Beispiel #8
0
 public static string BuildErrorJson(string type_name, string err_msg, NameValueCollection col)
 {
     var item = new
     {
         api_name = type_name,
         err_msg = err_msg,
         query = col.ToDictionary().ToJson(),
     };
     return item.ToJson();
 }
 public override HttpRequestItem BuildRequest()
 {
     var req = HttpRequestItem.CreateJsonRequest(ApiUrls.TulingRobot);
     var obj = new
     {
         key = _key,
         info = _input,
         userid = Session.User.UserName,
     };
     req.RawData = obj.ToJson();
     return req;
 }
        public void TestAnonymousClass() {
            var obj = new {
                I = 1,
                D = 1.1,
                S = "Hello"
            };
            var json = obj.ToJson();
            var expected = "{ 'I' : 1, 'D' : 1.1, 'S' : 'Hello' }".Replace("'", "\"");
            Assert.AreEqual(expected, json);

            var bson = obj.ToBson();
            Assert.Throws<InvalidOperationException>(() => BsonSerializer.Deserialize(bson, obj.GetType()));
        }
Beispiel #11
0
 public override HttpRequestItem BuildRequest()
 {
     var url = string.Format(ApiUrls.SendMsg, Session.BaseUrl);
     var obj = new
     {
         Session.BaseRequest,
         Msg = _msg
     };
     var req = new HttpRequestItem(HttpMethodType.Post, url)
     {
         RawData = obj.ToJson(),
         ContentType = HttpConstants.JsonContentType
     };
     return req;
 }
Beispiel #12
0
 public ActionResult TestTableMegaListJson(JqGridParam jqgridparam)
 {
     Stopwatch watch = CommonHelper.TimerStart();
     string UserId = ManageProvider.Provider.Current().UserId;
     DataTable ListData = this.FindTablePageBySql("SELECT TestId, Code, FullName, CreateDate, CreateUserName, Remark FROM TestTable", ref jqgridparam);
     var JsonData = new
     {
         total = jqgridparam.total,
         page = jqgridparam.page,
         records = jqgridparam.records,
         costtime = CommonHelper.TimerEnd(watch),
         rows = ListData,
     };
     return Content(JsonData.ToJson());
 }
Beispiel #13
0
        public void Serialize_An_Array()
        {
            // arrange
            var expected = @"[{""X"":""test""},{""X"":""test1""},{""X"":""test2""}]";
            var body = new[] {
                new { X = "test" },
                new { X = "test1" },
                new { X = "test2" }
            };

            // act
            var actual = body.ToJson();

            // assert
            Assert.AreEqual(expected, actual);
        }
Beispiel #14
0
 /// <summary>
 ///【备份计划】返回列表JONS
 /// </summary>
 /// <returns></returns>
 public ActionResult DbBackupList()
 {
     try
     {
         List<Base_BackupJob> ListData = DataFactory.Database().FindList<Base_BackupJob>("ORDER BY CreateDate DESC");
         var JsonData = new
         {
             rows = ListData,
         };
         return Content(JsonData.ToJson());
     }
     catch (Exception ex)
     {
         Base_SysLogBll.Instance.WriteLog("", OperationType.Query, "-1", "异常错误:" + ex.Message);
         return null;
     }
 }
Beispiel #15
0
		private void Form1_Load(object sender, EventArgs e)
		{
			var sampleObject = new 
			{
				ReportDate = DateTime.Now,
				DepartmentList = new []
				{
					new 
					{
						DepartmentName = "Developers",
						EmployeeList = new []
						{
							new { FirstName="Essie", LastName="Vaill" },
							new { FirstName="Cruz", LastName="Roudabush" },
							new { FirstName="Billie", LastName="Tinnes" },
							new { FirstName="Lashawn", LastName="Hasty" },
							new { FirstName="Marianne", LastName="Earman" }
						}
					},
					new 
					{
						DepartmentName = "QA",
						EmployeeList = new []
						{
							new { FirstName="Zackary", LastName="Mockus" },
							new { FirstName="Rosemarie", LastName="Fifield" },
							new { FirstName="Bernard", LastName="Laboy" },
						}
					},
					new
					{
						DepartmentName = "ProjectManagemnt",
						EmployeeList = new []
						{
							new { FirstName="Sue", LastName="Haakinson" },
							new { FirstName="Valerie", LastName="Pou" },
						}
					}
				}
			};
			_txtJson.Text = sampleObject.ToJson(true);
			_txtRazorView.Text = Resources.RazorSampleView;
			this.UpdatePreview();
			this.UpdateSmtpSettings();
		}
 /// <summary>
 /// 发送订单提交成功短信
 /// </summary>
 /// <param name="mobile">手机号</param>
 /// <param name="orderId">订单金额</param>
 /// <param name="totalPrice">总价</param>
 /// <returns>0为成功</returns>
 public int SendSMSOrderCreated(string mobile,long orderId, decimal totalPrice)
 {
     try
     {
         //开关,避免测试发送过多短信
         if (smsSendOnOff == "0")
         {
             return 0;
         }
         var tempParamModel = new
         {
             order_sn = orderId,
             price = totalPrice
         };
         var token = getToken();
         var smsRequestModel = new SMSRequestModel()
         {
             acceptor_tel = mobile,
             access_token = token,
             app_id = appId,
             template_id = orderTempId,
             template_param = tempParamModel.ToJson(),
             timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
         };
         var requestParamList = new List<string>();
         requestParamList.Add("acceptor_tel=" + smsRequestModel.acceptor_tel);
         requestParamList.Add("access_token=" + smsRequestModel.access_token);
         requestParamList.Add("app_id=" + smsRequestModel.app_id);
         requestParamList.Add("template_id=" + smsRequestModel.template_id);
         requestParamList.Add("template_param=" + smsRequestModel.template_param);
         requestParamList.Add("timestamp=" + smsRequestModel.timestamp);
         var sign = getSign(requestParamList);
         requestParamList.Add("sign=" + sign);
         var content = string.Join("&", requestParamList);
         var returnJson = Post(templateUrl, content);
         var smsResponseModel = JsonHelper.FromJson<SMSResponseModel>(returnJson);
         logger.Info("订单短信接口返回:" + returnJson);
         return smsResponseModel.res_code;
     }
     catch (Exception ex)
     {
         logger.Error(ex);
         return 1;
     }
 }
Beispiel #17
0
 public override HttpRequestItem BuildRequest()
 {
     var url = string.Format(ApiUrls.WebwxSync, Session.BaseUrl, Session.Sid, Session.Skey, Session.PassTicket);
     // var url = string.Format(ApiUrls.WebwxSync, Session.BaseUrl);
     var obj = new
     {
         Session.BaseRequest,
         Session.SyncKey,
         rr = ~Timestamp // 注意是按位取反
     };
     var req = new HttpRequestItem(HttpMethodType.Post, url)
     {
         RawData = obj.ToJson(),
         ContentType = HttpConstants.JsonContentType,
         Referrer = "https://wx.qq.com/?&lang=zh_CN"
     };
     return req;
 }
Beispiel #18
0
        private static string createRequest(RegistrationIdCollection registers, string groupName, Servers.GCMPushServer server)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(server._settings.DeviceGroup);

            request.Method = "POST";
            request.ContentType = "application/json";
            request.Headers.Add(string.Format("Authorization:key={0}",server._apiKey));
            request.Headers.Add(string.Format("project_id:",server._settings.ProjectNumber));

            object reqContent = new
            {
                operation = "create",
                notification_key_name = groupName,
                registration_ids = registers.toList()
            };

            var requestStream = request.GetRequestStream();
            using(var swriter = new StreamWriter(requestStream))
            {
                swriter.Write(reqContent.ToJson());
                swriter.Flush();
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseStream = response.GetResponseStream();

            string responseStr = null;

            using(var sreader = new StreamReader(responseStream))
            {
                responseStr = sreader.ReadToEnd();
            }

            if(response.StatusCode == HttpStatusCode.OK)
            {
                return responseStr;
            }
            else
            {
                return null;
            }
        }
        public void Should_log_bsondocument()
        {
            ILog target = GetConfiguredLog();
            var customProperty = new {
                Start = DateTime.Now,
                Finished = DateTime.Now,
                Input = new {
                    Count = 100
                },
                Output = new {
                    Count = 95
                }
            };
            ThreadContext.Properties["customProperty"] = customProperty.ToBsonDocument();

            target.Info("Finished");

            string customPropertyFromDbJson = _collection.FindOneAs<BsonDocument>()["customProperty"].ToJson();
            customProperty.ToJson().Should().Be.EqualTo(customPropertyFromDbJson);
        }
Beispiel #20
0
        public void Y()
        {
            var w = new W();
            var q = new[] {new Q {W = w}, new Q {W = w}};

            var working = "{'S':'Kalle'}".Replace("\'", "\"");
            var wobj = working.FromJson<W>();
            var restored = wobj.ToJson();
            var len1 = working.Length;
            var len2 = restored.Length;
            for (var i = 0; i < len1; i++)
                Debug.Print("{0} {1} {2} {3}", working[i], restored[i], (int) working[i], (int) restored[i]);
            var equals = string.CompareOrdinal(working, restored);
            var backtobasic = restored.FromJson<W>();

            var x = w.ToJson().Replace("\"", "'");
            var y = x.FromJson<W>();

            var json = q.ToJson();
            var r = json.FromJson<Q[]>();
        }
 private static void Main()
 {
     JsConfig.IncludeNullValues = true;
     var c1 = new Person { Name = "John", Address = "USA", Age = null };
     var c2 = new Person { Name = "John", Address = "USA", Age = 12 };
     var children = new List<Person> {c1};
     const string name = "Jim";
     // Uncomment lines below and check  - Children attribute is omitted from JSON result
     // children = null;
     // name = null;
     var p1 = new { Name = name, Address = "USA", Age = 40, Children = children };
     var p2 = new Person { Name = "Jim", Address = "USA", Age = null };
     p2.Children.Add(c2);
     Console.WriteLine(p1.ToJson());
     Console.WriteLine(p2.ToJson());
     //string xml =
     //    "<data><collection-title /><collection-short-title /><copyright><copyryear>2014</copyryear> <copyrholder /> </copyright><language>English</language> <object-id>1_24531314</object-id> <versionset-id>24531314</versionset-id> <document-id /> <document-path /> <status /> <document-type /> <last-modified-date /> <access /> <topic /> </data>";
     //XmlReader xmlReader = new XmlTextReader(xml, XmlNodeType.Document, null);
     //Console.WriteLine((new XmlSerializer(typeof(Data)).Deserialize(xmlReader)).ToJson());
     //Console.ReadLine();
 }
        public void ShouldTraceHistoryForCardMovedToNewBoard()
        {
            // Setup
            var list1 = new List { Id = "list-1-id" };
            var list2 = new List { Id = "list-2-id" };
            var createTime = DateTime.Parse("2012-01-01");
            var moveToBoardTime = createTime.AddMinutes(5);

            var createCardAction = JsonObjectHelpers.CreateCardAction(createTime, "card-id", "list-1-id");
            var moveCardAction = JsonObjectHelpers.MoveCardAction(moveToBoardTime, "card-id");
            var lists = List.CreateLookupFunction(list1, list2);
            var card = new Card { Id = "card-id", List = list2 };
            var actions = new { actions = new[] {
                // Keep order, Trello sends newest items first in list
                moveCardAction,
                createCardAction  }
            };

            // Exercise
            _parser.ProcessCardHistory(card, actions.ToJson(), lists);

            // verify
            var actualListHistory = GetActualHistory(card);
            var expectedListHistory = new[] {
                new { List = list1, StartTime = (DateTime?)createTime, EndTime = (DateTime?)moveToBoardTime },
                new { List = list2, StartTime = (DateTime?)moveToBoardTime, EndTime = (DateTime?)null }};
            Assert.That(actualListHistory, Is.EqualTo(expectedListHistory));
        }
        public void Can_serialize_object_array_with_nulls()
        {
            var objs = new[] { (object)"hello", (object)null };
            JsConfig.IncludeNullValues = false;

            Assert.That(objs.ToJson(), Is.EqualTo("[\"hello\",null]"));
        }
        private static void CurrentStepActivity(string status)
        {
            var percentage = (_currentStep == null) ? _upgradeProgress : _upgradeProgress + (_currentStep.Percentage / _steps.Count);
            var obj = new
            {
                progress = percentage,
                details = status,
                check0 = upgradeDatabase.Status.ToString() + (upgradeDatabase.Errors.Count == 0 ? "" : " Errors " + upgradeDatabase.Errors.Count),
                check1 = upgradeExtensions.Status.ToString() + (upgradeExtensions.Errors.Count == 0 ? "" : " Errors " + upgradeExtensions.Errors.Count)
            };

            try
            {
                if (!File.Exists(StatusFile)) File.CreateText(StatusFile);
                var sw = new StreamWriter(StatusFile, true);
                sw.WriteLine(obj.ToJson());
                sw.Close();
            }
            catch (Exception)
            {
                //TODO - do something                
            }
        }
    public void JsonPCallback()
    {
        string Callback = Request.QueryString["jsonp"];
        if (!string.IsNullOrEmpty(Callback))
        {
            var attendeesQuery = new AttendeesQuery();
            if (HttpContext.Current.Request["query"] != null)
            {
                attendeesQuery = HttpContext.Current.Request["query"].FromJson<AttendeesQuery>();
            }
            //attendeesQuery.CodeCampYearId = Utils.CurrentCodeCampYear;
           // attendeesQuery.Id = 6061;
            attendeesQuery.PresentersOnly = true;
            attendeesQuery.CodeCampYearIds = new List<int>() {7};

            int bioMaxLen = 4096;
            if (HttpContext.Current.Request["biomaxlen"] != null)
            {
                Int32.TryParse(HttpContext.Current.Request["biomaxlen"] ?? "", out bioMaxLen);
            }

            var attendeesManager = new AttendeesManager();
            var listDataSpeakers = attendeesManager.Get(attendeesQuery);

            var sessionsManager = new SessionsManager();
            var sessionsResults = sessionsManager.Get(new SessionsQuery()
            {
                CodeCampYearId = Utils.CurrentCodeCampYear
            });

            //var xxx = listDataSpeakers.Where(a => a.Id == 6061).ToList();

            //var yyy = sessionsResults.Where(a => a.Attendeesid == 6061).ToList();

            var listDataResults = (from data in listDataSpeakers
                                   orderby data.UserLastName
                                   select new
                                   {
                                       AttendeesId = data.Id,
                                       data.UserFirstName,
                                       data.UserLastName,
                                       data.UserWebsite,
                                       data.PKID,
                                       UserBio = TruncateStringWithEllipse(data.UserBio,4090),
                                       UserBioShort = TruncateStringWithEllipse(data.UserBio, bioMaxLen),
                                       data.SpeakerPictureUrl,
                                       data.TwitterHandle

                                       // AFTER REMOVING ATTENDEESID FROM SESSION THIS BROKE. NEED TO FIX IF WE WANT TO
                                       // MAKE JSONP WORK AGAIN CORRECTLY
                                       //Sessions = (from data1 in sessionsResults
                                       //           where data1.Attendeesid == data.Id &&
                                       //                 data1.CodeCampYearId == Utils.CurrentCodeCampYear
                                       //           select new
                                       //           {
                                       //               data1.Id,
                                       //               data1.Title,
                                       //               data1.Description,
                                       //               data.UserFirstName,
                                       //               data.UserLastName
                                       //           }).ToList()

                                   }).ToList();

            //var xx = listDataResults.Where(a => a.AttendeesId == 6061).ToList();

            //foreach (var rec in listDataResults)
            //{
            //    if (bioMaxLen != 0)
            //    {
            //        int oriLen = rec.UserBio.Length;
            //        if (oriLen > bioMaxLen)
            //        {
            //            rec.UserBio = rec.UserBio.Substring(0, bioMaxLen) + "...";
            //        }
            //    }
            //}

            var ret = new { success = true, rows = listDataResults, total = attendeesQuery.OutputTotal };
            Response.Write(Callback + "( " + ret.ToJson() + " );");
        }

        Response.End();
    }
        public void ShouldNotThrowExceptionWhenStartHistoryIsMissing()
        {
            // Setup
            var time = DateTime.Parse("2012-1-1");
            var actions = new
            {
                actions = new[] {
                JsonObjectHelpers.MoveToListAction(time, "card-id", "list-1-id", "list-2-id") }
            };
            var list1 = new List { Id = "list-1-id" };
            var list2 = new List { Id = "list-2-id" };
            var lists = List.CreateLookupFunction(list1, list2);
            var card = new Card { Id = "card-id", List = list1 };
            // Exercise
            _parser.ProcessCardHistory(card, actions.ToJson(), lists);

            // Verify
            var actualListHistory = GetActualHistory(card);
            var expectedListHistory = new[]
                {
                    new {List = list1, StartTime = (DateTime?)null, EndTime = (DateTime?)time },
                    new {List = list2, StartTime = (DateTime?)time, EndTime = (DateTime?) null},
                };
            Assert.That(actualListHistory, Is.EqualTo(expectedListHistory));
        }
        public void ShouldTraceHistoryForToBoardAndThenMoved()
        {
            // Setup
            var list1 = new List { Id = "list-1-id" };
            var list2 = new List { Id = "list-2-id" };
            var list3 = new List { Id = "list-3-id" };
            var lists = List.CreateLookupFunction(list1, list2, list3);
            var time1 = DateTime.Parse("2012-01-01 12:00");
            var time2 = time1.AddHours(1);
            var time3 = time2.AddHours(2);

            var actions = new
            {
                actions = new object[] {
                    // Keep order, Trello sends newest items first in list
                    JsonObjectHelpers.MoveToListAction(time3, "card-id", "list-2-id", "list-3-id"),
                    JsonObjectHelpers.MoveCardAction(time2, "card-id") ,
                    JsonObjectHelpers.CreateCardAction(time1, "card-id", "list-1-id")
                }
            };
            var card = new Card { Id = "card-id", List = list3 };

            // Exercise
            _parser.ProcessCardHistory(card, actions.ToJson(), lists);

            // verify
            var actualListHistory = GetActualHistory(card);
            var expectedListHistory = new[] {
                new { List = list1, StartTime = (DateTime?)time1, EndTime = (DateTime?)time2 },
                new { List = list2, StartTime = (DateTime?)time2, EndTime = (DateTime?)time3 },
                new { List = list3, StartTime = (DateTime?)time3, EndTime = (DateTime?)null }};
            Assert.That(actualListHistory, Is.EqualTo(expectedListHistory));
        }
        /// <summary>
        /// Processes the binary file.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uploadedFile">The uploaded file.</param>
        private void ProcessBinaryFile( HttpContext context, HttpPostedFile uploadedFile )
        {
            // get BinaryFileType info
            Guid fileTypeGuid = context.Request.QueryString["fileTypeGuid"].AsGuid();

            RockContext rockContext = new RockContext();
            BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid );

            // always create a new BinaryFile record of IsTemporary when a file is uploaded
            BinaryFile binaryFile = new BinaryFile();
            binaryFile.IsTemporary = true;
            binaryFile.BinaryFileTypeId = binaryFileType.Id;
            binaryFile.MimeType = uploadedFile.ContentType;
            binaryFile.FileName = Path.GetFileName( uploadedFile.FileName );
            binaryFile.Data = new BinaryFileData();
            binaryFile.Data.Content = GetFileBytes( context, uploadedFile );

            var binaryFileService = new BinaryFileService( rockContext );
            binaryFileService.Add( binaryFile );

            rockContext.SaveChanges();

            var response = new
            {
                Id = binaryFile.Id,
                FileName = binaryFile.FileName
            };

            context.Response.Write( response.ToJson() );
        }
        public void ShouldReturnCardsWithNameInitialized()
        {
            // Setup
            var data = new
            {
                id = "board-id",
                name = "Board name",
                cards = new[] {
                    new { id = "id-1", name = "Card 1" },
                    new { id = "id-2", name = "Card 2" } }
            };

            // Exercise
            var cards = _parser.GetCards(data.ToJson());

            // Verify
            var expected = new[] {
                new { Id = "id-1", TrelloName = "Card 1" },
                new { Id = "id-2", TrelloName = "Card 2" }};
            var actual = cards.Select(x => new { x.Id, x.TrelloName }).ToArray();
            Assert.That(actual, Is.EqualTo(expected));
        }
        /// <summary>
        /// Processes the content file.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uploadedFile">The uploaded file.</param>
        private void ProcessContentFile( HttpContext context, HttpPostedFile uploadedFile )
        {
            // validate file type (child FileUploader classes, like ImageUploader, can do additional validation);
            this.ValidateFileType( context, uploadedFile );

            // get folderPath and construct filePath
            string relativeFolderPath = context.Request.Form["folderPath"] ?? string.Empty;
            string relativeFilePath = Path.Combine( relativeFolderPath, Path.GetFileName( uploadedFile.FileName ) );
            string rootFolderParam = context.Request.QueryString["rootFolder"];

            string rootFolder = string.Empty;

            if ( !string.IsNullOrWhiteSpace( rootFolderParam ) )
            {
                // if a rootFolder was specified in the URL, decrypt it (it is encrypted to help prevent direct access to filesystem)
                rootFolder = Rock.Security.Encryption.DecryptString( rootFolderParam );
            }

            if ( string.IsNullOrWhiteSpace( rootFolder ) )
            {
                // set to default rootFolder if not specified in the params
                rootFolder = "~/Content";
            }

            string physicalRootFolder = context.Request.MapPath( rootFolder );
            string physicalContentFolderName = Path.Combine( physicalRootFolder, relativeFolderPath.TrimStart( new char[] { '/', '\\' } ) );
            string physicalFilePath = Path.Combine( physicalContentFolderName, uploadedFile.FileName );
            byte[] fileContent = GetFileBytes( context, uploadedFile );

            // store the content file in the specified physical content folder
            if ( !Directory.Exists( physicalContentFolderName ) )
            {
                Directory.CreateDirectory( physicalContentFolderName );
            }

            if ( File.Exists( physicalFilePath ) )
            {
                File.Delete( physicalFilePath );
            }

            File.WriteAllBytes( physicalFilePath, fileContent );

            var response = new
            {
                Id = string.Empty,
                FileName = relativeFilePath
            };

            context.Response.Write( response.ToJson() );
        }