public Dog(mouseHelp mouse, AppDJ appDJ)
        {
            this.appDJ = appDJ;
            this.mouse = mouse;
            screenHeight = 480;
            screenWidth = 800;

            fetch = new Fetch(this, this.mouse, this.appDJ);
            water = new Water(this, this.mouse, this.appDJ);
            food = new Food(this, this.mouse, this.appDJ);
            tug = new Tug(this, this.mouse, this.appDJ);

            statThirst = 1.0f;
            statHygiene = 1.0f;
            statHunger = 1.0f;
            statEntertainment = 1.0f;
            statHappiness = 1.0f;
            myActivity = activity.dogIdle;
            myAnimate = animate.dogSitting;
            aniX = 0;
            aniY = 0;
            myFPS = 0;
            FPS = 12;
            returnHome = false;
            tugBool = false;

            dogX = (int)((float)screenWidth * .51);
            dogY = (int)((float)screenHeight * .54);
            dogZ = 0.5f;
            dogScale = 1.0f;
            dogRec = new Rectangle(0, 0, 200, 200);
            dogRot = 0.0f;
            origin = new Vector2(dogX, dogY);
            dogPos = new Vector2(dogX, dogY);
            returnSpeedX = 2;
            returnSpeedY = 1;
            returnSpeedS = .005f;
        }
        public async Task ProtocolGateway()
        {
            int partitionId = 0;
            var router = new BrokerRouter(Options);

            var producer = new Producer(router);
            string messge1 = Guid.NewGuid().ToString();
            var respose = await producer.SendMessageAsync(IntegrationConfig.IntegrationTopic, new[] { new Message(messge1) }, 1, null, MessageCodec.CodecNone, partitionId);
            var offset = respose.FirstOrDefault().Offset;

            ProtocolGateway protocolGateway = new ProtocolGateway(IntegrationConfig.IntegrationUri);
            var fetch = new Fetch
                         {
                             Topic = IntegrationConfig.IntegrationTopic,
                             PartitionId = partitionId,
                             Offset = offset,
                             MaxBytes = 32000,
                         };

            var fetches = new List<Fetch> { fetch };

            var fetchRequest = new FetchRequest
                {
                    MaxWaitTime = 1000,
                    MinBytes = 10,
                    Fetches = fetches
                };

            var r = await protocolGateway.SendProtocolRequest(fetchRequest, IntegrationConfig.IntegrationTopic, partitionId);
            //  var r1 = await protocolGateway.SendProtocolRequest(fetchRequest, IntegrationConfig.IntegrationTopic, partitionId);
            Assert.IsTrue(r.Messages.FirstOrDefault().Value.ToUtf8String() == messge1);
        }
Beispiel #3
0
        public static void HandleResponseErrors(this FetchResponse response, Fetch request)
        {
            switch ((ErrorResponseCode)response.Error)
            {
                case ErrorResponseCode.NoError:
                    return;

                case ErrorResponseCode.OffsetOutOfRange:
                    throw new OffsetOutOfRangeException("FetchResponse indicated we requested an offset that is out of range.  Requested Offset:{0}", request.Offset) { FetchRequest = request };
                case ErrorResponseCode.BrokerNotAvailable:
                case ErrorResponseCode.ConsumerCoordinatorNotAvailableCode:
                case ErrorResponseCode.LeaderNotAvailable:
                case ErrorResponseCode.NotLeaderForPartition:
                    throw new InvalidMetadataException("FetchResponse indicated we may have mismatched metadata.  ErrorCode:{0}", response.Error) { ErrorCode = response.Error };
                default:
                    throw new KafkaApplicationException("FetchResponse returned error condition.  ErrorCode:{0}", response.Error) { ErrorCode = response.Error };
            }
        }
        /// <summary>
        /// 控制后台访问
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (!this.validateAdminPermission())
            {
                ViewBag.Title        = "受限访问";
                ViewBag.Message      = "抱歉, 系统设置了IP访问列表限制, 您无法访问本网站!";
                filterContext.Result = this.Content(this.getSystemTemplate("error.cshtml"));
                return;
            }

            if (!this.userOnlineInfo.AdminOnline)
            {
                string url = Fetch.getRawUrl();
                if (!url.EndsWith("/"))
                {
                    url += "/";
                }
                if (url != "/admin/")
                {
                    filterContext.Result = getResult(Entity.Error.登录超时, "登陆超时!");
                }
                else
                {
                    filterContext.Result = new RedirectResult("/admin/login/");
                }
                return;
            }
            else if (this.userOnlineInfo.AdminUserInfo.UserId != 1)//权限控制
            {
                object area       = null;
                object controller = null;
                if (filterContext.RouteData.Values.TryGetValue("controller", out controller) && filterContext.RouteData.DataTokens.TryGetValue("area", out area))
                {
                    if (controller != null && area != null)
                    {
                        var _controller = controller.ToString().ToLower();
                        var _area       = area.ToString().ToLower();
                        if (!(_area == "admin" && (_controller == "home" || _controller == "changepassword" || _controller == "shortcutmenu")))//排除管理主页和修改密码页
                        {
                            using (var manage = new bitcms.Data.CMSManage())
                            {
                                Entity.AdminMenuInfo meunInfo = null;
                                var menuList = manage.getAdminMenuList(_area, _controller);
                                if (menuList.Count == 1)
                                {
                                    meunInfo = menuList[0];
                                }
                                else if (menuList.Count > 1)
                                {
                                    //参数
                                    var url = Fetch.getRawUrl();
                                    if (url.IndexOf('?') > -1)
                                    {
                                        foreach (var info in menuList)
                                        {
                                            if (!string.IsNullOrEmpty(info.Parm) && url.IndexOf(info.Parm) > -1)
                                            {
                                                meunInfo = info;
                                                break;
                                            }
                                        }
                                    }
                                }
                                Entity.RolePowerInfo power = null;
                                if (meunInfo != null)
                                {
                                    power = manage.getRolePowerInfo(this.userOnlineInfo.AdminUserInfo.RoleId, meunInfo.AdminMenuId);
                                }

                                if (power == null)
                                {
                                    filterContext.Result = getResult(Entity.Error.无查看权限, "无查看权限!");
                                    return;
                                }
                                else if (Fetch.isPost() && power.Edit != 1)//post提交
                                {
                                    filterContext.Result = getResult(Entity.Error.无提交权限, "无提交权限!");
                                    return;
                                }
                                this.ViewBag.Power = power;
                            }
                        }
                    }
                }
            }
        }
Beispiel #5
0
 public bool Equals(Fetch other)
 {
     return Equals(other.value, value);
 }
        protected void btnUpdate_Click(object sender, System.EventArgs e)
        {
            Message agentBalance = FacadeManage.aideTreasureFacade.GetAgentBalance(Utility.StrToInt(this.txtScore.Text.Trim(), 0), Fetch.GetUserCookie().UserID, GameRequest.GetUserIP());

            if (agentBalance.Success)
            {
                base.ShowAndRedirect("结算成功!", "/Mobile/Agent/AgentScaleInfo.aspx");
            }
            else
            {
                base.ShowAndRedirect(agentBalance.Content, "/Mobile/Agent/AgentScaleInfo.aspx");
            }
        }
Beispiel #7
0
        /// <summary>Try to apply the special case.</summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="dependencies">The dependencies.</param>
        /// <param name="customParameters">The custom parameters.</param>
        /// <param name="fetch">The fetch.</param>
        /// <returns>True if applied, false otherwise.</returns>
        public bool TryApply(IViewConfiguration configuration, IDataAdapterDependencies dependencies, IDictionary <string, string> customParameters, Fetch fetch)
        {
            if (!this.IsApplicable(configuration))
            {
                return(false);
            }

            var contextLanguageInfo = dependencies.GetRequestContext()?.HttpContext?.GetContextLanguageInfo();

            if (contextLanguageInfo == null || !contextLanguageInfo.IsCrmMultiLanguageEnabled)
            {
                return(false);
            }

            var serviceContext       = dependencies.GetServiceContext();
            var provisionedLanguages = ContextLanguageInfo.GetProvisionedLanugages(serviceContext as IOrganizationService);

            if (!provisionedLanguages.Any())
            {
                return(false);
            }

            var languageCondition = new Condition
            {
                Attribute = "adx_systemlanguage",
                Operator  = ConditionOperator.In,
                Values    = provisionedLanguages.Cast <object>().ToArray()
            };

            var filter = new Filter {
                Conditions = new[] { languageCondition }
            };

            if (fetch.Entity.Filters == null)
            {
                fetch.Entity.Filters = new List <Filter> {
                    filter
                };
            }
            else
            {
                fetch.Entity.Filters.Add(filter);
            }

            return(true);
        }
