Exemplo n.º 1
0
        /// <summary>
        /// Serialize collection of objects with names to string.
        /// </summary>
        /// <param name="specialities">Collection of objects to serialize.</param>
        /// <returns>String with collection elements names.</returns>
        private string _SerializeNames(IEnumerable specialities)
        {
            if (specialities == null)
            {
                return(null);
            }

            // Get names from objects collection.
            var names = new List <string>();

            foreach (ISupportName spec in specialities)
            {
                names.Add(spec.Name);
            }

            if (names.Count == 0)
            {
                return(null);
            }

            // Serialize names list.
            var speciality = new Specialities();

            speciality.Names = names;
            return(JsonSerializeHelper.Serialize(speciality));
        }
        public bool EditBook(EditBookViewModel model)
        {
            var tags      = _tagRepository.GetAllTags();
            var saveModel = new EditBookDbViewModel();

            saveModel.Title             = model.Title;
            saveModel.Context           = model.Context;
            saveModel.Tags              = JsonSerializeHelper.Serialize(model.Tags);
            saveModel.IncludeInHomePage = model.IncludeInHomePage;
            var result = _bookRepository.EditBook(saveModel);

            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Serializes route settings for the specified date.
        /// </summary>
        private string _SerializeRouteSettings()
        {
            var solverSettings = _solver.SolverSettings;

            var restrictions = solverSettings.Restrictions
                               .Select(restriction => new RestrictionAttributeInfo
            {
                Name      = restriction.NetworkAttributeName,
                IsEnabled = restriction.IsEnabled,
            })
                               .ToArray();

            var value      = default(object);
            var attributes =
                (from attribute in _solver.NetworkDescription.NetworkAttributes
                 from parameter in attribute.Parameters
                 let hasValue = solverSettings.GetNetworkAttributeParameterValue(
                     attribute.Name,
                     parameter.Name,
                     out value)
                                where hasValue && value != null
                                group new ParameterInfo(
                     parameter.RoutingName,
                     value.ToString(),
                     // Check that parameter is restriction usage parameter.
                     // In case if attribute has restriction usage parameter name check that it is
                     // equal to current parameter name, otherwise, false.
                     attribute.RestrictionUsageParameter != null ?
                     parameter.Name == attribute.RestrictionUsageParameter.Name : false)
                                by attribute.RoutingName into info
                                select new AttributeInfo
            {
                Name = info.Key,
                Parameters = info.ToArray(),
            }).ToArray();

            var settings = new RouteSettings
            {
                UTurnPolicy           = solverSettings.GetUTurnPolicy(),
                ImpedanceAttribute    = _solver.NetworkDescription.ImpedanceAttributeName,
                DirectionsLengthUnits = RequestBuildingHelper.GetDirectionsLengthUnits(),
                Restrictions          = restrictions,
                Attributes            = attributes,
                BreakTolerance        = _settings.BreakTolerance
            };

            return(JsonSerializeHelper.Serialize(settings));
        }
Exemplo n.º 4
0
        public async static Task <PostResult> PostBlogCommentVoteAsync(VoteBlogComment voteBlogComment)
        {
            try
            {
                string data = JsonSerializeHelper.Serialize(voteBlogComment);
                string json = await HttpHelper.Post(WcfApiUrlConstants.VoteBlogComment, data, CacheManager.LoginUserInfo.Cookies);

                PostResult response = JsonSerializeHelper.Deserialize <PostResult>(json);
                return(response);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return(new PostResult()
                {
                    IsSuccess = false, Message = "提交时发送异常"
                });
            }
        }
        BackgroundTaskDeferral _deferral; // Note: defined at class scope so we can mark it complete inside the OnCancel() callback if we choose to support cancellation
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            //
            // TODO: Insert code to start one or more asynchronous methods using the
            //       await keyword, for example:
            //
            // await ExampleMethodAsync();
            //
            //获取第一条博客
            List <News> news = await NewsService.GetHotNewsDataArticlesAsync(1);

            var  lastNews           = news.LastOrDefault();
            bool needPostNotifition = NeedPostNotifition(lastNews);

            if (needPostNotifition) //推送过,且未包含感兴趣的新闻,则通知
            {
                //更新磁铁
                string url = (await NewsService.GetNewsBodyAsync(lastNews.Id)).ImageUrl;
                //可能有多个图片用;分割,且以//开头,去掉//
                //images2015.cnblogs.com/news/66372/201701/66372-20170105220153644-24320897.jpg;
                if (!url.IsNullOrEmpty())
                {
                    url = "http://" + url.Split(';')[0].TrimStart('/');
                }
                //string locaFileName = await ImageStorageHelper.GetLocalImageName(url);
                //if (locaFileName.IsNullOrEmpty())
                //{
                //    //不存在缓存时才通知
                //    url = await Core.HttpHelper.DownloadImage(url);
                //}
                string command = new QueryString()
                {
                    { "action", "HotNews" },
                    { "queryString", JsonSerializeHelper.Serialize(lastNews) }
                }.ToString();
                ToastNotificationHelper.PushToastNotification(command, lastNews.Id, lastNews.Title, lastNews.Summary, lastNews.TopicIcon, url);
                //加入最后推送缓存
                RoamingSetting.Current.SetSetting("LastNotifitionNewsId", lastNews.Id);
            }
            //
            _deferral.Complete();
        }
