public async void GroupAsyncTest()
        {
            List <DetectResult> detectResult = null;
            GroupResult         groupResult  = null;

            try
            {
                detectResult = await ApiReference.Instance.Face.DetectAsync(faceAPISettingsFixture.TestGroupImageUrl, "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise", true, true);

                if (detectResult.Count > 0)
                {
                    groupResult = await ApiReference.Instance.Face.GroupAsync((from result in detectResult select result.faceId).ToArray());
                }
            }
            catch
            {
                throw;
            }

            Assert.True(groupResult != null);
        }
Example #2
0
        public GroupResult GetAll()
        {
            var groupReslut = new GroupResult();

            using (_context = new GroupsManagementDbEntities())
            {
                try
                {
                    IList <BGroup> groups = _context.Groups.Select(g => new BGroup {
                        GroupId = g.GroupId, Name = g.Name
                    }).ToList();
                    groupReslut.bGroups = groups;
                }
                catch (Exception e)
                {
                    groupReslut.IsValid = false;
                    groupReslut.ErrorMessages.Add(e.Message);
                }
            }
            return(groupReslut);
        }
Example #3
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(value);
            }

            GroupResult groupResult = value as GroupResult;
            SfListView  listview    = parameter as SfListView;

            var items = new List <MusicInfo>(groupResult.Items.ToList <MusicInfo>());

            if ((items.All(listitem => listitem.IsSelected == false)))
            {
                for (int i = 0; i < items.Count(); i++)
                {
                    var item = items[i];
                    (item as MusicInfo).IsSelected = false;
                    listview.SelectedItems.Remove(item);
                }
                return(ImageSource.FromResource("CustomSelection.Images.NotSelected.png"));
            }

            else if ((items.All(listitem => listitem.IsSelected == true)))
            {
                for (int i = 0; i < items.Count(); i++)
                {
                    var item = items[i];
                    (item as MusicInfo).IsSelected = true;
                    listview.SelectedItems.Add(item);
                }

                return(ImageSource.FromResource("CustomSelection.Images.Selected.png"));
            }

            else
            {
                return(ImageSource.FromResource("CustomSelection.Images.Intermediate.png"));
            }
        }
Example #4
0
        public int GetSubResultRows(GroupResult gr)
        {
            DataTable dt = this.ExControl.GetDataSource();

            if (dt == null)
            {
                return(0);
            }

            int count = 0;

            if (gr.SubGroupInfo == null)
            {
                return(count);
            }

            if (gr.SubGroupInfo.GroupResults == null)
            {
                return(count);
            }

            string field = (gr.SubGroupInfo as FieldGroupInfo).GroupByField;

            if (field == null || field == string.Empty)
            {
                return(count);
            }

            foreach (GroupResult groupResult in gr.SubGroupInfo.GroupResults)
            {
                if (groupResult.GroupValue == null || groupResult.GroupValue.ToString() == string.Empty)
                {
                    continue;
                }

                count += groupResult.RowIndicators.Count;
            }

            return(count);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var         listView    = parameter as SfListView;
            var         itemData    = value as Contacts;
            object      key         = null;
            GroupResult actualGroup = null;
            var         descriptor  = listView.DataSource.GroupDescriptors[0];

            if (value == null)
            {
                return(defaultThickness);
            }

            if (itemData == null)
            {
                return(groupBorderThickness);
            }
            else
            {
                key = descriptor.KeySelector(itemData);
                for (int i = 0; i < listView.DataSource.Groups.Count; i++)
                {
                    var group = listView.DataSource.Groups[i];
                    if ((group.Key != null && group.Key.Equals(key)) || group.Key == key)
                    {
                        actualGroup = group;
                        break;
                    }
                }
                var lastItem = actualGroup.GetGroupLastItem();

                if (lastItem == itemData)
                {
                    return(lastItemThickness);
                }

                return(defaultThickness);
            }
        }
        private void CancelImageTapped()
        {
            GroupResult group = null;

            for (int i = 0; i < ListView.SelectedItems.Count; i++)
            {
                var item = ListView.SelectedItems[i] as MusicInfo;
                item.IsSelected = false;

                var temp = GetGroup(item);

                if (group != temp)
                {
                    RefreshGroupHeader(temp);
                    group = temp;
                }
            }

            this.ListView.SelectedItems.Clear();
            UpdateSelectionTempate();
            this.ListView.RefreshView();
        }
Example #7
0
        private GroupResult ValidateUserAndGroupInput(GearUser user, string groupName, bool isValidatedAlready = false)
        {
            Arg.NotNull(user, nameof(ValidateUserAndGroupInput));
            if (isValidatedAlready)
            {
                return(GroupResult.Success);
            }
            var userProvided      = user != null || !string.IsNullOrEmpty(user.Id);
            var groupNameProvided = !string.IsNullOrEmpty(groupName);

            if (!userProvided && !groupNameProvided)
            {
                return(GroupResult.Failed(_emptyUserError, _emptyGroupError));
            }

            if (!userProvided)
            {
                return(_emptyUserResult);
            }

            return(!groupNameProvided ? _emptyGroupNameResult : GroupResult.Success);
        }
Example #8
0
        internal static GroupResult ToGroupResult(this MPOGroupResult groupResult)
        {
            var groupingResult = new GroupResult
            {
                Groups = groupResult.Groups.Select((grp, index) => new FaceGroup
                {
                    Title   = $"Face Group #{index + 1}",
                    FaceIds = grp.ToList()
                }).ToList()
            };

            if (groupResult.MesseyGroup?.Length > 0)
            {
                groupingResult.MessyGroup = new FaceGroup
                {
                    Title   = "Messy Group",
                    FaceIds = groupResult.MesseyGroup.ToList()
                };
            }

            return(groupingResult);
        }
        private void CreateDirectoryByGroupResult(string path, GroupResult group, IList <Image> images)
        {
            path = $@"{path}\result";
            var           groupPath      = string.Empty;
            IList <Image> imagesSelected = new List <Image>();

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var i = 0;

            group.Groups.ForEach(item =>
            {
                var groupName = "group" + i;
                groupPath     = $@"{path}\{groupName}";

                if (!Directory.Exists(groupPath))
                {
                    Directory.CreateDirectory(groupPath);
                }

                imagesSelected = SelectRecognizedImages(images, item);
                SaveAllImages(imagesSelected, groupPath);

                i++;
            });


            groupPath = $@"{path}\unknow";
            if (!Directory.Exists(groupPath))
            {
                Directory.CreateDirectory(groupPath);
            }

            imagesSelected = SelectRecognizedImages(images, group.MessyGroup);
            SaveAllImages(imagesSelected, groupPath);
        }
Example #10
0
        private void ListView_GroupExpanding(object sender, GroupExpandCollapseChangingEventArgs e)
        {
            if (e.Groups.Count > 0)
            {
                var group = e.Groups[0];
                if (expandedGroup == null || group.Key != expandedGroup.Key)
                {
                    foreach (var otherGroup in listView.DataSource.Groups)
                    {
                        if (group.Key != otherGroup.Key)
                        {
                            listView.CollapseGroup(otherGroup);
                        }
                    }

                    expandedGroup = group;
                    listView.ExpandGroup(expandedGroup);
                    int index = listView.DataSource.DisplayItems.IndexOf(expandedGroup);
                    listView.LayoutManager.ScrollToRowIndex(index, Syncfusion.ListView.XForms.ScrollToPosition.Center, true);
                }
            }
        }