Beispiel #8
0
        public static string GenerateSetSQL(List <SETAttribute> setList, ref StringBuilder sbSelectstr, Fetch fetchType)
        {
            StringBuilder sbSet = new StringBuilder();

            foreach (SETAttribute setAtt in setList)
            {
                if ((fetchType == Fetch.Default && !setAtt.LazyLoad) || fetchType == Fetch.SETS || fetchType == Fetch.REFSandSets)
                {
                    //如果不采用中间表的形式存储集合关联
                    if (!setAtt.IsMidTable)
                    {
                        sbSet.Append(string.Format(" left join {0} on {1}.id = {0}.{2}", setAtt.ElementEntityName, setAtt.EntityName, setAtt.ElementEntityId));
                        sbSelectstr.Append(string.Format(",{0}.id as E_{0}Id,{0}.*", setAtt.ElementEntityName));
                    }
                    //采用中间表的形式的查询SQL语句生成
                    else
                    {
                    }
                }
            }
            return(sbSet.ToString());
        }
        public Package SelectPackage()
        {
            var serviceContext = Dependencies.GetServiceContext();
            var website        = Dependencies.GetWebsite();

            var fetch = new Fetch
            {
                Version     = "1.0",
                MappingType = MappingType.Logical,
                Entity      = new FetchEntity
                {
                    Name       = Package.LogicalName,
                    Attributes = FetchAttribute.All,
                    Filters    = new[]
                    {
                        new Filter
                        {
                            Type       = LogicalOperator.And,
                            Conditions = new[]
                            {
                                new Condition("adx_packageid", ConditionOperator.Equal, Package.Id),
                                new Condition("statecode", ConditionOperator.Equal, 0),
                            }
                        }
                    },
                    Links = new Collection <Link>()
                }
            };

            AddPackageCategoryJoin(fetch.Entity);
            AddPackageComponentJoin(fetch.Entity);
            AddPackageDependencyJoin(fetch.Entity);
            AddPackageImageJoin(fetch.Entity);
            AddPackagePublisherJoin(fetch.Entity);
            AddPackageVersionJoin(fetch.Entity);

            var entityGrouping = FetchEntities(serviceContext, fetch)
                                 .GroupBy(e => e.Id)
                                 .FirstOrDefault();

            if (entityGrouping == null)
            {
                return(null);
            }

            var entity = entityGrouping.FirstOrDefault();

            if (entity == null)
            {
                return(null);
            }

            var versions = GetPackageVersions(entityGrouping, website.Id)
                           .OrderByDescending(e => e.ReleaseDate)
                           .ToArray();

            var currentVersion = versions.FirstOrDefault();

            if (currentVersion == null)
            {
                return(null);
            }

            PackageImage icon;

            var images = GetPackageImages(entityGrouping, website.Id, entity.GetAttributeValue <EntityReference>("adx_iconid"), out icon)
                         .OrderBy(e => e.Name)
                         .ToArray();

            var packageRepository = entity.GetAttributeValue <EntityReference>("adx_packagerepository");

            return(new Package
            {
                Categories = GetPackageCategories(entityGrouping).ToArray(),
                Components = GetPackageComponents(entityGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
                ContentUrl = currentVersion.Url,
                Dependencies = GetPackageDependencies(entityGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
                Description = entity.GetAttributeValue <string>("adx_description"),
                DisplayName = entity.GetAttributeValue <string>("adx_name"),
                HideFromPackageListing = entity.GetAttributeValue <bool?>("adx_hidefromlisting").GetValueOrDefault(false),
                Icon = icon,
                Images = images,
                OverwriteWarning = entity.GetAttributeValue <bool?>("adx_overwritewarning").GetValueOrDefault(false),
                PublisherName = entity.GetAttributeAliasedValue <string>("adx_name", "publisher"),
                ReleaseDate = currentVersion.ReleaseDate,
                RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
                Summary = entity.GetAttributeValue <string>("adx_summary"),
                Type = GetPackageType(entity.GetAttributeValue <OptionSetValue>("adx_type")),
                UniqueName = entity.GetAttributeValue <string>("adx_uniquename"),
                Uri = GetPackageUri(packageRepository, website.Id, entity.GetAttributeValue <string>("adx_uniquename")),
                Url = null,
                Version = currentVersion.Version,
                Versions = versions
            });
        }
Beispiel #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Guid entityId;
            var  entityIdValue        = HttpContext.Current.Request["entityid"];
            var  entityName           = HttpContext.Current.Request["entityname"];
            var  entityPrimaryKeyName = HttpContext.Current.Request["entityprimarykeyname"];
            var  formName             = HttpContext.Current.Request["formname"];
            var  controlId            = HttpUtility.HtmlEncode(HttpContext.Current.Request["controlid"]);
            int  languageCode;

            if (!Guid.TryParse(entityIdValue, out entityId) || string.IsNullOrWhiteSpace(entityName) ||
                string.IsNullOrWhiteSpace(formName) || string.IsNullOrWhiteSpace(controlId))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(entityPrimaryKeyName))
            {
                entityPrimaryKeyName = MetadataHelper.GetEntityPrimaryKeyAttributeLogicalName(ServiceContext, entityName);
            }

            if (string.IsNullOrWhiteSpace(entityPrimaryKeyName))
            {
                return;
            }

            var fetch = new Fetch
            {
                MappingType = MappingType.Logical,
                Entity      = new FetchEntity(entityName)
                {
                    Attributes = FetchAttribute.All,
                    Filters    = new List <Filter>
                    {
                        new Filter
                        {
                            Type       = LogicalOperator.And,
                            Conditions = new List <Condition> {
                                new Condition(entityPrimaryKeyName, ConditionOperator.Equal, entityId)
                            }
                        }
                    }
                }
            };

            var dataSource = new CrmDataSource
            {
                ID             = string.Format("{0}_datasource", controlId),
                FetchXml       = fetch.ToFetchExpression().Query,
                IsSingleSource = true
            };

            var formView = new CrmEntityFormView
            {
                ID                 = controlId,
                CssClass           = "crmEntityFormView",
                DataSourceID       = dataSource.ID,
                DataBindOnPostBack = true,
                EntityName         = entityName,
                FormName           = formName,
                Mode               = FormViewMode.ReadOnly,
                ClientIDMode       = ClientIDMode.Static,
                IsQuickForm        = true,
            };

            var languageCodeSetting = HttpContext.Current.Request["languagecode"];

            if (!string.IsNullOrWhiteSpace(languageCodeSetting) && int.TryParse(languageCodeSetting, out languageCode))
            {
                var found      = false;
                var portalName = languageCode.ToString(CultureInfo.InvariantCulture);
                var portals    = Microsoft.Xrm.Portal.Configuration.PortalCrmConfigurationManager.GetPortalCrmSection().Portals;

                formView.LanguageCode = languageCode;

                if (portals.Count > 0)
                {
                    foreach (var portal in portals)
                    {
                        var portalContext = portal as PortalContextElement;
                        if (portalContext != null && portalContext.Name == portalName)
                        {
                            found = true;
                        }
                    }

                    if (found)
                    {
                        formView.ContextName          = portalName;
                        dataSource.CrmDataContextName = portalName;
                    }
                }
            }

            FormPanel.Controls.Add(dataSource);
            FormPanel.Controls.Add(formView);
        }
Beispiel #11
0
        private Task ConsumeTopicPartitionAsync(string topic, int partitionId)
        {
            return Task.Run(async () =>
            {
                try
                {
                    var bufferSizeHighWatermark = FetchRequest.DefaultBufferSize;

                    _options.Log.DebugFormat("Consumer: Creating polling task for topic: {0} on parition: {1}", topic, partitionId);
                    while (_disposeToken.IsCancellationRequested == false)
                    {
                        try
                        {
                            //get the current offset, or default to zero if not there.
                            long offset = 0;
                            _partitionOffsetIndex.AddOrUpdate(partitionId, i => offset, (i, currentOffset) => { offset = currentOffset; return currentOffset; });

                            //build a fetch request for partition at offset
                            var fetch = new Fetch
                            {
                                Topic = topic,
                                PartitionId = partitionId,
                                Offset = offset,
                                MaxBytes = bufferSizeHighWatermark,
                            };

                            var fetches = new List<Fetch> { fetch };

                            var fetchRequest = new FetchRequest
                                {
                                    MaxWaitTime = (int)Math.Min((long)int.MaxValue, _options.MaxWaitTimeForMinimumBytes.TotalMilliseconds),
                                    MinBytes = _options.MinimumBytes,
                                    Fetches = fetches
                                };

                            //make request and post to queue
                            var route = _options.Router.SelectBrokerRoute(topic, partitionId);

                            var responses = await route.Connection.SendAsync(fetchRequest).ConfigureAwait(false);

                            if (responses.Count > 0)
                            {
                                var response = responses.FirstOrDefault(); //we only asked for one response

                                if (response != null && response.Messages.Count > 0)
                                {
                                    HandleResponseErrors(fetch, response);

                                    foreach (var message in response.Messages)
                                    {
                                        _fetchResponseQueue.Add(message, _disposeToken.Token);

                                        if (_disposeToken.IsCancellationRequested) return;
                                    }

                                    var nextOffset = response.Messages.Max(x => x.Meta.Offset) + 1;
                                    _partitionOffsetIndex.AddOrUpdate(partitionId, i => nextOffset, (i, l) => nextOffset);

                                    // sleep is not needed if responses were received
                                    continue;
                                }
                            }

                            //no message received from server wait a while before we try another long poll
                            Thread.Sleep(_options.BackoffInterval);
                        }
                        catch (BufferUnderRunException ex)
                        {
                            bufferSizeHighWatermark = (int)(ex.RequiredBufferSize * _options.FetchBufferMultiplier) + ex.MessageHeaderSize;
                            _options.Log.InfoFormat("Buffer underrun.  Increasing buffer size to: {0}", bufferSizeHighWatermark);
                        }
                        catch (OffsetOutOfRangeException ex)
                        {
                            //TODO this turned out really ugly.  Need to fix this section.
                            _options.Log.ErrorFormat(ex.Message);
                            FixOffsetOutOfRangeExceptionAsync(ex.FetchRequest);
                        }
                        catch (InvalidMetadataException ex)
                        {
                            //refresh our metadata and ensure we are polling the correct partitions
                            _options.Log.ErrorFormat(ex.Message);
                            _options.Router.RefreshTopicMetadata(topic);
                            EnsurePartitionPollingThreads();
                        }
                        catch (Exception ex)
                        {
                            _options.Log.ErrorFormat("Exception occured while polling topic:{0} partition:{1}.  Polling will continue.  Exception={2}", topic, partitionId, ex);
                        }
                    }
                }
                finally
                {
                    _options.Log.DebugFormat("Consumer: Disabling polling task for topic: {0} on parition: {1}", topic, partitionId);
                    Task tempTask;
                    _partitionPollingIndex.TryRemove(partitionId, out tempTask);
                }
            });
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GameScoreInfo scoreInfo = FacadeManage.aideTreasureFacade.GetTreasureInfo2(Fetch.GetUserCookie().UserID);
                if (scoreInfo != null)
                {
                    this.lblInsureScore.Text = scoreInfo.InsureScore.ToString();
                    this.lblScore.Text       = scoreInfo.Score.ToString();
                }
            }

            StringBuilder sqlQuery = new StringBuilder();

            sqlQuery.AppendFormat("select {0} from {1} where {2}='{3}'", SystemStatusInfo._StatusValue, SystemStatusInfo.Tablename, SystemStatusInfo._StatusName, "TransferPrerequisite");
            MinTradeScore = Convert.ToInt32(FacadeManage.aideAccountsFacade.GetObjectBySql(sqlQuery.ToString()));
        }