Exemplo n.º 6
0
        private static string _ParamValueToString(object value,
                                                  IEnumerable <Type> knownTypes)
        {
            string valueStr = ""; // reserve empty string for null values

            if (value != null)
            {
                if (_IsJsonObject(value))
                {
                    // serialize JSON object
                    valueStr = JsonSerializeHelper.Serialize(value, knownTypes, true);
                }
                else
                {
                    // serialize non-JSON object
                    valueStr = value.ToString();
                }
            }

            return(valueStr);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Converts attribute parameters to text.
        /// </summary>
        /// <returns>Attribute parameters string.</returns>
        private string _FormatAttrParameters()
        {
            string result = null;

            RouteAttrParameters parameters = _ConvertAttrParameters(
                _context.NetworkDescription.NetworkAttributes,
                _context.SolverSettings);

            if (parameters.Parameters.Length > 0)
            {
                string value = JsonSerializeHelper.Serialize(parameters);

                Match match = Regex.Match(value, "\\[.+\\]");
                if (!match.Success || string.IsNullOrEmpty(match.Value))
                {
                    throw new RouteException(Properties.Messages.Error_AttrParametersFormat); // exception
                }
                result = match.Value;
            }

            return(result);
        }
Exemplo n.º 8
0
        public async static Task <LoginResult> SignInAsync(LoginUserInfo loginUserInfo)
        {
            try
            {
                string data    = JsonSerializeHelper.Serialize(loginUserInfo);
                var    content = new StringContent(data, Encoding.UTF8, Constants.JsonMediaType);

                Uri uri = new Uri(WcfApiUrlConstants.LoginUrl);
                content.Headers.Add(Constants.XRequestWith, Constants.XmlHttpRequest);
                content.Headers.Add(Constants.VerificationToken, loginUserInfo.VerificationToken);
                HttpHelper.HttpClientHandler.CookieContainer.Add(uri, new Cookie(Constants.ServerId, loginUserInfo.ServerId));
                HttpHelper.HttpClientHandler.CookieContainer.Add(uri, new Cookie(Constants.AspxAutoDetectCookieSupport, "1"));
                var response = await HttpHelper.HttpClient.PostAsync(uri, content);

                response.EnsureSuccessStatusCode();
                string responseContent = await response.Content.ReadAsStringAsync();

                LoginResult postResult = JsonSerializeHelper.Deserialize <LoginResult>(responseContent);
                if (postResult.Success)// || postResult.Message == Constants.HadLogined)//提示已登录过cnblogs不能从响应中获取cookie。
                {
                    Cookie cookie = HttpHelper.LoadCookieFromHeader(response.Headers, Constants.AuthenticationCookiesName);
                    HttpHelper.HttpClientHandler.CookieContainer.Add(uri, cookie);
                    //登录成功先保存cookie
                    CacheManager.Current.UpdateCookies(cookie);
                }
                return(postResult);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return(new LoginResult()
                {
                    Success = false, Message = exception.Message
                });
            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Serializes the specified object.
 /// </summary>
 /// <param name="value">The reference to the object to be serialized.</param>
 /// <returns>String representation of the specified object.</returns>
 public string Serialize(object value)
 {
     return(JsonSerializeHelper.Serialize(value));
 }
Exemplo n.º 10
0
        /// <summary>
        /// Applies specified edits to the feature layer.
        /// </summary>
        /// <param name="newObjects">The reference to the collection of feature records to
        /// be added to the layer. Values of object ID field will be ignored.</param>
        /// <param name="updatedObjects">The reference to the collection of feature records
        /// to be updated.</param>
        /// <param name="deletedObjectIDs">The reference to the collection of object IDs of
        /// feature records to be deleted.</param>
        /// <returns>A reference to the collection of object IDs of added feature
        /// records.</returns>
        /// <exception cref="System.ArgumentNullException"><paramref name="newObjects"/>,
        /// <paramref name="updatedObjects"/>, <paramref name="deletedObjectIDs"/> or any element
        /// in the <paramref name="newObjects"/> or <paramref name="updatedObjects"/> is a null
        /// reference.</exception>
        /// <exception cref="ESRI.ArcLogistics.Tracking.TrackingService.TrackingServiceException">
        /// Failed to apply edits to the feature layer.</exception>
        /// <exception cref="ESRI.ArcLogistics.CommunicationException">failed
        /// to communicate with the REST service.</exception>
        public IEnumerable <long> ApplyEdits(
            IEnumerable <TFeatureRecord> newObjects,
            IEnumerable <TFeatureRecord> updatedObjects,
            IEnumerable <long> deletedObjectIDs)
        {
            if (newObjects == null || newObjects.Any(obj => obj == null))
            {
                throw new ArgumentNullException("newObjects");
            }

            if (updatedObjects == null || updatedObjects.Any(obj => obj == null))
            {
                throw new ArgumentNullException("updatedObjects");
            }

            if (deletedObjectIDs == null)
            {
                throw new ArgumentNullException("deletedObjectIDs");
            }

            if (!newObjects.Any() && !updatedObjects.Any() && !deletedObjectIDs.Any())
            {
                return(Enumerable.Empty <long>());
            }

            var itemsToDelete = updatedObjects.Where(
                item => item.Deleted == DeletionStatus.Deleted);

            if (typeof(TFeatureRecord) == typeof(Device) && itemsToDelete.Any())
            {
                var itemsMessages = JsonSerializeHelper.Serialize(
                    itemsToDelete.Select(_mapper.MapObject).ToArray());
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendFormat(
                    "Executing deletion for {0} records:\n",
                    typeof(TFeatureRecord));
                messageBuilder.Append(string.Join("\n", itemsMessages));

                Logger.Info(messageBuilder.ToString());
            }

            var request = new ApplyEditsRequest
            {
                Adds = JsonProcHelper.DoPostProcessing(JsonSerializeHelper.Serialize(newObjects
                                                                                     .Select(_mapper.MapObject)
                                                                                     .ToArray(),
                                                                                     VrpRequestBuilder.JsonTypes)),
                Updates = JsonProcHelper.DoPostProcessing(JsonSerializeHelper.Serialize(updatedObjects
                                                                                        .Select(_mapper.MapObject)
                                                                                        .ToArray(),
                                                                                        VrpRequestBuilder.JsonTypes)),
                Deletes = string.Join(",", deletedObjectIDs),
            };

            var query   = RestHelper.BuildQueryString(request, Enumerable.Empty <Type>(), true);
            var url     = string.Format(APPLY_EDITS_URL_FORMAT, _uri.AbsoluteUri);
            var options = new HttpRequestOptions
            {
                Method          = HttpMethod.Post,
                UseGZipEncoding = true,
            };

            var response = _requestSender.SendRequest <ApplyEditsResponse>(url, query, options);

            var failures = response
                           .AddResults
                           .Concat(response.UpdateResults)
                           .Concat(response.DeleteResults)
                           .Where(editResult => !editResult.Succeeded)
                           .Select(editResult => editResult.Error)
                           .Distinct()
                           .Select(error => error == null ? null : new TrackingServiceError(
                                       error.Code,
                                       error.Description));

            if (failures.Any())
            {
                var msg = string.Format(
                    Properties.Messages.Error_FeatureLayerCannotApplyEdits,
                    _layerDescription.Name ?? string.Empty);
                throw new TrackingServiceException(msg, failures);
            }

            var ids = response.AddResults
                      .Select(addResult => addResult.ObjectID)
                      .ToList();

            return(ids);
        }