Example #11
0
        public async Task <GroupResult> GetWithGroupByAsync <T>(IRequestContext context, IList <QueryPhrase> queryPhrases, String groupBy) where T : BaseEntity
        {
            String collectionName = EntityTypeRegistry.GetInstance().GetCollectionName(typeof(T));
            string url            = context.GetPath() + "/" + collectionName + "/groups";

            // Octane group API now return logical name by default as ID field,
            // this parameter change this to return numeric ID.
            var serviceArgs = new Dictionary <string, string>();

            serviceArgs.Add("use_numeric_id", "true");

            string queryString = QueryStringBuilder.BuildQueryString(queryPhrases, null, null, null, null, groupBy, serviceArgs);

            ResponseWrapper response = await rc.ExecuteGetAsync(url, queryString).ConfigureAwait(RestConnector.AwaitContinueOnCapturedContext);

            if (response.Data != null)
            {
                GroupResult result = jsonSerializer.Deserialize <GroupResult>(response.Data);
                return(result);
            }
            return(null);
        }
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            View view            = convertView;
            var  contacttemplate = view as ConctactTemplate;

            if (this[position] is Contacts)
            {
                if (view == null || contacttemplate == null)
                {
                    view = new ConctactTemplate(this.context);
                }

                view.SetBackgroundColor(Color.Transparent);
                (view as ConctactTemplate).UpdateValue(this[position]);
            }
            else if (this[position] is GroupResult)
            {
                GroupResult group = (GroupResult)this[position];
                if (view == null || contacttemplate != null)
                {
                    var textView = new TextView(this.context);
                    textView.SetBackgroundColor(Color.Rgb(217, 217, 217));
                    textView.Gravity  = GravityFlags.CenterVertical;
                    textView.TextSize = 18;
                    textView.SetTypeface(Typeface.DefaultBold, TypefaceStyle.Bold);
                    textView.SetPadding((int)(15 * context.Resources.DisplayMetrics.Density), 0, 0, 0);
                    textView.SetMinimumHeight((int)(40 * context.Resources.DisplayMetrics.Density));
                    textView.Text = group.Key.ToString();
                    view          = textView;
                }
                else
                {
                    (view as TextView).Text = group.Key.ToString();
                }
            }

            return(view);
        }
Example #13
0
        public GroupResult Get(int id)
        {
            GroupResult groupResult = new GroupResult();

            using (_context = new GroupsManagementDbEntities())
            {
                try
                {
                    Group group = _context.Groups.Find(id);
                    groupResult.bGroups.Add(new BGroup()
                    {
                        GroupId = group.GroupId,
                        Name    = group.Name
                    });
                }
                catch (Exception e)
                {
                    groupResult.IsValid = false;
                    groupResult.ErrorMessages.Add(e.Message);
                }
            }
            return(groupResult);
        }
Example #14
0
        public GroupResult GetWithGroupBy <T>(IRequestContext context, IList <QueryPhrase> queryPhrases, String groupBy)
            where T : BaseEntity
        {
            String collectionName = GetCollectionName <T>();
            string url            = context.GetPath() + "/" + collectionName + "/groups";


            String queryString = QueryStringBuilder.BuildQueryString(queryPhrases, null, null, null, null, groupBy);

            if (!String.IsNullOrEmpty(queryString))
            {
                url = url + "?" + queryString;
            }

            ResponseWrapper response = rc.ExecuteGet(url);

            if (response.Data != null)
            {
                GroupResult result = jsonSerializer.Deserialize <GroupResult>(response.Data);
                return(result);
            }
            return(null);
        }
Example #15
0
        private GroupResult GroupSummary(GroupResult groupResult)
        {
            var teamSummaries = groupResult.Group.TeamGroups
                                .Select(tg => tg.Team)
                                .Select(team => new TeamSummary {
                Team = team, Group = groupResult.Group
            })
                                .ToList();

            foreach (var matchResult in groupResult.MatchResults)
            {
                var hostSummary = teamSummaries.Single(s => s.Team.Id == matchResult.Host.Team.Id);
                MatchSummary(hostSummary, matchResult.Host);
                var guestSummary = teamSummaries.Single(s => s.Team.Id == matchResult.Guest.Team.Id);
                MatchSummary(guestSummary, matchResult.Guest);
            }

            teamSummaries = RankByPoints(teamSummaries).ToList();
            teamSummaries = teamSummaries.OrderBy(s => s.Loses).ToList();
            _context.TeamSummaries.AddRange(teamSummaries);
            _context.SaveChanges();
            groupResult.Summaries = teamSummaries;
            return(groupResult);
        }
Example #16
0
        internal static GroupResult ToGroupResult(this Droid.Contract.GroupResult groupResult)
        {
            var typedList = ((JavaList)groupResult.Groups).JavaCast <JavaList <UUID []> > ();

            var groupingResult = new GroupResult
            {
                Groups = typedList.Select((grp, index) => new FaceGroup
                {
                    Title   = $"Face Group #{index + 1}",
                    FaceIds = grp.AsStrings()
                }).ToList()
            };

            if (groupResult.MessyGroup?.Count > 0)
            {
                groupingResult.MessyGroup = new FaceGroup
                {
                    Title   = "Messy Group",
                    FaceIds = groupResult.MessyGroup.Cast <UUID> ().AsStrings()
                };
            }

            return(groupingResult);
        }
Example #17
0
        private static void CheckSubGroup(GroupResult gr, ICollection <string> keyList, StringBuilder csvData)
        {
            keyList.Add(gr.Key.ToString());
            if (gr.SubGroups == null)
            {
                var ftData = gr.Items.Cast <FutureTrendExcelDataHolder>();

                decimal sumForecast      = 0;
                decimal sumNessFleet     = 0;
                decimal sumExpectedFleet = 0;
                foreach (var d in ftData)
                {
                    sumForecast      += d.Forecast;
                    sumNessFleet     += d.NessesaryFleet;
                    sumExpectedFleet += d.ExpectedFleet;
                }

                var str = string.Format("{0},{1},{2}\n",
                                        Math.Round(sumForecast, 0, MidpointRounding.AwayFromZero),
                                        Math.Round(sumNessFleet, 0, MidpointRounding.AwayFromZero),
                                        Math.Round(sumExpectedFleet, 0, MidpointRounding.AwayFromZero));

                var listOfKeys = new StringBuilder();
                foreach (var key in keyList)
                {
                    listOfKeys.Append(key + DELIMITER);
                }
                csvData.Append(listOfKeys + str);
            }
            else
            {
                gr.SubGroups.ToList().ForEach(d => CheckSubGroup(d, keyList, csvData));
            }

            keyList.Remove(gr.Key.ToString());
        }