Beispiel #13
0
        /// <summary>
        /// Returns ideas that have been submitted to the idea forum this adapter applies to.
        /// </summary>
        /// <param name="startRowIndex">The row index of the first idea to be returned.</param>
        /// <param name="maximumRows">The maximum number of ideas to return.</param>
        /// <returns>type: IEnumerable</returns>
        public override IEnumerable <IIdea> SelectIdeas(int startRowIndex = 0, int maximumRows = -1)
        {
            if (startRowIndex < 0)
            {
                throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
            }

            if (maximumRows == 0)
            {
                return(new IIdea[] { });
            }

            var serviceContext = Dependencies.GetServiceContext();

            var includeUnapprovedIdeas = TryAssertIdeaPreviewPermission(serviceContext);

            var feedbackConditions = new List <Condition>
            {
                new Condition("statecode", ConditionOperator.Equal, 0),
                new Condition("rating", ConditionOperator.NotNull)
            };

            var linkEntityConditions = new List <Condition>
            {
                new Condition("statecode", ConditionOperator.Equal, 0),
                new Condition("adx_ideaforumid", ConditionOperator.Equal, IdeaForum.Id)
            };

            var pageInfo = Cms.OrganizationServiceContextExtensions.GetPageInfo(startRowIndex, maximumRows);

            var fetch = new Fetch
            {
                Aggregate  = true,
                PageSize   = pageInfo.Count,
                PageNumber = pageInfo.PageNumber,
                Entity     = new FetchEntity()
                {
                    Name       = "feedback",
                    Attributes = new List <FetchAttribute>
                    {
                        new FetchAttribute("feedbackid", "count", AggregateType.CountColumn),
                    },
                    Orders = new List <Order>
                    {
                        new Order
                        {
                            Alias     = "count",
                            Direction = OrderType.Descending,
                        }
                    },
                    Filters = new List <Filter>
                    {
                        new Filter
                        {
                            Type       = LogicalOperator.And,
                            Conditions = feedbackConditions,
                        }
                    },
                    Links = new List <Link>
                    {
                        new Link
                        {
                            Name          = "adx_idea",
                            FromAttribute = "adx_ideaid",
                            ToAttribute   = "regardingobjectid",
                            Attributes    = new List <FetchAttribute>
                            {
                                new FetchAttribute
                                {
                                    Name    = "adx_ideaid",
                                    Alias   = "ideaid",
                                    GroupBy = true,
                                }
                            },
                            Filters = new List <Filter>
                            {
                                new Filter
                                {
                                    Type       = LogicalOperator.And,
                                    Conditions = linkEntityConditions,
                                }
                            }
                        }
                    }
                }
            };

            if (MaxDate.HasValue)
            {
                linkEntityConditions.Add(new Condition("adx_date", ConditionOperator.LessThan, MaxDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture)));
            }

            if (MinDate.HasValue)
            {
                linkEntityConditions.Add(new Condition("adx_date", ConditionOperator.GreaterThan, MinDate.Value.ToUniversalTime().ToString(CultureInfo.InvariantCulture)));
            }

            if (!includeUnapprovedIdeas)
            {
                linkEntityConditions.Add(new Condition("adx_approved", ConditionOperator.Equal, "true"));
            }

            if (Status.HasValue)
            {
                linkEntityConditions.Add(new Condition("statuscode", ConditionOperator.Equal, (int)Status.Value));
            }

            var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest());

            var query = response.EntityCollection.Entities.Select(e => e.GetAttributeAliasedValue <Guid>("ideaid"));

            var ideaIds = query.ToList();

            if (!ideaIds.Any())
            {
                return(new IIdea[] { });
            }

            var ideaConditions = new List <Condition>();
            var ideaFetch      = new Fetch
            {
                Entity = new FetchEntity
                {
                    Name       = "adx_idea",
                    Attributes = FetchAttribute.All,
                    Filters    = new List <Filter>
                    {
                        new Filter
                        {
                            Type       = LogicalOperator.Or,
                            Conditions = ideaConditions,
                        }
                    }
                }
            };

            ideaConditions.AddRange(ideaIds.Select(ideaId => new Condition("adx_ideaid", ConditionOperator.Equal, ideaId)));

            var ideasFetchResponse = (RetrieveMultipleResponse)serviceContext.Execute(ideaFetch.ToRetrieveMultipleRequest());

            var ideas = ideasFetchResponse.EntityCollection.Entities.OrderBy(idea => ideaIds.IndexOf(idea.Id));

            return(new IdeaFactory(serviceContext, Dependencies.GetHttpContext(), Dependencies.GetPortalUser()).Create(ideas));
        }
Beispiel #14
0
        /// <summary>
        /// 购买商品
        /// </summary>
        /// <param name="context"></param>
        public void BuyAward(HttpContext context)
        {
            Message       msg      = new Message();
            AjaxJsonValid ajaxJson = new AjaxJsonValid();

            //判断登录
            if (!Fetch.IsUserOnline())
            {
                ajaxJson.code = 1;
                ajaxJson.msg  = "请先登录";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //获取参数
            int    typeID        = GameRequest.GetQueryInt("TypeID", 0);
            int    awardID       = GameRequest.GetFormInt("awardID", 0);                          //商品ID
            int    counts        = GameRequest.GetFormInt("counts", 0);                           //购买数量
            string compellation  = TextFilter.FilterScript(GameRequest.GetFormString("name"));    //真实姓名
            string mobilePhone   = TextFilter.FilterScript(GameRequest.GetFormString("phone"));   //移动电话
            int    province      = GameRequest.GetFormInt("province", -1);                        //省份
            int    city          = GameRequest.GetFormInt("city", -1);                            //城市
            int    area          = GameRequest.GetFormInt("area", -1);                            //地区
            string dwellingPlace = TextFilter.FilterScript(GameRequest.GetFormString("address")); //详细地址

            //验证奖品
            if (awardID == 0)
            {
                ajaxJson.msg = "非常抱歉,你所选购的商品不存在!";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //验证数量
            if (counts <= 0)
            {
                ajaxJson.msg = "请输入正确的兑换数量!";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }
            if (counts > 100)
            {
                ajaxJson.msg = "兑换数量不能超过100!";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            AwardInfo awardInfo    = FacadeManage.aideNativeWebFacade.GetAwardInfo(awardID);
            int       needInfo     = awardInfo.NeedInfo;
            int       qqValue      = (int)AppConfig.AwardNeedInfoType.QQ号码;
            int       nameValue    = (int)AppConfig.AwardNeedInfoType.真实姓名;
            int       phoneValue   = (int)AppConfig.AwardNeedInfoType.手机号码;
            int       addressValue = (int)AppConfig.AwardNeedInfoType.收货地址及邮编;

            //验证真实姓名
            if ((needInfo & nameValue) == nameValue)
            {
                msg = CheckingRealNameFormat(compellation, false);
                if (!msg.Success)
                {
                    ajaxJson.msg = "请输入正确的收件人";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
            }

            //验证手机号
            if ((needInfo & phoneValue) == phoneValue)
            {
                msg = CheckingMobilePhoneNumFormat(mobilePhone, false);
                if (!msg.Success)
                {
                    ajaxJson.msg = "请输入正确的手机号码";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
            }

            //验证地址邮编
            if ((needInfo & addressValue) == addressValue)
            {
                if (province == -1)
                {
                    ajaxJson.msg = "请选择省份";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
                if (city == -1)
                {
                    ajaxJson.msg = "请选择城市";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
                if (area == -1)
                {
                    ajaxJson.msg = "请选择地区";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
                if (string.IsNullOrEmpty(dwellingPlace))
                {
                    ajaxJson.msg = "请输入详细地址";
                    context.Response.Write(ajaxJson.SerializeToJson());
                    return;
                }
            }

            //验证用户
            UserInfo userInfo = FacadeManage.aideAccountsFacade.GetUserGlobalInfo(Fetch.GetUserCookie().UserID, 0, "").EntityList[0] as UserInfo;

            //验证余额
            int totalAmount = awardInfo.Price * counts;     //总金额

            if (totalAmount > userInfo.UserMedal)
            {
                ajaxJson.msg = "很抱歉!您的元宝数不足,不能兑换该奖品";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //验证库存
            if (awardInfo.Inventory <= 0)
            {
                ajaxJson.msg = "很抱歉!奖品的库存数不足,请更新其他奖品或者等待补充库存";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //扣除奖牌
            userInfo.UserMedal = userInfo.UserMedal - totalAmount;

            //更新奖牌
            AwardOrder awardOrder = new AwardOrder();

            awardOrder.UserID        = userInfo.UserID;
            awardOrder.AwardID       = awardID;
            awardOrder.AwardPrice    = awardInfo.Price;
            awardOrder.AwardCount    = counts;
            awardOrder.TotalAmount   = totalAmount;
            awardOrder.Compellation  = compellation;
            awardOrder.MobilePhone   = mobilePhone;
            awardOrder.QQ            = "";
            awardOrder.Province      = province;
            awardOrder.City          = city;
            awardOrder.Area          = area;
            awardOrder.DwellingPlace = dwellingPlace;
            awardOrder.PostalCode    = "";
            awardOrder.BuyIP         = Utility.UserIP;

            msg = FacadeManage.aideNativeWebFacade.BuyAward(awardOrder);
            if (msg.Success)
            {
                ajaxJson.SetValidDataValue(true);
                ajaxJson.msg = "恭喜您!兑换成功";
                awardOrder   = msg.EntityList[0] as AwardOrder;
                if (typeID == 0)
                {
                    ajaxJson.AddDataItem("uri", "/Shop/Order.aspx?param=" + awardOrder.AwardID);
                }
                else
                {
                    ajaxJson.AddDataItem("uri", "/Mobile/Shop/Order.aspx?param=" + awardOrder.AwardID);
                }
                context.Response.Write(ajaxJson.SerializeToJson());
            }
            else
            {
                ajaxJson.msg = msg.Content;
                context.Response.Write(ajaxJson.SerializeToJson());
            }
        }
Beispiel #15
0
        /// <summary>
        /// 申请退货
        /// </summary>
        /// <param name="context"></param>
        public void ReturnAward(HttpContext context)
        {
            Message       msg      = new Message();
            AjaxJsonValid ajaxJson = new AjaxJsonValid();

            //判断登录
            if (!Fetch.IsUserOnline())
            {
                ajaxJson.code = 1;
                ajaxJson.msg  = "请先登录";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //验证订单号
            int orderID = GameRequest.GetQueryInt("orderid", 0);           //订单号

            if (orderID == 0)
            {
                return;
            }

            AwardOrder awardOrder = FacadeManage.aideNativeWebFacade.GetAwardOrder(orderID, Fetch.GetUserCookie().UserID);

            if (awardOrder == null)
            {
                ajaxJson.msg = "申请退货失败,订单不存在";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }
            if (awardOrder.OrderStatus != 1 && awardOrder.OrderStatus != 2)
            {
                ajaxJson.msg = "此订单暂不允许退货";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            //验证商品是否允许退货
            AwardInfo awardInfo = FacadeManage.aideNativeWebFacade.GetAwardInfo(awardOrder.AwardID);

            if (!awardInfo.IsReturn)
            {
                ajaxJson.msg = "此商品属于不予退货服务的产品范畴";
                context.Response.Write(ajaxJson.SerializeToJson());
                return;
            }

            awardOrder.OrderStatus = (int)AppConfig.AwardOrderStatus.申请退货;
            FacadeManage.aideNativeWebFacade.UpdateAwardOrderStatus(awardOrder);
            ajaxJson.SetValidDataValue(true);
            ajaxJson.msg = "申请退货成功,请等待客服审核";
            context.Response.Write(ajaxJson.SerializeToJson());
            return;
        }
Beispiel #16
0
        /// <summary>
        /// 根据EntityInfo信息生成查询实体的SQL语句
        /// </summary>
        /// <param name="einfo">EntityInfo</param>
        /// <param name="sbSelectstr">用于追加select *的stringbuilder</param>
        /// <param name="fetchType">加载方式</param>
        /// <returns>sql语句</returns>
        public static string GenerateREFSelfSQL(EntityInfo einfo, ref StringBuilder sbSelectstr, Fetch fetchType)
        {
            StringBuilder sb = new StringBuilder();

            if (fetchType == Fetch.REFS)
            {
                sb.Append(string.Format(" left join {0} as PT on {0}.ParentId=PT.Id", einfo.EntityName));
                sbSelectstr.Append(string.Format(",PT.Id as PTId,PT.{0} as PTC", einfo.Properties[0].FieldName));
            }
            else if (fetchType == Fetch.SETS)
            {
                sb.Append(string.Format(" left join {0} as CT on {0}.Id=CT.ParentId", einfo.EntityName));
                sbSelectstr.Append(string.Format(",CT.Id as CTId,CT.ParentId as CTPId,CT.{0} as CTC", einfo.Properties[0].FieldName));
            }
            else if (fetchType == Fetch.REFSandSets)
            {
                sb.Append(string.Format(" left join {0} as PT on {0}.ParentId=PT.Id", einfo.EntityName));
                sbSelectstr.Append(string.Format(",PT.Id as PTId,PT.{0} as PTC", einfo.Properties[0].FieldName));
                sb.Append(string.Format(" left join {0} as CT on {0}.Id=CT.ParentId", einfo.EntityName));
                sbSelectstr.Append(string.Format(",CT.Id as CTId,CT.ParentId as CTPId,CT.{0} as CTC", einfo.Properties[0].FieldName));
            }
            return(sb.ToString());
        }
Beispiel #17
0
        protected override void OnStopServer()
        {
            if (_agent != null)
                _agent.Stop();

            if (_fetch != null) {
                _fetch.Stop();
                _fetch = null;
            }
        }
 public FetchXmlQueryDrop(IPortalLiquidContext portalLiquidContext, Fetch fetch, CrmEntityPermissionProvider.EntityPermissionRightResult permissionRightResult = null)
     : this(portalLiquidContext, new Lazy <Fetch>(() => fetch, LazyThreadSafetyMode.None), permissionRightResult)
 {
 }
Beispiel #19
0
        private Task ConsumeTopicPartitionAsync(string topic, int partitionId)
        {
            return Task.Run(async () =>
            {
                try
                {
                    bool refreshMetaData = false;
                    var bufferSizeHighWatermark = FetchRequest.DefaultBufferSize;

                    _options.Log.DebugFormat("Consumer: Creating polling task for topic: {0} on parition: {1}", topic, partitionId);
                    while (_disposeToken.IsCancellationRequested == false)
                    {
                        if (refreshMetaData)
                        {
                            await _options.Router.RefreshTopicMetadata(topic);
                            EnsurePartitionPollingThreads();
                            refreshMetaData = false;
                        }

                        try
                        {
                            //get the current offset, or default to zero if not there.
                            long offset = 0;
                            _partitionOffsetIndex.AddOrUpdate(partitionId, i => offset, (i, currentOffset) =>
                            {
                                offset = currentOffset;
                                return currentOffset;
                            });

                            //build a fetch request for partition at offset
                            var fetch = new Fetch
                            {
                                Topic = topic,
                                PartitionId = partitionId,
                                Offset = offset,
                                MaxBytes = bufferSizeHighWatermark,
                            };

                            var fetchRequest = fetch.ToFetchRequest(_options);

                            //make request and post to queue
                            var route = _options.Router.SelectBrokerRouteFromLocalCache(topic, partitionId);

                            var taskSend = route.Connection.SendAsync(fetchRequest);

                            await Task.WhenAny(taskSend, _disposeTask.Task).ConfigureAwait(false);
                            if (_disposeTask.Task.IsCompleted) return;

                            var responses = await taskSend; //already done
                            if (responses.Count > 0)
                            {
                                var response = responses.FirstOrDefault(); //we only asked for one response
                                
                                var hasProcessed = await ProcessResponseAndUpdateOffsetAsync(response, fetch, partitionId);

                                if (_disposeToken.IsCancellationRequested) return;

                                // sleep is not needed if responses were received
                                if (hasProcessed) continue;
                            }

                            //no message received from server wait a while before we try another long poll
                            await Task.Delay(_options.BackoffInterval, _disposeToken.Token);
                        }
                        catch (BufferUnderRunException ex)
                        {
                            bufferSizeHighWatermark = (int)(ex.RequiredBufferSize * _options.FetchBufferMultiplier) +
                                                      ex.MessageHeaderSize;
                            _options.Log.InfoFormat("Buffer underrun.  Increasing buffer size to: {0}",
                                bufferSizeHighWatermark);
                        }
                        catch (OffsetOutOfRangeException ex)
                        {
                            //TODO this turned out really ugly.  Need to fix this section.
                            _options.Log.ErrorFormat(ex.Message);
                            FixOffsetOutOfRangeExceptionAsync(ex.FetchRequest);
                        }
                        catch (InvalidMetadataException ex)
                        {
                            //refresh our metadata and ensure we are polling the correct partitions
                            refreshMetaData = true;
                            _options.Log.ErrorFormat(ex.Message);
                        }
                        catch (TaskCanceledException ex)
                        {
                            //TODO :LOG
                        }
                        catch (Exception ex)
                        {
                            _options.Log.ErrorFormat("Exception occured while polling topic:{0} partition:{1}.  Polling will continue.  Exception={2}", topic, partitionId, ex);
                        }
                    }
                }
                finally
                {
                    _options.Log.DebugFormat("Consumer: Disabling polling task for topic: {0} on parition: {1}", topic, partitionId);
                    Task tempTask;
                    _partitionPollingIndex.TryRemove(partitionId, out tempTask);
                }
            });
        }
Beispiel #20
0
 /// <summary>
 /// 页面跳转
 /// </summary>
 /// <param name="url"></param>
 protected void Redirect(string url)
 {
     Fetch.Redirect(url);
 }
        private void IncrementKnowledgeArticleReferrerViewCount(int referrer, string domainName)
        {
            var serviceContext = Dependencies.GetServiceContextForWrite();

            Condition[] conditions =
            {
                new Condition("knowledgearticleid", ConditionOperator.Equal,  KnowledgeArticle.Id),
                new Condition("viewdate",           ConditionOperator.Today),
                new Condition("adx_referrer",       ConditionOperator.Equal,  referrer)
            };

            var list = conditions.ToList();

            if (!string.IsNullOrEmpty(domainName))
            {
                list.Add(new Condition("adx_domainname", ConditionOperator.Equal, domainName));
            }
            var kbViewsfetch = new Fetch
            {
                Distinct = true,
                Entity   = new FetchEntity
                {
                    Name       = "knowledgearticleviews",
                    Attributes = new List <FetchAttribute>
                    {
                        new FetchAttribute("knowledgearticleviewsid"),
                        new FetchAttribute("knowledgearticleview"),
                    },
                    Filters = new[]
                    {
                        new Filter
                        {
                            Type       = LogicalOperator.And,
                            Conditions = list
                        }
                    },
                }
            };

            var kbViewsEntity = kbViewsfetch.Execute(serviceContext as IOrganizationService, RequestFlag.AllowStaleData).Entities.FirstOrDefault();


            if (kbViewsEntity == null)
            {
                var knowledgeArticleView = new Entity("knowledgearticleviews")
                {
                    Id = Guid.NewGuid()
                };
                knowledgeArticleView["knowledgearticleid"]   = KnowledgeArticle;
                knowledgeArticleView["viewdate"]             = DateTime.Now;
                knowledgeArticleView["adx_referrer"]         = new OptionSetValue(referrer);
                knowledgeArticleView["location"]             = new OptionSetValue(KnowledgeArticleViewCountWebLocation);
                knowledgeArticleView["knowledgearticleview"] = 1;
                knowledgeArticleView["adx_domainname"]       = string.IsNullOrEmpty(domainName) ? null : domainName;

                serviceContext.AddObject(knowledgeArticleView);
                serviceContext.SaveChanges();
            }
            else
            {
                var updateKnowledgeArticleView = new Entity("knowledgearticleviews")
                {
                    Id = kbViewsEntity.Id
                };
                updateKnowledgeArticleView["viewdate"]             = DateTime.Now;
                updateKnowledgeArticleView["knowledgearticleview"] = (int)kbViewsEntity.Attributes["knowledgearticleview"] + 1;

                var updateServiceContext = Dependencies.GetServiceContextForWrite();

                if (!updateServiceContext.IsAttached(updateKnowledgeArticleView))
                {
                    updateServiceContext.Attach(updateKnowledgeArticleView);
                }

                updateServiceContext.UpdateObject(updateKnowledgeArticleView);
                updateServiceContext.SaveChanges();
            }
        }
Beispiel #22
0
        /// <summary>
        /// 将实体的REF特性集合生成left join语句
        /// </summary>
        /// <param name="refList">REFAttribute集合</param>
        /// <param name="sbSelectstr">在生成left join的同时也改变select列表里的字符串</param>
        /// <param name="fetchType">Fetch类型</param>
        /// <returns>left join语句</returns>
        public static string GenerateLeftJoinSQL(List <REFAttribute> refList, ref StringBuilder sbSelectstr, Fetch fetchType)
        {
            StringBuilder sbLeftJoin = new StringBuilder();

            foreach (REFAttribute refAtt in refList)
            {
                if ((fetchType == Fetch.Default && !refAtt.LazyLoad) || fetchType == Fetch.REFS || fetchType == Fetch.REFSandSets)
                {
                    sbLeftJoin.Append(string.Format(" left join {0} on {1}.{2}={0}.Id",
                                                    refAtt.REFEntityName, refAtt.EntityName, refAtt.REFFieldName));
                    sbSelectstr.Append(string.Format(",{0}.id as E_{0}Id,{0}.*", refAtt.REFEntityName));
                }
            }
            return(sbLeftJoin.ToString());
        }
 public FetchXmlQueryDrop(IPortalLiquidContext portalLiquidContext, string fetchXml, CrmEntityPermissionProvider.EntityPermissionRightResult permissionRightResult = null)
     : this(portalLiquidContext, Fetch.Parse(fetchXml), permissionRightResult)
 {
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SwitchStep(1);

                Message umsg = FacadeManage.aideAccountsFacade.GetUserSecurityByUserID(Fetch.GetUserCookie().UserID);
                if (umsg.Success)
                {
                    AccountsProtect protect = umsg.EntityList[0] as AccountsProtect;

                    this.lblQuestion1.Text = protect.Question1;
                    this.lblQuestion2.Text = protect.Question2;
                    lblQuestion3.Text      = protect.Question3;
                }
                else
                {
                    RenderAlertInfo2(true, "抱歉,您还没有申请密码保护功能,不能重置银行密码!");
                }
            }
        }
        protected virtual IEnumerable <Entity> FetchEntities(OrganizationServiceContext serviceContext, Fetch fetch)
        {
            fetch.PageNumber = 1;

            while (true)
            {
                var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest());

                foreach (var entity in response.EntityCollection.Entities)
                {
                    yield return(entity);
                }

                if (!response.EntityCollection.MoreRecords)
                {
                    break;
                }

                fetch.PageNumber++;
            }
        }
Beispiel #26
0
        /// <summary>
        /// 绑定查询数据
        /// </summary>
        private void DataBindInsure( )
        {
            if (!Fetch.IsUserOnline())
            {
                return;
            }

            StringBuilder sWhere = new StringBuilder();

            sWhere.Append(" WHERE ");
            sWhere.AppendFormat("( SourceUserID = {0} OR TargetUserID = {0} ) and (TradeType = 3 or TradeType = 4)", Fetch.GetUserCookie().UserID);
            sWhere.AppendFormat(" AND CollectDate >= '{0}' AND CollectDate <= '{1}'", Convert.ToDateTime(CtrlHelper.GetText(txtStartDate) + " 00:00:00"), Convert.ToDateTime(CtrlHelper.GetText(txtEndDate) + " 23:59:59"));

            int sPageIndex = anpPage.CurrentPageIndex;
            int sPageSize  = anpPage.PageSize;

            PagerSet pagerSet = treasureFacade.GetInsureTradeRecord(sWhere.ToString(), sPageIndex, sPageSize);

            anpPage.RecordCount = pagerSet.RecordCount;

            if (pagerSet.PageSet.Tables[0].Rows.Count > 0)
            {
                rptInsureList.DataSource = pagerSet.PageSet;
                rptInsureList.DataBind();

                this.rptInsureList.Visible = true;
                this.trNoData.Visible      = false;
            }
            else
            {
                this.rptInsureList.Visible = false;
                this.trNoData.Visible      = true;
            }
        }
 protected void Page_Load(object sender, System.EventArgs e)
 {
     if (!base.IsPostBack)
     {
         this.childCount = FacadeManage.aideAccountsFacade.GetAgentChildCount(Fetch.GetUserCookie().UserID).ToString();
         System.Data.DataSet agentFinance = FacadeManage.aideTreasureFacade.GetAgentFinance(Fetch.GetUserCookie().UserID);
         this.agentRevenue  = System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentRevenue"]).ToString();
         this.agentPay      = System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentPay"]).ToString();
         this.agentPayBack  = System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentPayBack"]).ToString();
         this.agentIn       = (System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentRevenue"]) + System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentPay"]) + System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentPayBack"])).ToString();
         this.agentOut      = System.Convert.ToInt64(agentFinance.Tables[0].Rows[0]["AgentOut"]).ToString();
         this.agentRemain   = (System.Convert.ToInt64(this.agentIn) - System.Convert.ToInt64(this.agentOut)).ToString();
         this.txtScore.Text = this.agentRemain.ToString();
     }
 }
Beispiel #28
0
        private void BindData()
        {
            if (IntParam <= 0)
            {
                return;
            }
            //获取信息
            AccountsInfo model = FacadeManage.aideAccountsFacade.GetAccountInfoByUserID(IntParam);

            if (model == null)
            {
                MessageBox("用户信息不存在");
                return;
            }

            CtrlHelper.SetText(ltGameID, model.GameID.ToString());
            CtrlHelper.SetText(ltAccounts, model.Accounts.Trim());
            CtrlHelper.SetText(ltUserModel, model.UserMedal.ToString("N0"));
            CtrlHelper.SetText(ltLove, model.LoveLiness.ToString("N0"));

            UserCurrencyInfo uci = FacadeManage.aideTreasureFacade.GetUserCurrencyInfo(IntParam);

            if (uci != null)
            {
                ltCurrency.Text = uci.Currency.ToString("N0");
            }

            //游戏币信息
            GameScoreInfo scoreInfo = FacadeManage.aideTreasureFacade.GetGameScoreInfoByUserID(IntParam);

            if (scoreInfo == null)
            {
                return;
            }
            CtrlHelper.SetText(ltScore, scoreInfo.Score.ToString("N0"));
            CtrlHelper.SetText(ltInsureScore, scoreInfo.InsureScore.ToString("N0"));
            CtrlHelper.SetText(ltWinCount, scoreInfo.WinCount.ToString());
            CtrlHelper.SetText(ltLostCount, scoreInfo.LostCount.ToString());
            CtrlHelper.SetText(ltDrawCount, scoreInfo.DrawCount.ToString());
            CtrlHelper.SetText(ltFleeCount, scoreInfo.FleeCount.ToString());
            CtrlHelper.SetText(ltRevenue, scoreInfo.Revenue.ToString("N0"));

            //登录房间、注册信息
            CtrlHelper.SetText(ltGameLogonTimes, scoreInfo.AllLogonTimes.ToString());
            CtrlHelper.SetText(ltLastLogonDate, scoreInfo.AllLogonTimes == 0 ? "从未登陆房间" : scoreInfo.LastLogonDate.ToString("yyyy-MM-dd HH:mm:ss"));
            CtrlHelper.SetText(ltLogonSpacingTime, scoreInfo.AllLogonTimes == 0 ? "" : Fetch.GetTimeSpan(Convert.ToDateTime(scoreInfo.LastLogonDate), DateTime.Now) + " 前");

            CtrlHelper.SetText(ltLastLogonIP, scoreInfo.LastLogonIP.ToString());
            CtrlHelper.SetText(ltLogonIPInfo, IPQuery.GetAddressWithIP(scoreInfo.LastLogonIP.ToString()));
            CtrlHelper.SetText(ltLastLogonMachine, scoreInfo.LastLogonMachine.ToString());
            CtrlHelper.SetText(ltRegisterDate, scoreInfo.RegisterDate.ToString("yyyy-MM-dd HH:mm:ss"));
            CtrlHelper.SetText(ltRegisterIP, scoreInfo.RegisterIP.ToString());
            CtrlHelper.SetText(ltRegIPInfo, IPQuery.GetAddressWithIP(scoreInfo.RegisterIP.ToString()));
            CtrlHelper.SetText(ltRegisterMachine, scoreInfo.RegisterMachine.ToString());
            CtrlHelper.SetText(ltOnLineTimeCount, scoreInfo.OnLineTimeCount.ToString());
            CtrlHelper.SetText(ltPlayTimeCount, scoreInfo.PlayTimeCount.ToString());

            //房卡信息
            if (AllowBattle == "1")
            {
                UserRoomCard card = FacadeManage.aideTreasureFacade.GetUserRoomCard(IntParam);
                CardNumber = card == null ? "0" : card.RoomCard.ToString();
            }
        }
Beispiel #29
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string formString = GameRequest.GetFormString("account");

            if (formString == "")
            {
                base.Response.Write("充值账号错误");
                base.Response.End();
            }
            int formInt = GameRequest.GetFormInt("amount", 0);

            if (formInt < 6)
            {
                base.Response.Write("充值金额不能低于6元");
                base.Response.End();
            }
            string      text        = GameRequest.GetFormString("type");
            OnLineOrder onLineOrder = new OnLineOrder();

            onLineOrder.OrderID = PayHelper.GetOrderIDByPrefix("wt");
            if (Fetch.GetUserCookie() == null)
            {
                onLineOrder.OperUserID = 0;
            }
            else
            {
                onLineOrder.OperUserID = Fetch.GetUserCookie().UserID;
            }
            onLineOrder.Accounts    = formString;
            onLineOrder.OrderAmount = formInt;
            onLineOrder.IPAddress   = GameRequest.GetUserIP();
            string text4 = text;

            switch (text4)
            {
            case "alipay":
                text = "alipaywap";
                onLineOrder.ShareID = 2;
                goto IL_240;

            case "weixin":
                text = "wxh5";
                onLineOrder.ShareID = 3;
                goto IL_240;

            case "alipay-scan":
                text                = "alipay";
                this.paytype        = "支付宝";
                onLineOrder.ShareID = 4;
                goto IL_240;

            case "weixin-scan":
                text                = "weixin";
                this.paytype        = "微信";
                onLineOrder.ShareID = 5;
                goto IL_240;

            case "qq":
                text = "qqwallet";
                onLineOrder.ShareID = 6;
                goto IL_240;

            case "qq-scan":
                text                = "QQZF";
                this.paytype        = "QQ";
                onLineOrder.ShareID = 8;
                goto IL_240;

            case "kuaijie":
                text = "bank";
                onLineOrder.ShareID = 7;
                goto IL_240;
            }
            text = "bank";
            onLineOrder.ShareID = 1;
IL_240:
            Message message = FacadeManage.aideTreasureFacade.RequestOrder(onLineOrder);

            if (!message.Success)
            {
                base.Response.Write(message.Content);
                base.Response.End();
            }
            string str   = ApplicationSettings.Get("url_wt");
            string value = ApplicationSettings.Get("parter_wt");
            string text2 = ApplicationSettings.Get("key_wt");
            string text3 = ApplicationSettings.Get("pay_url");

            if (text3 == "")
            {
                text3 = "http://" + base.Request.Url.Host;
            }
            string orderID = onLineOrder.OrderID;
            string value2  = text3 + "/pay/wtpay/notify_url.aspx";

            System.Collections.Generic.Dictionary <string, string> dictionary = new System.Collections.Generic.Dictionary <string, string>();
            dictionary["version"]    = "1.0";
            dictionary["customerid"] = value;
            dictionary["total_fee"]  = formInt + ".00".ToString();
            dictionary["sdorderno"]  = orderID;
            dictionary["notifyurl"]  = value2;
            dictionary["returnurl"]  = value2;
            string password = string.Format("version={0}&customerid={1}&total_fee={2}&sdorderno={3}&notifyurl={4}&returnurl={5}&{6}", new object[]
            {
                dictionary["version"],
                dictionary["customerid"],
                dictionary["total_fee"],
                dictionary["sdorderno"],
                dictionary["notifyurl"],
                dictionary["returnurl"],
                text2
            });
            string value3 = TextEncrypt.EncryptPassword(password).ToLower();

            dictionary["paytype"]  = text;
            dictionary["bankcode"] = "";
            dictionary["remark"]   = "";
            dictionary["sign"]     = value3;
            string url = str + "?" + PayHelper.PrepareSign(dictionary);

            base.Response.Redirect(url);
        }
Beispiel #30
0
        private FetchRequest CreateFetchRequest(long offset)
        {
            var fetch = new Fetch() {
                Offset = offset,
                PartitionId = _partitionId,
                Topic = _topic,
                MaxBytes = _maxSizeOfMessageSet
            };

            var request = new FetchRequest()
            {
                MaxWaitTime = MaxWaitTimeForKafka,
                MinBytes = 0,
                Fetches = new List<Fetch>() { fetch },
                ClientId = _clientId
            };

            return request;
        }
Beispiel #31
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            string formString = GameRequest.GetFormString("account");

            if (formString == "")
            {
                base.Response.Write("充值账号错误");
                base.Response.End();
            }
            int formInt = GameRequest.GetFormInt("amount", 0);

            if (formInt < 6)
            {
                base.Response.Write("充值金额不能低于6元");
                base.Response.End();
            }
            string      text        = GameRequest.GetFormString("type");
            OnLineOrder onLineOrder = new OnLineOrder();

            onLineOrder.OrderID = PayHelper.GetOrderIDByPrefix("y");
            if (Fetch.GetUserCookie() == null)
            {
                onLineOrder.OperUserID = 0;
            }
            else
            {
                onLineOrder.OperUserID = Fetch.GetUserCookie().UserID;
            }
            onLineOrder.Accounts    = formString;
            onLineOrder.OrderAmount = formInt;
            onLineOrder.IPAddress   = GameRequest.GetUserIP();
            if (text == "bank")
            {
                text = "1000";
                onLineOrder.ShareID = 1;
            }
            if (text == "alipay-wap-yika")
            {
                text = "1006";
                onLineOrder.ShareID = 2;
            }
            if (text == "weixin-wap-yika")
            {
                text = "1007";
                onLineOrder.ShareID = 3;
            }
            if (text == "alipay")
            {
                text = "992";
                onLineOrder.ShareID = 4;
            }
            if (text == "weixin")
            {
                text = "1004";
                onLineOrder.ShareID = 5;
            }
            if (text == "qq-wap")
            {
                text = "1008";
                onLineOrder.ShareID = 6;
            }
            Message message = FacadeManage.aideTreasureFacade.RequestOrder(onLineOrder);

            if (!message.Success)
            {
                base.Response.Write(message.Content);
                base.Response.End();
            }
            string str   = ApplicationSettings.Get("url_yika");
            string text2 = ApplicationSettings.Get("parter_yika");
            string text3 = ApplicationSettings.Get("key_yika");
            string text4 = ApplicationSettings.Get("pay_url");

            if (text4 == "")
            {
                text4 = "http://" + base.Request.Url.Host;
            }
            string orderID  = onLineOrder.OrderID;
            string text5    = text4 + "/pay/yika/notify_url.aspx";
            string str2     = text4 + "/pay/yika/return_url.aspx";
            string password = string.Format("parter={0}&type={1}&value={2}&orderid={3}&callbackurl={4}{5}", new object[]
            {
                text2,
                text,
                formInt,
                orderID,
                text5,
                text3
            });
            string str3  = TextEncrypt.EncryptPassword(password).ToLower();
            string value = str + "?parter=" + text2;

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(value);
            stringBuilder.Append("&type=" + text);
            stringBuilder.Append("&value=" + formInt);
            stringBuilder.Append("&orderid=" + orderID);
            stringBuilder.Append("&callbackurl=" + text5);
            stringBuilder.Append("&hrefbackurl=" + str2);
            stringBuilder.Append("&payerIp=" + onLineOrder.IPAddress);
            stringBuilder.Append("&attach=");
            stringBuilder.Append("&sign=" + str3);
            stringBuilder.Append("&agent=");
            stringBuilder.Append("&playerId=");
            base.Response.Redirect(stringBuilder.ToString());
        }
Beispiel #32
0
        /// <summary>
        /// 绑定查询数据
        /// </summary>
        private void DataBindInsure()
        {
            StringBuilder sWhere = new StringBuilder();

            sWhere.Append(" WHERE ");

            if (Convert.ToInt32(ddlType.SelectedValue) != 0)
            {
                if (Convert.ToInt32(ddlType.SelectedValue) < 3)
                {
                    sWhere.AppendFormat(" TradeType = {0} AND SourceUserID = {1}", Convert.ToInt32(ddlType.SelectedValue) == 1 ? 1 : 2, Fetch.GetUserCookie().UserID);
                }
                else
                {
                    if (Convert.ToInt32(ddlType.SelectedValue) == 3)
                    {
                        sWhere.AppendFormat(" SourceUserID = {0} AND TradeType = 3 and TargetUserID <> {0}", Fetch.GetUserCookie().UserID);
                    }
                    else if (Convert.ToInt32(ddlType.SelectedValue) == 4)
                    {
                        sWhere.AppendFormat(" SourceUserID <> {0} AND TradeType = 3 and TargetUserID = {0}", Fetch.GetUserCookie().UserID);
                    }
                }
            }
            else
            {
                sWhere.AppendFormat(" SourceUserID = {0} OR TargetUserID = {0}", Fetch.GetUserCookie().UserID);
            }
            sWhere.AppendFormat(" AND CollectDate >= '{0}' AND CollectDate <= '{1}'", CtrlHelper.GetText(txtStartDate) + " 00:00:00", CtrlHelper.GetText(txtEndDate) + " 23:59:59");

            int sPageIndex = anpPage.CurrentPageIndex;
            int sPageSize  = anpPage.PageSize;

            PagerSet pagerSet = treasureFacade.GetInsureTradeRecord(sWhere.ToString(), sPageIndex, sPageSize);

            anpPage.RecordCount = pagerSet.RecordCount;

            if (pagerSet.PageSet.Tables[0].Rows.Count > 0)
            {
                rptInsureList.DataSource = pagerSet.PageSet;
                rptInsureList.DataBind();

                this.rptInsureList.Visible = true;
                this.trNoData.Visible      = false;
            }
            else
            {
                this.rptInsureList.Visible = false;
                this.trNoData.Visible      = true;
            }
        }
Beispiel #33
0
 public void Init()
 {
     _MailBox     = Client.SelectMailbox(_Cache.MailBoxName);
     _Fetch       = _MailBox.Fetch;
     _UIDValidity = _MailBox.UidValidity;
 }
Beispiel #34
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Message umsg = FacadeManage.aideAccountsFacade.GetUserGlobalInfo(Fetch.GetUserCookie().UserID, 0, "");
                if (umsg.Success)
                {
                    UserInfo ui = umsg.EntityList[0] as UserInfo;
                    accounts   = ui.Accounts;
                    nickName   = ui.NickName;
                    gameID     = ui.GameID.ToString();
                    gender     = ui.Gender == 0 ? "女" : "男";
                    experience = ui.Experience.ToString("N0");
                    if (ui.MemberOrder == 0)
                    {
                        member = GetMemberInfo(ui.MemberOrder);
                    }
                    else
                    {
                        member = GetMemberInfo(ui.MemberOrder) + "&nbsp;[" + ui.MemberOverDate.ToString("yyyy-MM-dd") + "]";
                    }
                    underWrite = ui.UnderWrite;
                    loveLiness = ui.LoveLiness.ToString("N0");
                    medal      = ui.UserMedal.ToString("N0");
                    faceUrl    = FacadeManage.aideAccountsFacade.GetUserFaceUrl(ui.FaceID, ui.CustomID);
                }

                GameScoreInfo scoreInfo = FacadeManage.aideTreasureFacade.GetTreasureInfo2(Fetch.GetUserCookie().UserID);
                if (scoreInfo != null)
                {
                    score       = scoreInfo.Score.ToString("N0");
                    insureScore = scoreInfo.InsureScore.ToString("N0");
                }

                UserCurrencyInfo currencyInfo = FacadeManage.aideTreasureFacade.GetUserCurrencyInfo(Fetch.GetUserCookie().UserID);
                if (currencyInfo != null)
                {
                    currency = currencyInfo.Currency.ToString("N");
                }
                else
                {
                    currency = "0";
                }
            }
        }
Beispiel #35
0
        protected override bool OnStartServer()
        {
            if (_agent != null)
                _agent.Start();

            //Ver5.9.8
            if (Kernel.MailBox == null || !Kernel.MailBox.Status){
                return false;
            }

                    //fetchList = (Dat) conf.Get("fetchList");
            //_timeout = (int) conf.Get("timeOut");
            //_sizeLimit = (int) conf.Get("sizeLimit");
            _fetch = new Fetch(Kernel,_mailSave,DomainList[0],(Dat) Conf.Get("fetchList"),(int) Conf.Get("timeOut"),(int) Conf.Get("sizeLimit"));
            _fetch.Start();
            return true;
        }
Beispiel #36
0
        public static int FetchBlogPostCountForWebsite(this OrganizationServiceContext serviceContext, Guid websiteId, string tag)
        {
            if (string.IsNullOrWhiteSpace(tag))
            {
                throw new ArgumentException("Value can't be null or whitespace.", "tag");
            }

            // If multi-language is enabled, only select blog posts of blogs that are language-agnostic or match the current language.
            var    contextLanguageInfo       = HttpContext.Current.GetContextLanguageInfo();
            string conditionalLanguageFilter = contextLanguageInfo.IsCrmMultiLanguageEnabled
                                ? string.Format(@"<filter type=""or"">
						<condition attribute=""adx_websitelanguageid"" operator=""null"" />
						<condition attribute=""adx_websitelanguageid"" operator=""eq"" value=""{0}"" />
					</filter>"                    , contextLanguageInfo.ContextLanguage.EntityReference.Id.ToString("D"))
                                : string.Empty;

            var fetchXml = XDocument.Parse(string.Format(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""adx_blogpost"">
						<attribute name=""adx_blogpostid"" aggregate=""count"" alias=""count"" />
						<filter type=""and"">
							<condition attribute=""adx_published"" operator=""eq"" value=""true"" />
						</filter>
						<link-entity name=""adx_blog"" from=""adx_blogid"" to=""adx_blogid"">
							<filter type=""and"">
								<condition attribute=""adx_websiteid"" operator=""eq"" />
								{0}
							</filter>
						</link-entity>
						<link-entity name=""adx_blogpost_tag"" from=""adx_blogpostid"" to=""adx_blogpostid"">
							<link-entity name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"">
								<filter type=""and"">
									<condition attribute=""adx_name"" operator=""eq"" />
								</filter>
							</link-entity>
						</link-entity>
					</entity>
				</fetch>"                , conditionalLanguageFilter));

            var websiteIdCondition = fetchXml.XPathSelectElement("//link-entity[@name='adx_blog']//condition[@attribute='adx_websiteid']");

            if (websiteIdCondition == null)
            {
                throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_websiteid filter"));
            }

            websiteIdCondition.SetAttributeValue("value", websiteId.ToString());

            var tagNameCondition = fetchXml.XPathSelectElement("//link-entity[@name='adx_tag']/filter/condition[@attribute='adx_name']");

            if (tagNameCondition == null)
            {
                throw new InvalidOperationException("Unable to select the tag name filter element.");
            }

            tagNameCondition.SetAttributeValue("value", tag);

            var entity = serviceContext.RetrieveSingle(Fetch.Parse(fetchXml.ToString()));

            return((int)entity.GetAttributeValue <AliasedValue>("count").Value);
        }
Beispiel #37
0
        public static IDictionary <Guid, Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo> > FetchBlogPostExtendedData(this OrganizationServiceContext serviceContext, IEnumerable <Guid> postIds, BlogCommentPolicy defaultCommentPolicy, Guid websiteId)
        {
            if (!postIds.Any())
            {
                return(new Dictionary <Guid, Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo> >());
            }

            var ids = postIds.ToArray();

            var fetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"">
					<entity name=""adx_blogpost"">
						<attribute name=""adx_commentpolicy"" />
						<filter type=""and"">
						</filter>
						<link-entity name=""adx_blog"" from=""adx_blogid"" to=""adx_blogid"" alias=""blog"">
							<attribute name=""adx_commentpolicy"" />
						</link-entity>
						<link-entity link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
							<attribute name=""contactid"" />
							<attribute name=""fullname"" />
							<attribute name=""firstname"" />
							<attribute name=""lastname"" />
							<attribute name=""emailaddress1"" />
						</link-entity>
						<link-entity link-type=""outer"" name=""adx_blogpost_tag"" from=""adx_blogpostid"" to=""adx_blogpostid"">
							<link-entity link-type=""outer"" name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"" alias=""tag"">
								<attribute name=""adx_name"" />
								<filter type=""and"">
									<condition attribute=""adx_websiteid"" operator=""eq"" />
								</filter>
							</link-entity>
						</link-entity>
					</entity>
				</fetch>"                );

            var postFilter = fetchXml.XPathSelectElement("//entity[@name='adx_blogpost']/filter");

            if (postFilter == null)
            {
                throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_blogpostid filter condition"));
            }

            postFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));

            var websiteConditions = fetchXml.XPathSelectElements("//filter/condition[@attribute='adx_websiteid']");

            foreach (var websiteCondition in websiteConditions)
            {
                websiteCondition.SetAttributeValue("value", websiteId.ToString());
            }

            var fetch       = Fetch.Parse(fetchXml.ToString());
            var contactLink = fetch.Entity.Links.FirstOrDefault(l => l.Name.Equals("contact"));

            if (contactLink != null)
            {
                contactLink.IsUnique = true;
            }

            var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);

            var aggregateFilter = fetchXml.Descendants("filter").First();

            aggregateFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));
            EntityCollection aggregateResponse = null;

            if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
            {
                XDocument aggregateFetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""feedback"">
						<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
						<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
						<attribute name=""rating"" alias=""value"" groupby=""true"" />
						<filter type=""and"">
							<condition attribute=""statecode"" operator=""eq"" value=""0"" />
							<condition attribute=""rating"" operator=""not-null"" />
						</filter>
						<link-entity name=""adx_blogpost"" from=""adx_blogpostid"" to=""regardingobjectid"">
							<attribute name=""adx_blogpostid"" alias=""postid"" groupby=""true"" />
							<filter type=""and"" />
						</link-entity>
					</entity>
				</fetch>"                );

                aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));
            }
            return(ids.ToDictionary(id => id, id =>
            {
                var entities = response.Entities.Where(e => e.Id == id).ToArray();

                if (!entities.Any())
                {
                    return new Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo>(null, null, defaultCommentPolicy, new string[] {}, null);
                }

                var entity = entities.First();

                var authorName = Localization.LocalizeFullName(entity.GetAttributeAliasedValue <string>("author.firstname"), entity.GetAttributeAliasedValue <string>("author.lastname"));
                var authorEmail = entity.GetAttributeAliasedValue <string>("author.emailaddress1");

                object postCommentPolicyAttributeValue;
                var postCommentPolicy = entity.Attributes.TryGetValue("adx_commentpolicy", out postCommentPolicyAttributeValue) && (postCommentPolicyAttributeValue is OptionSetValue)
                                        ? (BlogPostCommentPolicy)Enum.ToObject(typeof(BlogPostCommentPolicy), ((OptionSetValue)postCommentPolicyAttributeValue).Value)
                                        : BlogPostCommentPolicy.Inherit;

                var blogCommentPolicyOption = entity.GetAttributeAliasedValue <OptionSetValue>("blog.adx_commentpolicy");
                var blogCommentPolicy = blogCommentPolicyOption == null
                                        ? defaultCommentPolicy
                                        : (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), blogCommentPolicyOption.Value);

                var commentPolicy = postCommentPolicy == BlogPostCommentPolicy.Inherit
                                        ? blogCommentPolicy
                                        : (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), (int)postCommentPolicy);

                var tags = entities
                           .Select(e => e.GetAttributeAliasedValue <string>("tag.adx_name"))
                           .Where(tagName => !string.IsNullOrWhiteSpace(tagName))
                           .ToArray();

                int ratingCount = 0;
                int ratingSum = 0;
                double averageRating = 0;
                int yesCount = 0;
                int noCount = 0;

                if (aggregateResponse != null)
                {
                    var aggregateResults = aggregateResponse.Entities
                                           .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id);

                    var aggregateYesResult = aggregateResponse.Entities
                                             .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id)
                                             .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 1);

                    var aggregateNoResult = aggregateResponse.Entities
                                            .Where(e => e.GetAttributeAliasedValue <Guid?>("postid") == id)
                                            .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 0);

                    yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                    noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                    foreach (var aggregateResult in aggregateResults)
                    {
                        ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0;
                        ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue <int?>("ratingsum") ?? 0;
                    }

                    if (ratingCount == 0)
                    {
                        averageRating = 0;
                    }
                    else
                    {
                        averageRating = ratingSum / (double)ratingCount;
                    }
                }

                var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);

                return new Tuple <string, string, BlogCommentPolicy, string[], IRatingInfo>(authorName, authorEmail, commentPolicy, tags, ratingInfo);
            }));
        }