Example #18
0
        private void MakeSearch(SearchModel model)
        {
            string query = model.SearchText + "~";

            DateTime      datastart = DateTime.Now;
            Directory     directory = FSDirectory.Open(new System.IO.DirectoryInfo(Server.MapPath("~/Data/Index")));
            IndexSearcher searcher  = new IndexSearcher(directory, true);
            Analyzer      analyzer  = new StandardAnalyzer(Version.LUCENE_29);

            List <string> strings = new List <string>();

            foreach (var checkBox in model.CheckBoxes)
            {
                if (checkBox.IsChecked)
                {
                    if (checkBox.SearchType == SearchType.Courses)
                    {
                        //make filtration here...
                        strings.Add("Name");
                        strings.Add("Content");
                    }
                    if (checkBox.SearchType == SearchType.Topics)
                    {
                        //make filtration here...
                        strings.Add("Topic");
                    }
                    if (checkBox.SearchType == SearchType.Users)
                    {
                        //make filtration here...
                        strings.Add("User");
                    }
                    if (checkBox.SearchType == SearchType.Disciplines)
                    {
                        //make filtration here...
                        strings.Add("Discipline");
                    }
                    //make filtration here...
                }
            }

            MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
                Version.LUCENE_29,
                strings.ToArray(),
                //new String[] { "Name", "Content", "Discipline", "User", "Group", "Topic" },
                analyzer
                );

            ScoreDoc[] scoreDocs = searcher.Search(queryParser.Parse(query), 100).scoreDocs;

            Hits hit   = searcher.Search(queryParser.Parse(query));
            int  total = hit.Length();

            List <Discipline>       disciplines123 = _CurriculmService.GetDisciplines(_UserService.GetCurrentUser()).ToList();
            List <Course>           courses123     = _CourseService.GetCourses(_UserService.GetCurrentUser()).ToList();
            List <TopicDescription> topics123      = _CurriculmService.GetTopicsAvailableForUser(_UserService.GetCurrentUser()).ToList();

            //List<Discipline> topics123 = _CurriculmService.GetDisciplinesWithTopicsOwnedByUser(_UserService.GetCurrentUser()).ToList();
            //foreach(Discipline curr in disciplines123){
            //    topics123.InsertRange(topics123.Count - 1, _CurriculmService.GetTopicsByDisciplineId(curr.Id));
            //}

            List <ISearchResult> results = new List <ISearchResult>();
            Stopwatch            sw      = new Stopwatch();

            sw.Start();

            foreach (ScoreDoc doc in scoreDocs)
            {
                ISearchResult result;
                Document      document = searcher.Doc(doc.doc);
                String        type     = document.Get("Type").ToLower();

                switch (type)
                {
                case "node":

                    Node node = new Node();
                    node.Id       = Convert.ToInt32(document.Get("NodeID"));
                    node.Name     = document.Get("Name");
                    node.CourseId = Convert.ToInt32(document.Get("NodeCourseID"));
                    node.IsFolder = Convert.ToBoolean(document.Get("isFolder"));

                    result = new NodeResult(node, _CourseService.GetCourse(node.CourseId).Name, document.Get("Content"), _CourseService.GetCourse(node.CourseId).Updated.ToString());
                    results.Add(result);
                    break;

                case "course":

                    Course course = new Course();
                    course.Id   = Convert.ToInt32(document.Get("CourseID"));
                    course.Name = document.Get("Name");
                    foreach (Course cour in courses123)
                    {
                        if (cour.Id == course.Id)
                        {
                            result = new CourseResult(course, _CourseService.GetCourse(course.Id).Updated.ToString(), _CourseService.GetCourse(course.Id).Owner);
                            results.Add(result);
                            break;
                        }
                    }
                    break;

                case "discipline":

                    Discipline discipline = new Discipline();
                    discipline.Id    = Convert.ToInt32(document.Get("DisciplineID"));
                    discipline.Name  = document.Get("Discipline");
                    discipline.Owner = document.Get("Owner");

                    string str = _CurriculmService.GetDiscipline(discipline.Id).Owner;
                    foreach (Discipline curr in disciplines123)
                    {
                        if (curr.Owner.Equals(discipline.Owner))
                        {
                            result = new DisciplineResult(discipline, _CurriculmService.GetDiscipline(discipline.Id).Updated.ToString());
                            results.Add(result);
                            break;
                        }
                    }
                    break;

                case "user":

                    User user = new User();
                    user.Id   = Guid.Parse(document.Get("UserID"));
                    user.Name = document.Get("User");
                    //user.Roles
                    /*user.RoleId = Convert.ToInt32(document.Get("RoleId"));*/

                    result = new UserResult(user);
                    results.Add(result);
                    break;

                case "group":

                    Group group = new Group();
                    group.Id   = int.Parse(document.Get("GroupID"));
                    group.Name = document.Get("Group");
                    result     = new GroupResult(group);
                    results.Add(result);
                    break;

                case "topic":

                    Topic topic = new Topic();
                    topic.Id   = Convert.ToInt32(document.Get("TopicID"));
                    topic.Name = document.Get("Topic");
                    if (document.Get("CourseRef") == "null")
                    {
                        topic.CourseRef = null;
                    }
                    else
                    {
                        topic.CourseRef = Convert.ToInt32(document.Get("CourseRef"));
                    }

                    foreach (TopicDescription themdesc in topics123)
                    {
                        if (themdesc.Topic.Id == topic.Id)
                        {
                            result = new TopicResult(topic, _CourseService.GetCourse(topic.CourseRef.Value).Name);
                            results.Add(result);
                            break;
                        }
                    }
                    break;

                default:
                    throw new Exception("Unknown result type");
                }
            }
            sw.Stop();

            DateTime dataend = DateTime.Now;

            analyzer.Close();
            searcher.Close();
            directory.Close();

            //ViewData["SearchString"] = query;
            //ViewData["score"] = Math.Abs(dataend.Millisecond - datastart.Millisecond); //sw.ElapsedMilliseconds.ToString();
            //ViewData["total"] = total;


            model.SearchResult = results;

            model.Total = total;
            model.Score = Math.Abs(dataend.Millisecond - datastart.Millisecond);
        }
Example #19
0
        private async Task <GroupResult> CheckGroupsForAuthorizationAsync(string groups)
        {
            // Retrieve storefrontname to use with logging
            string storeFrontName = SF.GetValue(FieldType.SystemProperty, SystemProperty.STOREFRONT_NAME, null);

            // Log what groups we have to check
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "CheckGroupsForAuthorization begin");
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "Groups: " + groups);

            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage($"|----------------------------------------------------------|");
                LogMessage("CheckGroupsForAuthorization begin");
                LogMessage("Groups: " + groups);
            }

            // Setup connection to test authorization
            HttpClient client = new HttpClient();

            client.Timeout     = TimeSpan.FromSeconds(10);
            client.BaseAddress = new Uri(_PROTOCOL + StorefrontAPI.Storefront.GetValue("ModuleField", _SA_DOMAIN, _UNIQUE_NAME) + _PATH + StorefrontAPI.Storefront.GetValue("ModuleField", _SA_STOREFRONT_NAME, _UNIQUE_NAME) + "/");

            // Log the validation uri used
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "Validation URI: " + client.BaseAddress.AbsoluteUri + groups);
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "Try to add accept header");

            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage("Validation URI: " + client.BaseAddress.AbsoluteUri + groups);
                LogMessage("Try to add accept header");
            }

            // Add an Accept header for JSON format.
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Log we have assigned a return data for JSON type
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "assign to return data as JSON");
            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage("assign to return data as JSON");
            }

            var returnData = new GroupResult();

            // Log we saved to return data
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "list data response saved");
            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage("list data response saved");
            }

            // List data response.
            HttpResponseMessage response = await client.GetAsync(groups);

            if (response.IsSuccessStatusCode)
            {
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "response is success status code");
                if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                {
                    LogMessage("response is success status code");
                }

                returnData = await response.Content.ReadAsAsync <GroupResult>();
            }

            // Log completion of method
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, "CheckGroupsForAuthorization end");
            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage("CheckGroupsForAuthorization end");
            }

            return(returnData);
        }
Example #20
0
        private void UserPageInit(object sender, EventArgs e)
        {
            // Setup variables to use in this method
            Page page             = (Page)HttpContext.Current.Handler;
            var  storefrontUrl    = string.Empty;
            var  storefrontUrlTwo = string.Empty;
            var  userID           = SF.GetValue(FieldType.SystemProperty, SystemProperty.LOGGED_ON_USER_ID, null);

            // Retrieve storefrontname to use with logging
            string storeFrontName = SF.GetValue(FieldType.SystemProperty, SystemProperty.STOREFRONT_NAME, null);


            //
            //
            // Check if storefront analytics cookie is != null. If not then check process for previews report cookie.
            //
            //


            // Check to see if we need to add a link button or not
            if (page.Request.Cookies["StorefrontAnalytics"] != null && page.Request.Cookies["StorefrontAnalytics"]["Url"] != null)
            {
                // Log that we have added the link button to the page
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: Link Button Added");

                if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                {
                    LogMessage($"|----------------------------------------------------------|");
                    LogMessage("UserPageInit Method: Link Button Added");
                }

                storefrontUrl = page.Request.Cookies["StorefrontAnalytics"]["Url"];
                AddLinkButton(page.Controls, storefrontUrl);

                // Check if we the second link should be on the page or not
                if ((string)ModuleData[_SA_ADD_LINK_TWO_FLAG] == "true")
                {
                    if (page.Request.Cookies["PreviewsReport"] != null && page.Request.Cookies["PreviewsReport"]["Url"] != null)
                    {
                        // Log that we have added the link button to the page
                        LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                        LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: Link Button Two Added");

                        if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                        {
                            LogMessage($"|----------------------------------------------------------|");
                            LogMessage("UserPageInit Method: Link Button Two Added");
                        }

                        storefrontUrlTwo = page.Request.Cookies["PreviewsReport"]["Url"];
                        AddLinkButtonTwo(page.Controls, storefrontUrlTwo);
                        return;
                    }

                    // Get all groups associated with the retrieved userid
                    var groupsTwo = GetGroupsForUser(userID);

                    // remove unwanted chars
                    groupsTwo = SanitizeGroupString(groupsTwo);

                    // Set groups up correctly
                    var         groupStringsTwo = BreakStringIntoValidParameterLength(groupsTwo);
                    GroupResult validResultTwo  = null;

                    try
                    {
                        foreach (string group in groupStringsTwo)
                        {
                            // blocking call!
                            var groupResultTwo = CheckGroupsForAuthorizationAsync(group).Result;

                            // Log that blocking call is complete
                            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: " + group + " Blocking Call Complete");

                            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                            {
                                LogMessage($"|----------------------------------------------------------|");
                                LogMessage("UserPageInit Method: " + group + " Blocking Call Complete");
                            }

                            // Check if our result is null or empty
                            if (string.IsNullOrEmpty(groupResultTwo.StorefrontUrl))
                            {
                                continue;
                            }

                            validResultTwo = groupResultTwo;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
                        LogMessage($"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
                    }

                    if (validResultTwo == null || string.IsNullOrEmpty(validResultTwo.StorefrontUrl))
                    {
                        return;
                    }

                    page.Response.Cookies["PreviewsReport"]["Url"] = validResultTwo.StorefrontUrl;

                    // set the cookie to expire at the end of the day
                    page.Response.Cookies["PreviewsReport"].Expires = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1).AddSeconds(-1);

                    AddLinkButtonTwo(page.Controls, validResultTwo.StorefrontUrl);

                    // Log that blocking call is complete
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Adding Link Button Two Complete");

                    if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                    {
                        LogMessage($"|----------------------------------------------------------|");
                        LogMessage("UserPageInit Adding Link Button Two Complete");
                    }
                }

                return;
            }


            //
            //
            // Check if previews report cookie is != null. If not then finish process for storefront analytics cookie.
            //
            //

            // Check if we the second link should be on the page or not
            if ((string)ModuleData[_SA_ADD_LINK_TWO_FLAG] == "true")
            {
                // Check to see if we need to add a link button or not
                if (page.Request.Cookies["PreviewsReport"] != null && page.Request.Cookies["PreviewsReport"]["Url"] != null)
                {
                    // Log that we have added the link button to the page
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: Link Two Button Added");

                    if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                    {
                        LogMessage($"|----------------------------------------------------------|");
                        LogMessage("UserPageInit Method: Link Two Button Added");
                    }

                    storefrontUrl = page.Request.Cookies["PreviewsReports"]["Url"];
                    AddLinkButtonTwo(page.Controls, storefrontUrl);

                    // Get all groups associated with the retrieved userid
                    var groupsOne = GetGroupsForUser(userID);

                    // remove unwanted chars
                    groupsOne = SanitizeGroupString(groupsOne);

                    // Set groups up correctly
                    var         groupStringsOne = BreakStringIntoValidParameterLength(groupsOne);
                    GroupResult validResultOne  = null;

                    try
                    {
                        foreach (string group in groupStringsOne)
                        {
                            // blocking call!
                            var groupResultOne = CheckGroupsForAuthorizationAsync(group).Result;

                            // Log that blocking call is complete
                            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: " + group + " Blocking Call Complete");

                            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                            {
                                LogMessage($"|----------------------------------------------------------|");
                                LogMessage("UserPageInit Method: " + group + " Blocking Call Complete");
                            }

                            // Check if our result is null or empty
                            if (string.IsNullOrEmpty(groupResultOne.StorefrontUrl))
                            {
                                continue;
                            }

                            validResultOne = groupResultOne;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
                        LogMessage($"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
                    }

                    if (validResultOne == null || string.IsNullOrEmpty(validResultOne.StorefrontUrl))
                    {
                        return;
                    }

                    page.Response.Cookies["StorefrontAnalytics"]["Url"] = validResultOne.StorefrontUrl;

                    // set the cookie to expire at the end of the day
                    page.Response.Cookies["StorefrontAnalytics"].Expires = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1).AddSeconds(-1);

                    AddLinkButton(page.Controls, validResultOne.StorefrontUrl);

                    // Log that blocking call is complete
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Adding Link Button Complete");

                    if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                    {
                        LogMessage($"|----------------------------------------------------------|");
                        LogMessage("UserPageInit Adding Link Button Complete");
                    }

                    return;
                }
            }

            //
            //
            // Both cookies were null so we need to add both.
            //
            //


            // Get all groups associated with the retrieved userid
            var groups = GetGroupsForUser(userID);

            // remove unwanted chars
            groups = SanitizeGroupString(groups);

            // Set groups up correctly
            var         groupStrings = BreakStringIntoValidParameterLength(groups);
            GroupResult validResult  = null;

            try
            {
                foreach (string group in groupStrings)
                {
                    // blocking call!
                    var groupResult = CheckGroupsForAuthorizationAsync(group).Result;

                    // Log that blocking call is complete
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                    LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Method: " + group + " Blocking Call Complete");

                    if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                    {
                        LogMessage($"|----------------------------------------------------------|");
                        LogMessage("UserPageInit Method: " + group + " Blocking Call Complete");
                    }

                    // Check if our result is null or empty
                    if (string.IsNullOrEmpty(groupResult.StorefrontUrl))
                    {
                        continue;
                    }

                    validResult = groupResult;
                    break;
                }
            }
            catch (Exception ex)
            {
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
                LogMessage($"Source: {ex.Source}\n\rMessage: {ex.Message}\n\rStack Trace: {ex.StackTrace}\n\rInner Exception:{ex.InnerException}");
            }

            if (validResult == null || string.IsNullOrEmpty(validResult.StorefrontUrl))
            {
                return;
            }

            page.Response.Cookies["StorefrontAnalytics"]["Url"] = validResult.StorefrontUrl;

            // set the cookie to expire at the end of the day
            page.Response.Cookies["StorefrontAnalytics"].Expires = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1).AddSeconds(-1);

            AddLinkButton(page.Controls, validResult.StorefrontUrl);

            // Log that blocking call is complete
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
            LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Adding Link Button Complete");

            if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
            {
                LogMessage($"|----------------------------------------------------------|");
                LogMessage("UserPageInit Adding Link Button Complete");
            }

            if ((string)ModuleData[_SA_ADD_LINK_TWO_FLAG] == "true")
            {
                page.Response.Cookies["PreviewsReport"]["Url"] = validResult.StorefrontUrl;

                // set the cookie to expire at the end of the day
                page.Response.Cookies["PreviewsReport"].Expires = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(1).AddSeconds(-1);

                AddLinkButtonTwo(page.Controls, validResult.StorefrontUrl);

                // Log that blocking call is complete
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"|----------------------------------------------------------|");
                LMTF.LogMessagesToFile(storeFrontName, LOG_FILENAME1, LOG_FILENAME2, $"UserPageInit Adding Link Button Two Complete");

                // Check if we the second link should be on the page or not
                if ((string)ModuleData[_SA_DEBUGGING_MODE] == "true")
                {
                    LogMessage($"|----------------------------------------------------------|");
                    LogMessage("UserPageInit Adding Link Button Two Complete");
                }
            }
        }
Example #21
0
		/// <summary>
		/// Sends result of actions connected with groups
		/// </summary>
		/// <param name="client">the client to send to</param>
		/// <param name="resultType">The result type</param>
		/// <param name="resultCode">The <see cref="GroupResult"/> result code</param>
		/// <param name="name">name of player event has happened to</param>
		public static void SendResult(IPacketReceiver client, GroupResult resultCode, uint resultType,
			string name)
		{
			// TODO: add enum for resultType
			using (var packet = new RealmPacketOut(RealmServerOpCode.SMSG_PARTY_COMMAND_RESULT))
			{
				packet.Write(resultType);
				packet.WriteCString(name);
				packet.Write((uint)resultCode);
				packet.Write((uint)0); // 3.3.3, lfg cooldown?

				client.Send(packet);
			}
		}