Beispiel #38
0
        public static IDictionary <Guid, Tuple <string, string, string, IRatingInfo> > FetchBlogPostCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable <Guid> commentIds)
        {
            if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
            {
                return(new Dictionary <Guid, Tuple <string, string, string, IRatingInfo> >());
            }
            if (!commentIds.Any())
            {
                return(new Dictionary <Guid, Tuple <string, string, string, IRatingInfo> >());
            }

            var ids = commentIds.ToArray();

            XDocument fetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"">
					<entity name=""feedback"">
						<filter type=""and"">
						</filter>
						<link-entity name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
							<attribute name=""contactid"" />
							<attribute name=""fullname"" />
							<attribute name=""firstname"" />
							<attribute name=""lastname"" />
							<attribute name=""emailaddress1"" />
							<attribute name=""websiteurl"" />
						</link-entity>
					</entity>
				</fetch>"                );

            var filter = fetchXml.Descendants("filter").First();

            filter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));

            var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));

            XDocument aggregateFetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""feedback"">
						<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
						<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
						<attribute name=""rating"" alias=""value"" groupby=""true"" />
						<link-entity name=""feedback"" from=""feedbackid"" to=""regardingobjectid"">
							<attribute name=""feedbackid"" alias=""commentid"" groupby=""true"" />
							<filter type=""and"" />
						</link-entity>
					</entity>
				</fetch>"                );

            var aggregateFilter = fetchXml.Descendants("filter").First();

            aggregateFilter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));

            var aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));

            return(ids.ToDictionary(id => id, id =>
            {
                var entity = response.Entities.FirstOrDefault(e => e.Id == id);

                if (entity == null)
                {
                    return new Tuple <string, string, string, IRatingInfo>(null, null, null, null);
                }

                var authorName = Localization.LocalizeFullName(entity.GetAttributeAliasedValue <string>("author.firstname"), entity.GetAttributeAliasedValue <string>("author.lastname"));
                var authorUrl = entity.GetAttributeAliasedValue <string>("author.websiteurl");
                var authorEmail = entity.GetAttributeAliasedValue <string>("author.emailaddress1");

                var aggregateResults = aggregateResponse.Entities
                                       .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id);

                var aggregateYesResult = aggregateResponse.Entities
                                         .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id)
                                         .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 1);

                var aggregateNoResult = aggregateResponse.Entities
                                        .Where(e => e.GetAttributeAliasedValue <Guid?>("commentid") == id)
                                        .FirstOrDefault(e => e.GetAttributeAliasedValue <int?>("value") == 0);

                var yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;
                var noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0 : 0;

                var ratingCount = 0;
                var ratingSum = 0;

                foreach (var aggregateResult in aggregateResults)
                {
                    ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue <int?>("ratingcount") ?? 0;
                    ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue <int?>("ratingsum") ?? 0;
                }

                double averageRating;

                if (ratingCount == 0)
                {
                    averageRating = 0;
                }
                else
                {
                    averageRating = ratingSum / (double)ratingCount;
                }

                var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);

                return new Tuple <string, string, string, IRatingInfo>(authorName, authorUrl, authorEmail, ratingInfo);
            }));
        }