Example #22
0
		/// <summary>
		/// Sends result of actions connected with groups
		/// </summary>
		/// <param name="client">the client to send to</param>
		/// <param name="resultCode">The <see cref="GroupResult"/> result code</param>
		/// <param name="name">name of player event has happened to</param>
		public static void SendResult(IPacketReceiver client, GroupResult resultCode,
			string name)
		{
			SendResult(client, resultCode, 0, name);
		}
Example #23
0
 /// <summary>Sends result of actions connected with groups</summary>
 /// <param name="client">the client to send to</param>
 /// <param name="resultCode">The <see cref="T:WCell.Constants.GroupResult" /> result code</param>
 /// <param name="name">name of player event has happened to</param>
 public static void SendResult(IPacketReceiver client, GroupResult resultCode, string name)
 {
     SendResult(client, resultCode, 0U, name);
 }
Example #24
0
        public ActionResult Search(String query)
        {
            if (query == "")
            {
                return(RedirectToAction("Index"));
            }

            query = query + "~";

            DateTime      datastart = DateTime.Now;
            Directory     directory = FSDirectory.Open(new System.IO.DirectoryInfo(Server.MapPath("~/Data/Index")));
            IndexSearcher searcher  = new IndexSearcher(directory, true);
            Analyzer      analyzer  = new StandardAnalyzer(Version.LUCENE_29);

            MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
                Version.LUCENE_29,
                new String[] { "Name", "Content", "Curriculum", "User", "Group", "Theme" },
                analyzer
                );


            ScoreDoc[] scoreDocs = searcher.Search(queryParser.Parse(query), 100).scoreDocs;

            Hits hit   = searcher.Search(queryParser.Parse(query));
            int  total = hit.Length();



            List <ISearchResult> results = new List <ISearchResult>();
            Stopwatch            sw      = new Stopwatch();

            sw.Start();
            foreach (ScoreDoc doc in scoreDocs)
            {
                ISearchResult result;
                Document      document = searcher.Doc(doc.doc);
                String        type     = document.Get("Type").ToLower();

                switch (type)
                {
                case "node":
                    Node node = new Node();
                    node.Id       = Convert.ToInt32(document.Get("ID"));
                    node.Name     = document.Get("Name");
                    node.CourseId = Convert.ToInt32(document.Get("CourseID"));
                    node.IsFolder = Convert.ToBoolean(document.Get("isFolder"));

                    result = new NodeResult(node, _CourseService.GetCourse(node.CourseId).Name, document.Get("Content"), _CourseService.GetCourse(node.CourseId).Updated.ToString());

                    break;

                case "course":

                    Course course = new Course();
                    course.Id   = Convert.ToInt32(document.Get("ID"));
                    course.Name = document.Get("Name");

                    result = new CourseResult(course, _CourseService.GetCourse(course.Id).Updated.ToString(), _CourseService.GetCourse(course.Id).Owner);

                    break;

                case "curriculum":

                    Curriculum curriculum = new Curriculum();
                    curriculum.Id   = Convert.ToInt32(document.Get("ID"));
                    curriculum.Name = document.Get("Curriculum");

                    result = new CurriculumResult(curriculum, _CurriculmService.GetCurriculum(curriculum.Id).Updated.ToString());

                    break;

                case "user":

                    User user = new User();
                    user.Id     = Guid.Parse(document.Get("ID"));
                    user.Name   = document.Get("User");
                    user.RoleId = Convert.ToInt32(document.Get("RoleId"));

                    result = new UserResult(user, _UserService.GetRole(user.RoleId).ToString());

                    break;

                case "group":

                    Group group = new Group();
                    group.Id   = int.Parse(document.Get("ID"));
                    group.Name = document.Get("Group");

                    result = new GroupResult(group);

                    break;

                case "theme":

                    Theme theme = new Theme();
                    theme.Id        = Convert.ToInt32(document.Get("ID"));
                    theme.Name      = document.Get("Theme");
                    theme.CourseRef = Convert.ToInt32(document.Get("CourseRef"));

                    result = new ThemeResult(theme, _CourseService.GetCourse(theme.CourseRef).Name);

                    break;

                default:
                    throw new Exception("Unknown result type");
                }

                results.Add(result);
            }
            sw.Stop();

            DateTime dataend = DateTime.Now;

            analyzer.Close();
            searcher.Close();
            directory.Close();

            ViewData["SearchString"] = query;
            ViewData["score"]        = Math.Abs(dataend.Millisecond - datastart.Millisecond); //sw.ElapsedMilliseconds.ToString();
            ViewData["total"]        = total;

            return(View(results));
        }
Example #25
0
 /// <summary>
 /// Sends result of actions connected with groups
 /// </summary>
 /// <param name="client">the client to send to</param>
 /// <param name="resultCode">The <see cref="GroupResult"/> result code</param>
 public static void SendResult(IPacketReceiver client, GroupResultType resultType, GroupResult resultCode)
 {
     SendResult(client, resultCode, resultType, String.Empty);
 }
Example #26
0
        private bool MapValue(GroupResult<PosName> posName, object[] values, Func<object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            var value = values[posName.Key.Pos];
            if (!Equals(value, DBNull.Value))
            {
                pocoColumn.SetValue(instance, converter != null ? converter(value) : value);
                return true;
            }

            if (_mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return false;
        }
Example #27
0
        private static void CheckSubGroup(GroupResult gr, ICollection <string> keyList, StringBuilder csvData)
        {
            keyList.Add(gr.Key.ToString());
            if (gr.SubGroups == null)
            {
                var ftData = gr.Items.Cast <BenchmarkExcelDataHolder>();

                decimal sumOnRent      = 0;
                decimal sumOnRentLy    = 0;
                decimal sumFrozenValue = 0;
                decimal sumWeek1       = 0;
                decimal sumWeek2       = 0;
                decimal sumWeek3       = 0;
                decimal sumWeek4       = 0;
                decimal sumWeek5       = 0;
                decimal sumWeek6       = 0;
                decimal sumWeek7       = 0;
                decimal sumWeek8       = 0;
                decimal sumTopDown     = 0;
                foreach (var d in ftData)
                {
                    sumOnRent      += d.CurrentOnRent;
                    sumOnRentLy    += d.OnRentLastYear;
                    sumFrozenValue += d.FrozenValue;
                    sumWeek1       += d.Week1;
                    sumWeek2       += d.Week2;
                    sumWeek3       += d.Week3;
                    sumWeek4       += d.Week4;
                    sumWeek5       += d.Week5;
                    sumWeek6       += d.Week6;
                    sumWeek7       += d.Week7;
                    sumWeek8       += d.Week8;
                    sumTopDown     += d.TopDown;
                }

                var str = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}\n",
                                        sumOnRent.Round(),
                                        sumOnRentLy.Round(),
                                        sumFrozenValue.Round(),
                                        sumWeek1.Round(),
                                        sumWeek2.Round(),
                                        sumWeek3.Round(),
                                        sumWeek4.Round(),
                                        sumWeek5.Round(),
                                        sumWeek6.Round(),
                                        sumWeek7.Round(),
                                        sumWeek8.Round(),
                                        sumTopDown.Round());

                var listOfKeys = new StringBuilder();
                foreach (var key in keyList)
                {
                    listOfKeys.Append(key + ",");
                }
                csvData.Append(listOfKeys + str);
            }
            else
            {
                gr.SubGroups.ToList().ForEach(d => CheckSubGroup(d, keyList, csvData));
            }

            keyList.Remove(gr.Key.ToString());
        }