Beispiel #39
0
        private async Task<bool> ProcessResponseAndUpdateOffsetAsync(FetchResponse response, Fetch request, int partitionId)
        {
            if (response == null || response.Messages.Count <= 0)
                return false;

            response.HandleResponseErrors(request);

            foreach (var message in response.Messages)
            {
                await Task.Run(() =>
                {
                    _fetchResponseQueue.Add(message, _disposeToken.Token);//this is a block!!!
                }, _disposeToken.Token);

                if (_disposeToken.IsCancellationRequested) return false;
            }

            var nextOffset = response.Messages.Max(x => x.Meta.Offset) + 1;
            _partitionOffsetIndex.AddOrUpdate(partitionId, i => nextOffset, (i, l) => nextOffset);

            return true;
        }
Beispiel #40
0
        public static int FetchBlogPostCount(this OrganizationServiceContext serviceContext, Guid blogId, string tag, bool published = true)
        {
            if (string.IsNullOrWhiteSpace(tag))
            {
                throw new ArgumentException("Value can't be null or whitespace.", "tag");
            }

            var fetchXml = XDocument.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<entity name=""adx_blogpost"">
						<attribute name=""adx_blogpostid"" aggregate=""count"" alias=""count"" />
						<filter type=""and"">
							<condition attribute=""adx_blogid"" operator=""eq"" />
						</filter>
						<filter type=""or"">
							<condition attribute=""adx_published"" operator=""eq"" value=""true"" />						
						</filter>
						<link-entity name=""adx_blogpost_tag"" from=""adx_blogpostid"" to=""adx_blogpostid"">
							<link-entity name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"">
								<filter type=""and"">
									<condition attribute=""adx_name"" operator=""eq"" />
								</filter>
							</link-entity>
						</link-entity>
					</entity>
				</fetch>"                );

            var blogIdAttribute = fetchXml.XPathSelectElement("//condition[@attribute='adx_blogid']");

            if (blogIdAttribute == null)
            {
                throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_blogid filter"));
            }

            blogIdAttribute.SetAttributeValue("value", blogId.ToString());

            if (!published)
            {
                var publishedFilter = fetchXml.XPathSelectElement("//entity/filter[@type='or']");

                if (publishedFilter == null)
                {
                    throw new InvalidOperationException("Unable to select the blog post publishing filter element.");
                }

                publishedFilter.Remove();
            }

            var tagNameCondition = fetchXml.XPathSelectElement("//link-entity[@name='adx_tag']/filter/condition[@attribute='adx_name']");

            if (tagNameCondition == null)
            {
                throw new InvalidOperationException("Unable to select the tag name filter element.");
            }

            tagNameCondition.SetAttributeValue("value", tag);

            var entity = serviceContext.RetrieveSingle(Fetch.Parse(fetchXml.ToString()));

            return((int)entity.GetAttributeValue <AliasedValue>("count").Value);
        }