Example #28
0
        public List <GroupResult> Search(string connectionString, DateTime start, DateTime end)
        {
            MongoDbWriter mongo = new MongoDbWriter();

            mongo.SetConnectionString(connectionString);

            Stopwatch watch = Stopwatch.StartNew();

            // 从数据库中查询数据
            List <PerformanceInfo> list = mongo.GetList <PerformanceInfo>(x => x.Time >= start && x.Time < end);

            // 记录查询时间
            watch.Stop();
            this.LastQueryTime = watch.Elapsed;


            // 先准备一个字典,用于汇总分析结果
            Dictionary <string, GroupResult> dict = new Dictionary <string, GroupResult>(list.Count);

            foreach (var info in list)
            {
                string key = GetGroupKey(info);

                GroupResult g = null;
                if (dict.TryGetValue(key, out g))
                {
                    g.Count++;
                    g.List.Add(info);
                }
                else
                {
                    g       = new GroupResult();
                    g.Count = 1;
                    g.List  = new List <PerformanceInfo>();
                    g.List.Add(info);

                    if (key.Length > 100 && info.HttpInfo == null)
                    {
                        // 此时KEY是根据SQL来生成的,但是SQL有可能很长,这里就取短一点
                        key = key.Substring(0, 100) + "...";
                    }

                    g.Url     = key;
                    dict[key] = g;
                }
            }


            // 计算平均时间
            foreach (var kvp in dict)
            {
                long sumTime = 0;
                foreach (var info in kvp.Value.List)
                {
                    sumTime += info.ExecuteTime.Ticks;
                }

                kvp.Value.AvgTime = TimeSpan.FromTicks(sumTime / kvp.Value.List.Count);
            }

            return((from x in dict
                    //where x.Value.Count > 5 && x.Value.Url.StartsWith("http://developers.mysoft.com.cn:9090/")
                    select x.Value
                    ).ToList());
        }
Example #29
0
        /// <summary>
        /// Sends result of actions connected with groups
        /// </summary>
        /// <param name="client">the client to send to</param>
        /// <param name="resultType">The result type</param>
        /// <param name="resultCode">The <see cref="GroupResult"/> result code</param>
        /// <param name="name">name of player event has happened to</param>
        public static void SendResult(IPacketReceiver client, GroupResult resultCode, GroupResultType resultType,
            string name)
        {
            using (var packet = new RealmPacketOut(RealmServerOpCode.SMSG_PARTY_COMMAND_RESULT, 4 + name.Length + 4 + 4))
            {
                packet.Write((uint)resultType);
                packet.WriteCString(name);
                packet.Write((uint)resultCode);
                packet.Write((uint)0); // 3.3.3, lfg cooldown?

                client.Send(packet);
            }
        }
Example #30
0
        private IEnumerable<MapPlan> BuildMapPlans(GroupResult<PosName> groupedName, DbDataReader dataReader, PocoData pocoData, List<PocoMember> pocoMembers)
        {
            // find pocomember by property name
            var pocoMember = pocoMembers.FirstOrDefault(x => IsEqual(groupedName.Item, x.Name));

            if (pocoMember == null)
            {
                yield break;
            }

            if (groupedName.SubItems.Any())
            {
                var memberInfoType = pocoMember.MemberInfoData.MemberType;
                if (memberInfoType.IsAClass() || pocoMember.IsDynamic)
                {
                    var children = PocoDataBuilder.IsDictionaryType(memberInfoType)
                        ? CreateDynamicDictionaryPocoMembers(groupedName.SubItems, pocoData)
                        : pocoMember.PocoMemberChildren;

                    var subPlans = groupedName.SubItems.SelectMany(x => BuildMapPlans(x, dataReader, pocoData, children)).ToArray();

                    yield return (reader, instance) =>
                    {
                        var newObject = pocoMember.IsList ? pocoMember.Create(dataReader) : (pocoMember.GetValue(instance) ?? pocoMember.Create(dataReader));

                        var shouldSetNestedObject = false;
                        foreach (var subPlan in subPlans)
                        {
                            shouldSetNestedObject |= subPlan(reader, newObject);
                        }

                        if (shouldSetNestedObject)
                        {
                            if (pocoMember.IsList)
                            {
                                var list = pocoMember.CreateList();
                                list.Add(newObject);
                                newObject = list;
                            }

                            pocoMember.SetValue(instance, newObject);
                            return true;
                        }
                        return false;
                    };
                }
            }
            else
            {
                var destType = pocoMember.MemberInfoData.MemberType;
                var defaultValue = MappingHelper.GetDefault(destType);
                var converter = GetConverter(pocoData, pocoMember.PocoColumn, dataReader.GetFieldType(groupedName.Key.Pos), destType);
                yield return (reader, instance) => MapValue(groupedName, reader, converter, instance, pocoMember.PocoColumn, defaultValue);
            }
        }
Example #31
0
        public void GetNotDoneDefectsAssinedToReleaseTest()
        {
            Phase PHASE_CLOSED = TestHelper.GetPhaseForEntityByLogicalName(entityService, workspaceContext, WorkItem.SUBTYPE_DEFECT, "phase.defect.closed");

            Defect  defect1 = CreateDefect();
            Defect  defect2 = CreateDefect(PHASE_CLOSED);
            Defect  defect3 = CreateDefect();
            Defect  defect4 = CreateDefect();
            Release release = ReleaseTests.CreateRelease();

            //assign defect to release
            Defect defectForUpdate1 = new Defect(defect1.Id);

            defectForUpdate1.Release = release;
            Defect defectForUpdate2 = new Defect(defect2.Id);

            defectForUpdate2.Release = release;
            Defect defectForUpdate3 = new Defect(defect3.Id);

            defectForUpdate3.Release  = release;
            defectForUpdate3.Severity = getSeverityCritical();

            Defect defectForUpdate4 = new Defect(defect4.Id);

            defectForUpdate4.Release = release;


            EntityList <Defect> listForUpdate = new EntityList <Defect>();

            listForUpdate.data.AddRange(new Defect[] { defectForUpdate1, defectForUpdate2, defectForUpdate3, defectForUpdate4 });

            EntityListResult <Defect> updated = entityService.UpdateEntities <Defect>(workspaceContext, listForUpdate);

            Assert.AreEqual <int?>(4, updated.total_count);

            //Fetch all defects that assigned to release and still not done
            //Fetch defects as work-items
            List <QueryPhrase> queries      = new List <QueryPhrase>();
            LogicalQueryPhrase subtypeQuery = new LogicalQueryPhrase(WorkItem.SUBTYPE_FIELD, WorkItem.SUBTYPE_DEFECT);

            queries.Add(subtypeQuery);

            //condition of release
            QueryPhrase releaseIdPhrase = new LogicalQueryPhrase(WorkItem.ID_FIELD, release.Id);
            QueryPhrase byReleasePhrase = new CrossQueryPhrase(WorkItem.RELEASE_FIELD, releaseIdPhrase);

            queries.Add(byReleasePhrase);

            //There are several phased in "Done" metaphase - there are we are doing condition on metaphase and not on phase
            //condition by metaphase (parent of phase)
            LogicalQueryPhrase  donePhaseNamePhrase = new LogicalQueryPhrase(Metaphase.LOGICAL_NAME_FIELD, "metaphase.work_item.done");
            NegativeQueryPhrase notDonePhrase       = new NegativeQueryPhrase(donePhaseNamePhrase);
            CrossQueryPhrase    phaseIdPhrase       = new CrossQueryPhrase("metaphase", notDonePhrase);
            CrossQueryPhrase    byPhasePhrase       = new CrossQueryPhrase(WorkItem.PHASE_FIELD, phaseIdPhrase);

            queries.Add(byPhasePhrase);

            EntityListResult <WorkItem> entitiesResult = entityService.Get <WorkItem>(workspaceContext, queries, null);

            Assert.AreEqual <int>(3, entitiesResult.total_count.Value);
            Assert.IsTrue(entitiesResult.data[0].Id == defect1.Id || entitiesResult.data[0].Id == defect3.Id || entitiesResult.data[0].Id == defect4.Id);
            Assert.IsTrue(entitiesResult.data[1].Id == defect1.Id || entitiesResult.data[1].Id == defect3.Id || entitiesResult.data[1].Id == defect4.Id);
            Assert.IsTrue(entitiesResult.data[2].Id == defect1.Id || entitiesResult.data[2].Id == defect3.Id || entitiesResult.data[2].Id == defect4.Id);


            //check group by
            GroupResult groupResult = entityService.GetWithGroupBy <WorkItem>(workspaceContext, queries, "severity");

            Assert.AreEqual(2, groupResult.groupsTotalCount);
            Group group1 = groupResult.groups[0];
            Group group2 = groupResult.groups[1];

            if (group1.count == 1)
            {
                Group temp = group1;
                group1 = group2;
                group2 = temp;
            }

            Assert.AreEqual <int>(2, group1.count);
            Assert.AreEqual <String>("list_node.severity.high", group1.value.logical_name);
            Assert.AreEqual <int>(1, group2.count);
            Assert.AreEqual <String>("list_node.severity.urgent", group2.value.logical_name);
        }