Beispiel #41
0
        private void FixOffsetOutOfRangeExceptionAsync(Fetch request)
        {
            _metadataQueries.GetTopicOffsetAsync(request.Topic)
                   .ContinueWith(t =>
                   {
                       try
                       {
                           var offsets = t.Result.FirstOrDefault(x => x.PartitionId == request.PartitionId);
                           if (offsets == null) return;

                           if (offsets.Offsets.Min() > request.Offset)
                               SetOffsetPosition(new OffsetPosition(request.PartitionId, offsets.Offsets.Min()));

                           if (offsets.Offsets.Max() < request.Offset)
                               SetOffsetPosition(new OffsetPosition(request.PartitionId, offsets.Offsets.Max()));
                       }
                       catch (Exception ex)
                       {
                           _options.Log.ErrorFormat("Failed to fix the offset out of range exception on topic:{0} partition:{1}.  Polling will continue.  Exception={2}",
                               request.Topic, request.PartitionId, ex);
                       }
                   });
        }
Beispiel #42
0
 public OffsetOutOfRangeException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     bool hasFetch = info.GetByte("HasFetch") == 1;
     if (hasFetch)
     {
         FetchRequest = new Fetch
         {
             MaxBytes = info.GetInt32("MaxBytes"),
             Offset = info.GetInt64("Offset"),
             PartitionId = info.GetInt32("PartitionId"),
             Topic = info.GetString("Topic")
         };
     }
 }