Example #32
0
 private string GetSheetName(GroupResult gr, PersonResult pr)
 {
     string baseName = gr.TblGroup.GroupName + " " + pr.TblPerson.PersonName;
     string name = baseName;
     if (_sheetNameDict.ContainsKey(baseName))
     {
         _sheetNameDict[baseName]++;
         name = baseName + _sheetNameDict[baseName];
     }
     else
     {
         _sheetNameDict[baseName] = 0;
     }
     return name;
 }
Example #33
0
 /// <summary>
 /// Sends result of actions connected with groups
 /// </summary>
 /// <param name="client">the client to send to</param>
 /// <param name="resultCode">The <see cref="GroupResult"/> result code</param>
 public static void SendResult(IPacketReceiver client, GroupResult resultCode)
 {
     Group.SendResult(client, resultCode, 0, String.Empty);
 }
        private void SetRowsValue(ref int i_Row, ref int i_Col, GroupInfo i_GroupInfo)
        {
            int m_OriginalStartCol = i_Col;

            int m_Rows = i_GroupInfo.GetGroupedRows();

            if (i_GroupInfo.GroupResults != null)
            {            //if not section group , sort group result
                if (!(i_GroupInfo is SectionGroupInfo))
                {
                    i_GroupInfo.GroupResults.Sort(i_GroupInfo.Sorting, i_GroupInfo.SortingBy);
                }
            }

            for (int m_row = 0; m_row < m_Rows; m_row++)
            {
                GroupResult m_GroupResult = i_GroupInfo.GroupResults[m_row];

                #region set summaryies
                if (i_GroupInfo.FollowSummaries)
                {
                    if (m_GroupResult.Summaries != null)
                    {
                        foreach (GroupSummary m_Summary in m_GroupResult.Summaries)
                        {
                            //if group have click event , summaries also need.
                            if (m_GroupResult.ClickEvent == ClickEvents.PlayVideo)
                            {
                                WebbTableCellHelper.SetCellValueWithClickEvent(this.PrintingTable, i_Row, i_Col, m_Summary); //03-10-2008@Scott
                            }
                            else
                            {
                                WebbTableCellHelper.SetCellValue(this.PrintingTable, i_Row, i_Col, m_Summary);
                            }

                            i_Col++;
                        }
                    }
                }
                #endregion

                //Set grouped value
                #region set grouped value
                if (m_GroupResult.ClickEvent == ClickEvents.PlayVideo)
                {
                    WebbTableCellHelper.SetCellValueWithClickEvent(this.PrintingTable, i_Row, i_Col, m_GroupResult.GroupValue, FormatTypes.String, m_GroupResult.RowIndicators);
                }
                else
                {
                    WebbTableCellHelper.SetCellValue(this.PrintingTable, i_Row, i_Col, m_GroupResult.GroupValue, FormatTypes.String);
                }

                this.ColumnStyleRows.GroupColumns.Add(i_Col);
                #endregion

                //Merge cells for section row
                #region Merge cell for section row
                if (i_GroupInfo.DistinctValues)
                {
                    this.PrintingTable.MergeCells(i_Row, i_Row, i_Col, this.PrintingTable.GetColumns() - 1);

                    this.SectionRows.Add(i_Row);

                    i_Row++;
                }
                #endregion

                //useless
                #region set header for one value per page
                if (i_GroupInfo == this._RootGroupInfo && this.OneValuePerPage && this.HaveHeader)
                {                //add break row indicators for page break
                    this.BreakRows.Add(i_Row);

                    int nHeaderStart = i_Row, nHeaderCount = 0;

                    this.SetHeaderValue(ref i_Row);

                    nHeaderCount = i_Row - nHeaderStart;

                    this.SetHeaderRows(nHeaderStart, nHeaderCount);
                }
                #endregion

                #region set summaryies
                if (i_GroupInfo.FollowSummaries)
                {
                }
                else
                {
                    if (m_GroupResult.Summaries != null)
                    {
                        foreach (GroupSummary m_Summary in m_GroupResult.Summaries)
                        {
                            i_Col++;

                            //if group have click event , summaries also need.
                            if (m_GroupResult.ClickEvent == ClickEvents.PlayVideo)
                            {
                                WebbTableCellHelper.SetCellValueWithClickEvent(this.PrintingTable, i_Row, i_Col, m_Summary); //03-10-2008@Scott
                            }
                            else
                            {
                                WebbTableCellHelper.SetCellValue(this.PrintingTable, i_Row, i_Col, m_Summary);
                            }
                        }
                    }
                }
                #endregion

                #region Set sub rows
                if (m_GroupResult.SubGroupInfos.Count > 0)
                {
                    int m_StartRow = i_Row;

                    int maxRow = 0;

                    bool bFirstIn = true;                       //06-23-2008@Scott

                    foreach (GroupInfo groupInfo in m_GroupResult.SubGroupInfos)
                    {
                        if (!i_GroupInfo.DistinctValues || !bFirstIn)   //06-23-2008@Scott
                        {
                            if (bFirstIn)
                            {
                                bFirstIn = false;                                       //06-23-2008@Scott
                            }
                            i_Col++;
                        }

                        this.SetRowsValue(ref i_Row, ref i_Col, groupInfo);

                        maxRow = Math.Max(maxRow, i_Row);

                        i_Row = m_StartRow;
                    }
                    if (maxRow > m_StartRow)
                    {
                        maxRow--;
                    }
                    else if (i_GroupInfo.DistinctValues)
                    {
                        maxRow--;
                    }
                    i_Row = maxRow;
                }

                if (this.AcrossPage)
                {
                    i_Col++;                            //06-27-2008@Scott
                }
                else
                {
                    i_Row++;

                    if (m_row < m_Rows - 1)
                    {
                        i_Col = m_OriginalStartCol;
                    }
                }
                #endregion
            }

            #region Set total row
//			if(i_GroupInfo.AddTotal&&i_GroupInfo.TotalSummaries!=null)
//			{
//				i_Col = m_OriginalStartCol;
//
//				if(i_GroupInfo.FollowSummaries)
//				{
//					i_Col--;
//				}
//				else
//				{
//					SetCellValue(i_Row,i_Col,i_GroupInfo.TotalTitle,FormatTypes.String);
//				}
//
//				Int32Collection totalIndicators = (i_GroupInfo as FieldGroupInfo).GetTotalIndicators(i_GroupInfo);
//
//				foreach(GroupSummary m_TotalSummary in i_GroupInfo.TotalSummaries)
//				{
//					i_Col++;
//
//					//04-24-2008@Scott
//					while(this.ColumnStyleRows.GroupColumns.Contains(i_Col))
//					{
//						i_Col++;
//					}
//
//					//05-08-2008@Scott
//					switch(m_TotalSummary.SummaryType)
//					{
//						case SummaryTypes.RelatedPercent:
//						case SummaryTypes.GroupPercent:
//							if(m_TotalSummary.Filter.Count == 0) continue;
//							break;
//						case SummaryTypes.FreqAndPercent:
//						case SummaryTypes.FreqAndRelatedPercent:
//							continue;
//						default:
//							break;
//					}
//
//					if(i_GroupInfo.ClickEvent == ClickEvents.PlayVideo)
//					{
//
//						WebbTableCellHelper.SetCellValueWithClickEvent(i_Row,i_Col,m_TotalSummary);
//					}
//					else
//					{
//						WebbTableCellHelper.SetCellValue(i_Row,i_Col,m_TotalSummary);
//					}
//				}
//
//				this.TotalRows.Add(i_Row);
//
//				i_Row++;
//			}
            #endregion
        }
Example #35
0
 /// <summary>Sends result of actions connected with groups</summary>
 /// <param name="client">the client to send to</param>
 /// <param name="resultCode">The <see cref="T:WCell.Constants.GroupResult" /> result code</param>
 public static void SendResult(IPacketReceiver client, GroupResult resultCode)
 {
     Group.SendResult(client, resultCode, 0U, string.Empty);
 }
        /// <summary>
        /// caculate total rows grouped
        /// </summary>
        /// <param name="i_GroupInfo"></param>
        /// <param name="i_value">must be zero</param>
        private void GetSubRows(GroupInfo i_GroupInfo, ref int i_value)
        {
            int m_TopGroups = i_GroupInfo.GetGroupedRows();

            if (i_value > 0 && m_TopGroups > 0)
            {
                i_value--;                              //-----------------------------------------------
                //|parent group result1	|	child group result1	|	//truncate this row
                //-----------------------------------------------
                //|						|	child group result2	|
                //-----------------------------------------------
                //|						|	...					|
                //-----------------------------------------------

                if (i_GroupInfo.ParentGroupResult != null && i_GroupInfo.ParentGroupResult.ParentGroupInfo != null)
                {
                    if (i_GroupInfo.ParentGroupResult.ParentGroupInfo.DistinctValues)
                    {
                        i_value++;                              //-----------------------------------------------
                        //|parent group result1	|						|	//add this row
                        //-----------------------------------------------
                        //|						|	child group result1	|
                        //-----------------------------------------------
                        //|						|	child group result2	|
                        //-----------------------------------------------
                        //|						|	...					|
                        //-----------------------------------------------
                    }
                }
            }

            if (i_GroupInfo != null && i_GroupInfo.SubGroupInfos.Count == 0)                    //calculate leaf group rows
            {
                if (i_GroupInfo.DistinctValues)
                {
                    i_value += m_TopGroups;                     //???
                }
            }

            if (i_GroupInfo.AddTotal)
            {
                i_value++;                      //calculate total row
            }
            i_value += m_TopGroups;             //calculate grouped result rows

            if (i_GroupInfo.GroupResults != null)
            {
                for (int m_index = 0; m_index < m_TopGroups /*Math.Min(m_TopGroups,i_GroupInfo.GroupResults.Count)*/; m_index++)
                {
                    GroupResult m_Result = i_GroupInfo.GroupResults[m_index];

                    int tempValue = i_value, maxValue = 0;

                    foreach (GroupInfo groupInfo in m_Result.SubGroupInfos)
                    {
                        GetSubRows(groupInfo, ref tempValue);

                        maxValue = Math.Max(maxValue, tempValue);

                        tempValue = i_value;
                    }
                    i_value = Math.Max(i_value, maxValue);
                }
            }
        }
Example #37
0
        private bool MapValue(GroupResult<PosName> posName, DbDataReader reader, Func<object, object> converter, object instance, PocoColumn pocoColumn, object defaultValue)
        {
            if (!reader.IsDBNull(posName.Key.Pos))
            {
                var value = converter != null ? converter(reader.GetValue(posName.Key.Pos)) : reader.GetValue(posName.Key.Pos);
                pocoColumn.SetValue(instance, value);
                return true;
            }

            if (_mappingOntoExistingInstance && defaultValue == null)
            {
                pocoColumn.SetValue(instance, null);
            }

            return false;
        }
Example #38
0
        public static void getReleaseMailReport(Release release, GroupResult groupResult, GroupResult usGroupResult)
        {
            MailItem mailItem = OutlookUtils.AddMailItem();

            mailItem.Subject    = "Release Status: #" + release.Id + " - " + release.Name + " (" + release.StartDate.ToShortDateString() + " - " + release.EndDate.ToShortDateString() + ")";
            mailItem.BodyFormat = OlBodyFormat.olFormatHTML;
            String htmlBody = getHtmlTemplate();

            htmlBody = htmlBody.Replace("@releasename", (release.Name + " (" + release.StartDate.ToShortDateString() + " - " + release.EndDate.ToShortDateString() + ")"));
            htmlBody = htmlBody.Replace("@numofsprints", release.NumOfSprints.ToString());

            int totatDefects             = 0;
            int maxWidth                 = 100;
            int maxVal                   = 1;
            Dictionary <string, int> map = new Dictionary <string, int>();

            map.Add("list_node.severity.urgent", 0);
            map.Add("list_node.severity.very_high", 0);
            map.Add("list_node.severity.high", 0);
            map.Add("list_node.severity.medium", 0);
            map.Add("list_node.severity.low", 0);
            foreach (Group group in groupResult.groups)
            {
                map[group.value.logical_name] = group.count;
                maxVal        = (maxVal < group.count ? group.count : maxVal);
                totatDefects += group.count;
            }
            htmlBody = htmlBody.Replace("@defecttotal", totatDefects.ToString());
            int urgentVal = ((int)(map["list_node.severity.urgent"] * maxWidth / maxVal));

            htmlBody = htmlBody.Replace("@urgentwidth", urgentVal.ToString());
            htmlBody = htmlBody.Replace("@urgentcol", ((urgentVal == 0) ? "none" : "red"));
            htmlBody = htmlBody.Replace("@urgentval", (map["list_node.severity.urgent"]).ToString());

            int veryhighVal = ((int)(map["list_node.severity.very_high"] * maxWidth / maxVal));

            htmlBody = htmlBody.Replace("@veryhighwidth", veryhighVal.ToString());
            htmlBody = htmlBody.Replace("@veryhighcol", ((veryhighVal == 0) ? "none" : "#D4522F"));
            htmlBody = htmlBody.Replace("@veryhighval", (map["list_node.severity.very_high"]).ToString());

            int highVal = ((int)(map["list_node.severity.high"] * maxWidth / maxVal));

            htmlBody = htmlBody.Replace("@highwidth", highVal.ToString());
            htmlBody = htmlBody.Replace("@highcol", ((highVal == 0) ? "none" : "#D97934"));
            htmlBody = htmlBody.Replace("@highval", (map["list_node.severity.high"]).ToString());

            int mediumVal = ((int)(map["list_node.severity.medium"] * maxWidth / maxVal));

            htmlBody = htmlBody.Replace("@mediumwidth", mediumVal.ToString());
            htmlBody = htmlBody.Replace("@mediumcol", ((mediumVal == 0) ? "none" : "#EDAE66"));
            htmlBody = htmlBody.Replace("@mediumval", (map["list_node.severity.medium"]).ToString());

            int lowVal = ((int)(map["list_node.severity.low"] * maxWidth / maxVal));

            htmlBody = htmlBody.Replace("@lowwidth", lowVal.ToString());
            htmlBody = htmlBody.Replace("@lowcol", ((lowVal == 0) ? "none" : "#E3CB44"));
            htmlBody = htmlBody.Replace("@lowval", (map["list_node.severity.low"]).ToString());

            StringBuilder storiesStrBuilder = new StringBuilder(" (");
            int           totalStories      = 0;
            bool          isFirst           = true;

            foreach (Group group in usGroupResult.groups)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    storiesStrBuilder.Append(",  ");
                }
                storiesStrBuilder.Append(group.value.name + ": " + group.count);
                totalStories += group.count;
            }
            storiesStrBuilder.Append(")");
            htmlBody          = htmlBody.Replace("@userstoriestotal", totalStories.ToString() + storiesStrBuilder.ToString());
            mailItem.HTMLBody = htmlBody;
            mailItem.Display();
        }