示例#1
0
    private void FillDDls()
    {
        ddlMaterial.Items.Clear();
        MaterialCollection materials = Material.Utils.GetMaterialsByCaseID(caseID);

        ddlMaterial.Items.Add(new ListItem(Resources.DeliveryPlanTexts.Choose, "-1"));
        foreach (var item in materials)
        {
            ddlMaterial.Items.Add(new ListItem(item.Title, item.ID.ToString()));
        }

        PartCollection parts = Part.Utils.GetPartsByCaseID(caseID);

        ddlPart.Items.Add(new ListItem(Resources.DeliveryPlanTexts.Choose, "-1"));
        foreach (var item in parts)
        {
            ddlPart.Items.Add(new ListItem(item.Title, item.ID.ToString()));
        }

        ActivityCollection activities = Activity.Utils.GetActitvitiesByCaseID(caseID);

        ddlActivity.Items.Add(new ListItem(Resources.DeliveryPlanTexts.Choose, "-1"));
        foreach (var item in activities)
        {
            Contract contract = new Contract(item.ContractID);
            ListItem listItem = new ListItem(item.Title, item.ID.ToString());
            listItem.Attributes["data-optiongroup"] = contract.Title;
            ddlActivity.Items.Add(listItem);
        }
    }
        protected internal override void AddChild(WorkflowMarkupSerializationManager serializationManager, object obj, object childObj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (childObj == null)
            {
                throw new ArgumentNullException("childObj");
            }
            ActivityCollection activitys = obj as ActivityCollection;

            if (activitys == null)
            {
                throw new ArgumentException(SR.GetString("Error_SerializerTypeMismatch", new object[] { typeof(ActivityCollection).FullName }), "obj");
            }
            if (!(childObj is Activity))
            {
                throw new InvalidOperationException(SR.GetString("Error_ActivityCollectionSerializer", new object[] { childObj.GetType().FullName }));
            }
            CompositeActivity owner = activitys.Owner as CompositeActivity;

            if (owner != null)
            {
                if (Helpers.IsCustomActivity(owner))
                {
                    throw new InvalidOperationException(SR.GetString("Error_CanNotAddActivityInBlackBoxActivity"));
                }
                base.AddChild(serializationManager, obj, childObj);
            }
        }
示例#3
0
        public async Task <HttpResponseMessage> DeleteActivityCollection(int id)
        {
            ActivityCollection collection = await db.ActivityCollections.FindAsync(id);

            if (collection == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid Id"));
            }

            ApplicationUser thisUser = await GetUser();

            if (thisUser == null || !thisUser.Trusted && collection.Author.Id != thisUser.Id)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Access denied"));
            }

            // Just add a 'deleted' flag so it doesn't show up anywhere,
            // in case users have downloaded + cached it offline
            collection.SoftDeleted = true;

            await db.SaveChangesAsync();

            await MakeLog(new Dictionary <string, string>() { { "id", id.ToString() } });

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
 public CompositeActivity(string name) : base(name)
 {
     this.activities = new ActivityCollection(this);
     this.activities.ListChanging += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnListChangingEventHandler);
     this.activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnListChangedEventHandler);
     base.SetValue(CanModifyActivitiesProperty, false);
 }
        protected internal override IList GetChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            ActivityCollection activityCollection = obj as ActivityCollection;

            if (activityCollection == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_SerializerTypeMismatch, typeof(ActivityCollection).FullName), "obj");
            }

            CompositeActivity compositeActivity = activityCollection.Owner as CompositeActivity;

            if (compositeActivity != null && Helpers.IsCustomActivity(compositeActivity))
            {
                return(null);
            }
            else
            {
                return(base.GetChildren(serializationManager, obj));
            }
        }
示例#6
0
        public async virtual Task <ActionResult> Index()
        {
            var allBadges = await BadgeCollection.GetAllBadgesByTypeAsync(BadgeType.Unset);

            var allEarnedBadges = await EarnedBadgeCollection.GetAllBadgesForUserByTypeAsync(AuthenticatedUser.EmployeeId, BadgeType.Unset);

            var allActivities = await ActivityCollection.GetAllActivitiesAsync(true);

            var corporateBadges       = allBadges.Where(b => b.Type == BadgeType.Corporate);
            var communityBadges       = allBadges.Where(b => b.Type == BadgeType.Community);
            var earnedCorporateBadges = allEarnedBadges.Where(b => b.Type == BadgeType.Corporate);
            var earnedCommunityBadges = allEarnedBadges.Where(b => b.Type == BadgeType.Community);

            var sortedCorporateBadges = corporateBadges.OrderByDescending(b => b.BadgePriority);
            var sortedCommunityBadges = communityBadges.OrderByDescending(b => b.BadgePriority);
            var badgeIndexViewModel   = new BadgeIndexViewModel()
            {
                CorporateBadges       = sortedCorporateBadges,
                CorporateEarnedBadges = earnedCorporateBadges,
                CommunityBadges       = sortedCommunityBadges,
                CommunityEarnedBadges = earnedCommunityBadges,
                SubmittedActivity     = SubmitActivity.CreateActivitySubmission(AuthenticatedUser.EmployeeId),
                AvailableUsers        = await UserCollection.GetAllAvailabileUsersForCurrentUserAsync(),
            };

            badgeIndexViewModel.AllActivities      = allActivities;
            badgeIndexViewModel.PossibleActivities = allActivities.Select(ai => new SelectListItem()
            {
                Text = ai.Name, Value = ai.Id.ToString(CultureInfo.CurrentCulture)
            });

            return(View(badgeIndexViewModel));
        }
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] global::Android.App.Result resultCode, Intent data)
        {
            if (resultCode != Result.Ok || data == null)
            {
                return;
            }

            switch (requestCode)
            {
            case editCollectionIntent:
            {
                ActivityCollection returned = JsonConvert.DeserializeObject <ActivityCollection>(data.GetStringExtra("JSON"));
                if (returned != null)
                {
                    newCollection = returned;
                    adapter.UpdateActivity(returned);
                }
                break;
            }

            case addActivityIntent:
            {
                LearningActivity added = JsonConvert.DeserializeObject <LearningActivity>(data.GetStringExtra("JSON"));
                adapter.Collection.Activities.Add(added);
                adapter.NotifyDataSetChanged();
                break;
            }
            }
        }
示例#8
0
        public ContextActivities Convert(ICollection <ContextActivityEntity> source, ContextActivities destination, ResolutionContext resolutionContext)
        {
            var context = new ContextActivities();

            var grouping = source.GroupBy(x => x.ContextType);

            foreach (var group in grouping)
            {
                var collection = new ActivityCollection();
                switch (group.Key)
                {
                case ContextType.Parent:
                    if (context.Parent == null)
                    {
                        context.Parent = new ActivityCollection();
                    }
                    collection = context.Parent;
                    break;

                case ContextType.Grouping:
                    if (context.Grouping == null)
                    {
                        context.Grouping = new ActivityCollection();
                    }
                    collection = context.Grouping;
                    break;

                case ContextType.Category:
                    if (context.Category == null)
                    {
                        context.Category = new ActivityCollection();
                    }
                    collection = context.Category;
                    break;

                case ContextType.Other:
                    if (context.Other == null)
                    {
                        context.Other = new ActivityCollection();
                    }
                    collection = context.Other;
                    break;

                case ContextType.Invalid:
                default:
                    throw new NotImplementedException();
                }

                foreach (var item in group.AsEnumerable())
                {
                    collection.Add(new Activity()
                    {
                        Id = new Iri(item.Activity.Id)
                    });
                }
            }

            return(context);
        }
        /// <summary>
        /// Load a collection of Prayer Activity for the given person.
        /// </summary>
        /// <param name="ac"></param>
        /// <param name="personID">ID of the person to fetch activity for</param>
        public static void LoadActivityByPersonID(this ActivityCollection ac, int personID)
        {
            SqlDataReader activityByPersonID = new RequestData().GetActivityByPersonID(personID);

            while (activityByPersonID.Read())
            {
                ac.Add(new Activity(activityByPersonID));
            }
            activityByPersonID.Close();
        }
示例#10
0
        private static void ConnectMapContainerToCollections()
        {
            var mapContainers = GetAllInformationObjects(null, io => io is MapContainer).Cast <MapContainer>().ToArray();

            foreach (var mapContainer in mapContainers)
            {
                mapContainer.MarkerSourceActivities = ActivityCollection.CreateDefault();
                mapContainer.MarkerSourceBlogs      = BlogCollection.CreateDefault();
                mapContainer.MarkerSourceLocations  = AddressAndLocationCollection.CreateDefault();
                mapContainer.ReconnectMastersAndCollections(true);
            }
        }
示例#11
0
        public async Task <HttpResponseMessage> PostActivityCollection(ActivityCollection collection)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid LearningActivity"));
            }

            ApplicationUser thisUser = await GetUser();

            if (thisUser == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Please log in"));
            }

            Application thisApp = db.Applications.AsEnumerable().FirstOrDefault();

            collection.Places = await ProcessPlacesInNewContent(collection.Places, thisUser);

            collection.Activities = await ProcessActivities(collection.Activities, thisUser);

            collection.Author      = thisUser;
            collection.CreatedAt   = DateTime.UtcNow;
            collection.Approved    = thisUser.Trusted;
            collection.Application = thisApp;

            bool   createdUnique = false;
            string randStr       = "";

            while (!createdUnique)
            {
                randStr = new string(Enumerable.Repeat(chars, 6)
                                     .Select(s => s[rand.Next(s.Length)]).ToArray());

                createdUnique = !await db.ActivityCollections.AnyAsync(la => la.InviteCode == randStr);
            }

            // ~ 900k possible combinations. If this becomes an issue we're in a good place :)
            collection.InviteCode = randStr;

            ActivityCollection finalAct = db.ActivityCollections.Add(collection);


            string qrCodeUrl    = "qrCodes/" + finalAct.InviteCode + ".png";
            string shareAddress = ServerUtils.GetActivityShareUrl(finalAct.InviteCode);

            finalAct.QRCodeUrl = await GenerateQR(finalAct.InviteCode, shareAddress);

            await db.SaveChangesAsync();

            await MakeLog(new Dictionary <string, string>() { { "id", finalAct.Id.ToString() } });

            return(Request.CreateResponse(HttpStatusCode.OK));;
        }
        /// <summary>
        /// Gets the minimum and optional maximum badge value.
        /// </summary>
        /// <param name="BadgeName">Name of the badge to get the value for.</param>
        /// <returns></returns>
        public async virtual Task <string> MaxAwardValue(string BadgeName)
        {
            var allActivities = await ActivityCollection.GetAllActivitiesAsync(false);

            var activityIds = allActivities.Where(x => x.Name == BadgeName).Select(x => x.Id);
            var allBadges   = await BadgeCollection.GetAllBadgesForActivitiesAsync(activityIds);

            var Badge       = allBadges.Select(x => new { x.Id, x.BadgeAwardValue, x.BadgeAwardValueMax }).FirstOrDefault();
            var valueObject = new { minval = Badge.BadgeAwardValue, maxval = Badge.BadgeAwardValueMax };

            return(Newtonsoft.Json.JsonConvert.SerializeObject(valueObject));;
        }
        public async virtual Task <ActionResult> AddBadge()
        {
            var allActivities = await ActivityCollection.GetAllActivitiesAsync(false);

            var badgeEdit          = BadgeEdit.CreateBadge();
            var badgeEditViewModel = new BadgeEditViewModel(allActivities);

            badgeEditViewModel.Badge          = badgeEdit as BadgeEdit;
            badgeEditViewModel.Badge.Priority = 0;

            return(View(Mvc.BadgeManager.Views.AddBadge, badgeEditViewModel));
        }
示例#14
0
    private void FillDdlWaiveActivities(long caseID)
    {
        ActivityCollection activities = Activity.Utils.GetActitvitiesByCaseID(caseID);

        foreach (var item in activities)
        {
            Contract contract = new Contract(item.ContractID);
            ListItem listItem = new ListItem(item.Title, item.ID.ToString());
            listItem.Attributes["data-optiongroup"] = contract.Title;

            ddlEkstraActivity.Items.Add(listItem);
        }
    }
示例#15
0
        public async virtual Task <ActionResult> SubmitActivityForm()
        {
            var submittedActivity = SubmitActivity.CreateActivitySubmission(AuthenticatedUser.EmployeeId);

            TryUpdateModel(submittedActivity, "SubmittedActivity");
            var activities = await ActivityCollection.GetAllActivitiesAsync(false);

            var badges = await BadgeCollection.GetAllBadgesForActivitiesAsync(activities.Where(x => x.Id == submittedActivity.ActivityId).Select(x => x.Id));

            var badge = badges.Select(x => new { x.Id, x.BadgeAwardValue, x.BadgeAwardValueMax }).FirstOrDefault();

            if (submittedActivity.AwardValue > badge.BadgeAwardValueMax || submittedActivity.AwardValue < badge.BadgeAwardValue)
            {
                ModelState.AddModelError("SubmittedActivity.AwardValue", String.Format("Award Value not within acceptable range. ({0} - {1})", badge.BadgeAwardValue, badge.BadgeAwardValueMax));
            }
            else if (string.IsNullOrWhiteSpace(submittedActivity.EmployeeIds))
            {
                ModelState.AddModelError("SubmittedActivity.EmployeeIds", ApplicationResources.NoEmployeeIdsErrorMsg);
            }
            else
            {
                //Parse the list of employee ids the client form sent us.
                List <int> empIds = submittedActivity.EmployeeIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Convert(delegate(string item, out int result) { return(int.TryParse(item.Trim(), out result)); });

                bool allSaved = true;
                foreach (int empId in empIds)
                {
                    var singleActivity = SubmitActivity.CreateActivitySubmission(empId);
                    singleActivity.ActivityId             = submittedActivity.ActivityId;
                    singleActivity.ActivitySubmissionDate = submittedActivity.ActivitySubmissionDate;
                    singleActivity.Notes      = submittedActivity.Notes;
                    singleActivity.AwardValue = submittedActivity.AwardValue;

                    var singActEdit = await ActivityEdit.GetActivityEditByIdAsync(singleActivity.ActivityId);

                    singleActivity.EntryType = singActEdit.EntryType;
                    if (!await SaveObjectAsync(singleActivity, true))
                    {
                        allSaved = false;
                    }
                }

                if (allSaved)
                {
                    return(RedirectToAction(await Mvc.Activities.Actions.Index()));
                }
            }

            return(await Index());
        }
        private void Adapter_EditCollectionClick(object sender, int e)
        {
            // Edit the collection's basic details
            Intent intent = new Intent(this, typeof(CreateCollectionActivity));

            newCollection = adapter.Collection;
            intent.PutExtra("JSON", JsonConvert.SerializeObject(newCollection, new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                MaxDepth = 6
            }));
            StartActivityForResult(intent, editCollectionIntent);
            intent.Dispose();
        }
		public void TestClearContains ()
		{
			ActivityCollection ac = new ActivityCollection (new ParallelActivity ());
			CodeActivity ca1 = new CodeActivity ();
			CodeActivity ca2 = new CodeActivity ();
			CodeActivity ca3 = new CodeActivity ();
			ac.Add (ca1);
			ac.Add (ca2);
			Assert.AreEqual (true, ac.Contains (ca2), "C2#1");
			Assert.AreEqual (false, ac.Contains (ca3), "C2#2");
			Assert.AreEqual (2, ac.Count, "C2#3");
			ac.Clear ();
			Assert.AreEqual (false, ac.Contains (ca3), "C2#4");
			Assert.AreEqual (0, ac.Count, "C2#5");
		}
示例#18
0
        public void BuildJsonActivityCollectionFile(Stream stream, ActivityCollection collection)
        {
            using (StreamWriter sw = new StreamWriter(stream))
            {
                using (JsonWriter jw = new JsonTextWriter(sw))
                {
                    jw.Formatting = Formatting.Indented;

                    JsonSerializer serializer = new JsonSerializer();

                    serializer.NullValueHandling = NullValueHandling.Ignore;
                    serializer.Serialize(jw, BuildJsonActivityCollection(collection));
                }
            }
        }
示例#19
0
        public ActivityCollectionAdapter(Context context, ActivityCollection thisCollection, Action save, bool editing)
        {
            this.context = context;
            Collection   = thisCollection;
            saveProgress = save;
            editingMode  = editing;

            if (!string.IsNullOrWhiteSpace(thisCollection.ActivityOrder))
            {
                // get the order of activities from the ActivityOrder string
                List <int> idOrder = Array.ConvertAll(thisCollection.ActivityOrder.Split(','), int.Parse).ToList();

                Collection.Activities = Collection.Activities.OrderBy(act => idOrder.IndexOf(act.Id)).ToList();
            }
        }
示例#20
0
        private async Task ContinueToNext()
        {
            if (newCollection == null)
            {
                ApplicationUser currentUser = (await Common.LocalData.Storage.GetDatabaseManager()).CurrentUser;

                newCollection = new ActivityCollection
                {
                    Author = new LimitedApplicationUser()
                    {
                        Id        = currentUser.Id,
                        FirstName = currentUser.FirstName,
                        Surname   = currentUser.Surname
                    },
                    Id         = new Random().Next(),// Temp ID, used locally only
                    Activities = new List <LearningActivity>()
                };
            }

            newCollection.Name        = titleInput.Text;
            newCollection.Description = descInput.Text;

            if (selectedImage != null)
            {
                newCollection.ImageUrl = selectedImage.Path;
            }

            Intent addActivitiesActivity = new Intent(this, typeof(CreateCollectionOverviewActivity));
            string json = JsonConvert.SerializeObject(newCollection, new JsonSerializerSettings
            {
                TypeNameHandling      = TypeNameHandling.Auto,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                MaxDepth = 5
            });

            addActivitiesActivity.PutExtra("JSON", json);

            if (editing)
            {
                SetResult(Result.Ok, addActivitiesActivity);
            }
            else
            {
                StartActivity(addActivitiesActivity);
            }

            Finish();
        }
示例#21
0
        public void TestClearContains()
        {
            ActivityCollection ac  = new ActivityCollection(new ParallelActivity());
            CodeActivity       ca1 = new CodeActivity();
            CodeActivity       ca2 = new CodeActivity();
            CodeActivity       ca3 = new CodeActivity();

            ac.Add(ca1);
            ac.Add(ca2);
            Assert.AreEqual(true, ac.Contains(ca2), "C2#1");
            Assert.AreEqual(false, ac.Contains(ca3), "C2#2");
            Assert.AreEqual(2, ac.Count, "C2#3");
            ac.Clear();
            Assert.AreEqual(false, ac.Contains(ca3), "C2#4");
            Assert.AreEqual(0, ac.Count, "C2#5");
        }
示例#22
0
        public static Task <ServerResponse <string> > UploadCollection(AppDataUpload upload, bool updateExisting = false)
        {
            ActivityCollection collection = JsonConvert.DeserializeObject <ActivityCollection>(upload.JsonData);
            List <FileUpload>  files      = JsonConvert.DeserializeObject <List <FileUpload> >(upload.FilesJson);

            // update the collection's image url if it's had one uploaded
            FileUpload f = files?.Where(fi => fi.LocalFilePath == collection.ImageUrl).FirstOrDefault();

            if (f != null && !string.IsNullOrWhiteSpace(f.RemoteFilePath))
            {
                collection.ImageUrl = f.RemoteFilePath;
            }

            return(updateExisting ? Put <string>(upload.UploadRoute, collection) :
                   Post <string>(upload.UploadRoute, collection));
        }
示例#23
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.CreateNewActivity);

            titleInput     = FindViewById <EditText>(Resource.Id.titleInput);
            descInput      = FindViewById <EditText>(Resource.Id.descInput);
            imageView      = FindViewById <ImageView>(Resource.Id.activityIcon);
            continueButton = FindViewById <Button>(Resource.Id.continueBtn);

            imageView.Click      += ImageView_Click;
            continueButton.Click += ContinueButton_Click;

            FindViewById <TextInputLayout>(Resource.Id.collName_text_input_layout).Hint = GetString(Resource.String.createCollectionNameHint);
            FindViewById <TextInputLayout>(Resource.Id.collDesc_text_input_layout).Hint = GetString(Resource.String.createCollectionDescriptionHint);

            string jsonData = Intent.GetStringExtra("JSON") ?? "";

            newCollection = JsonConvert.DeserializeObject <ActivityCollection>(jsonData, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto
            });

            // load given details in if available
            if (newCollection != null)
            {
                editing         = true;
                titleInput.Text = newCollection.Name;
                descInput.Text  = newCollection.Description;

                if (!string.IsNullOrWhiteSpace(newCollection.ImageUrl))
                {
                    if (newCollection.ImageUrl.StartsWith("upload"))
                    {
                        selectedImage = global::Android.Net.Uri.Parse(newCollection.ImageUrl);
                        ImageService.Instance.LoadUrl(ServerUtils.GetUploadUrl(selectedImage.ToString()))
                        .Transform(new CircleTransformation())
                        .Into(imageView);
                    }
                    else
                    {
                        selectedImage = global::Android.Net.Uri.FromFile(new Java.IO.File(newCollection.ImageUrl));
                        ImageService.Instance.LoadFile(selectedImage.Path).Transform(new CircleTransformation()).Into(imageView);
                    }
                }
            }
        }
		public void TestAddRemove ()
		{
			ActivityCollection ac = new ActivityCollection (new ParallelActivity ());
			CodeActivity ca1 = new CodeActivity ();
			CodeActivity ca2 = new CodeActivity ();
			CodeActivity ca3 = new CodeActivity ();
			ac.Add (ca1);
			Assert.AreEqual (1, ac.Count, "C1#1");
			ac.Add (ca2);
			Assert.AreEqual (2, ac.Count, "C1#2");
			ac.Add (ca3);
			Assert.AreEqual (3, ac.Count, "C1#3");
			ac.Remove (ca2);
			Assert.AreEqual (2, ac.Count, "C1#4");
			ac.RemoveAt (0);
			Assert.AreEqual (1, ac.Count, "C1#5");
			Assert.AreEqual (ca3, ac[0], "C1#6");
		}
示例#25
0
文件: Activity.cs 项目: juinti/juinti
            public static ActivityCollection GetActitvitiesByCaseID(Int64 CaseID)
            {
                ActivityCollection c = new ActivityCollection();

                DataTable dt = Execute.FillDataTable(StoredProcedures.GetActitvitiesByCaseID, new System.Data.SqlClient.SqlParameter("CaseID", CaseID));

                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        Activity o = new Activity();
                        LoadActivityByReader(row, o);
                        c.Add(o);
                    }
                }

                return(c);
            }
示例#26
0
    private void FillDdlPartActivity()
    {
        ActivityCollection activities = Activity.Utils.GetActitvitiesByCaseID(caseID);

        foreach (var activity in activities)
        {
            StructureCollection structures = Structure.Utils.GetStructuresByActivityID(activity.ID);
            foreach (var structure in structures)
            {
                Contract contract = new Contract(activity.ContractID);
                ListItem listItem = new ListItem();
                listItem.Text  = structure.Title;
                listItem.Value = structure.ID.ToString();
                listItem.Attributes["data-optiongroup"] = contract.Title + " - " + activity.Title;
                ddlPartStructure.Items.Add(listItem);
            }
        }
    }
        public virtual async Task <ActionResult> Compare(string userName)
        {
            var leftLeaderboardItem = await LeaderboardItem.GetLeaderboardForUserName(AuthenticatedUser.UserName);

            var rightLeaderboardItem = await LeaderboardItem.GetLeaderboardForUserName(userName);

            var allBadges = await BadgeCollection.GetAllBadgesByTypeAsync(BadgeType.Unset);

            var allActivities = await ActivityCollection.GetAllActivitiesAsync(false);

            var leaderboardCompareViewModel = new LeaderboardCompareViewModel();

            leaderboardCompareViewModel.LeftLeaderboardItem  = leftLeaderboardItem;
            leaderboardCompareViewModel.RightLeaderboardItem = rightLeaderboardItem;
            leaderboardCompareViewModel.AllBadges            = allBadges;
            leaderboardCompareViewModel.AllActivities        = allActivities;

            return(View(leaderboardCompareViewModel));
        }
示例#28
0
        public void TestAddRemove()
        {
            ActivityCollection ac  = new ActivityCollection(new ParallelActivity());
            CodeActivity       ca1 = new CodeActivity();
            CodeActivity       ca2 = new CodeActivity();
            CodeActivity       ca3 = new CodeActivity();

            ac.Add(ca1);
            Assert.AreEqual(1, ac.Count, "C1#1");
            ac.Add(ca2);
            Assert.AreEqual(2, ac.Count, "C1#2");
            ac.Add(ca3);
            Assert.AreEqual(3, ac.Count, "C1#3");
            ac.Remove(ca2);
            Assert.AreEqual(2, ac.Count, "C1#4");
            ac.RemoveAt(0);
            Assert.AreEqual(1, ac.Count, "C1#5");
            Assert.AreEqual(ca3, ac[0], "C1#6");
        }
        public async void SaveProgress()
        {
            newCollection = adapter.Collection;

            // Hide the prompt if the user has added at least 2 activities
            fabPrompt.Visibility =
                (newCollection.Activities != null && newCollection.Activities.Count >= 1)
                    ? ViewStates.Gone : ViewStates.Visible;

            // Don't save changes to uploaded activities until we're ready to submit
            if (editingSubmitted)
            {
                return;
            }

            if (dbManager == null)
            {
                dbManager = await Storage.GetDatabaseManager();
            }

            // Add/update this new activity in the user's inprogress cache
            string cacheJson = dbManager.CurrentUser.LocalCreatedCollectionsJson;
            List <ActivityCollection> inProgress = (string.IsNullOrWhiteSpace(cacheJson)) ?
                                                   new List <ActivityCollection>() :
                                                   JsonConvert.DeserializeObject <List <ActivityCollection> >(cacheJson);

            int existingInd = inProgress.FindIndex((la) => la.Id == newCollection.Id);

            if (existingInd == -1)
            {
                inProgress.Insert(0, newCollection);
            }
            else
            {
                inProgress.RemoveAt(existingInd);
                inProgress.Insert(0, newCollection);
            }

            dbManager.CurrentUser.LocalCreatedCollectionsJson = JsonConvert.SerializeObject(inProgress);
            dbManager.AddUser(dbManager.CurrentUser);
            MainMyCreationsFragment.ForceRefresh = true;
        }
示例#30
0
        public async Task <IHttpActionResult> PutActivityCollection(int id, ActivityCollection collection)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            ActivityCollection existing = db.ActivityCollections.FirstOrDefault(a => a.Id == id);

            if (existing == null)
            {
                return(NotFound());
            }

            ApplicationUser thisUser = await GetUser();

            if (thisUser == null || thisUser.Id != existing.Author.Id)
            {
                return(Unauthorized());
            }

            List <Place> places = await ProcessPlacesInNewContent(collection.Places, thisUser, existing.Places.ToList());

            List <LearningActivity> activities = (await ProcessActivities(collection.Activities, thisUser)).ToList();

            existing.CollectionVersionNumber = collection.CollectionVersionNumber;
            existing.Approved      = thisUser.Trusted;
            existing.CreatedAt     = DateTime.UtcNow;
            existing.Description   = collection.Description;
            existing.ImageUrl      = collection.ImageUrl;
            existing.Name          = collection.Name;
            existing.IsPublic      = collection.IsPublic;
            existing.Places        = places;
            existing.Activities    = activities;
            existing.ActivityOrder = collection.ActivityOrder;

            db.Entry(existing).State = System.Data.Entity.EntityState.Modified;

            await db.SaveChangesAsync();

            return(StatusCode(HttpStatusCode.OK));
        }
示例#31
0
        public static async Task LaunchCollection(ActivityCollection coll, Activity context)
        {
            if (coll == null)
            {
                return;
            }

            if (!IsContentVersionCompatible(coll, context))
            {
                return;
            }

            DatabaseManager db = await GetDbManager().ConfigureAwait(false);

            Dictionary <string, string> properties = new Dictionary <string, string>
            {
                { "UserId", db.CurrentUser.Id },
                { "CollectionId", coll.Id.ToString(CultureInfo.InvariantCulture) }
            };

            Analytics.TrackEvent("MainActivity_LaunchCollection", properties);

            ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(context);

            // Save this activity to the database for showing in the 'recent' feed section
            db.AddContentCache(coll, int.Parse(preferences.GetString("pref_cacheNumber", "4"), CultureInfo.InvariantCulture));

            MainLandingFragment.ForceRefresh = true;

            string json = JsonConvert.SerializeObject(coll, new JsonSerializerSettings
            {
                TypeNameHandling      = TypeNameHandling.Auto,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                MaxDepth = 6
            });

            using (Intent openCollectionIntent = new Intent(context, typeof(CollectionActivityListActivity)))
            {
                openCollectionIntent.PutExtra("JSON", json);
                context.StartActivity(openCollectionIntent);
            }
        }
        public ActivityCollection GetActivities(int year, int month, int day)
        {
            // cSelectDayActivity
            ActivityCollection result = new ActivityCollection();

            // We get input in local time, but we need to query in UTC time ...
            DateTime universalBeginDate = new DateTime(year, month, day).ToUniversalTime();
            DateTime universalEndDate = new DateTime(year, month, day, 23, 59, 59).ToUniversalTime();

            // Do we want a read/write locking mechanism? Now we just lock ...
            lock (this.writeLock)
            {
                SQLiteConnection conn = CreateConnection(this.mFilepath, true);

                try
                {
                    conn.Open();

                    SQLiteCommand cmd = new SQLiteCommand(cSelectDayActivity, conn);

                    cmd.Parameters.Add(new SQLiteParameter("@beginTime", universalBeginDate.Ticks));
                    cmd.Parameters.Add(new SQLiteParameter("@endTime", universalEndDate.Ticks));

                    using (SQLiteDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            long ticks = long.Parse(dr["timestamp"].ToString());
                            DateTime timestamp = new DateTime(ticks);
                            Activity act = new Activity(dr["description"].ToString(), timestamp.ToLocalTime());
                            result.Add(act);
                        }
                    }
                }
                finally
                {
                    conn.Close();
                }
            }

            return result;
        }
示例#33
0
        public async virtual Task <ActionResult> Index()
        {
            var submittedActivities = await SubmittedActivityCollection.GetSubmittedActivitiesByEmployeeIdAsync(AuthenticatedUser.EmployeeId, null, null);

            var activityIndexViewModel = new ActivityIndexViewModel()
            {
                SubmittedActivity = SubmitActivity.CreateActivitySubmission(AuthenticatedUser.EmployeeId),
                AvailableUsers    = await UserCollection.GetAllAvailabileUsersForCurrentUserAsync(),
            };

            var allActivities = await ActivityCollection.GetAllActivitiesAsync(true);

            activityIndexViewModel.PossibleActivities = allActivities.Select(ai => new SelectListItem()
            {
                Text = ai.Name, Value = ai.Id.ToString(CultureInfo.CurrentCulture)
            });
            activityIndexViewModel.PreviousActivities = await SubmittedActivityCollection.GetSubmittedActivitiesByEmployeeIdAsync(AuthenticatedUser.EmployeeId, null, null);

            return(View(Mvc.Activities.Views.Index, activityIndexViewModel));
        }
        public virtual async Task <ActionResult> EditBadge(int id)
        {
            var allActivities = await ActivityCollection.GetAllActivitiesAsync(false);

            var badgeEdit = await BadgeEdit.GetBadgeEditByIdAsync(id);

            if (BusinessRules.HasPermission(AuthorizationActions.EditObject, badgeEdit))
            {
                var badgeEditViewModel = new BadgeEditViewModel(allActivities, badgeEdit.BadgeActivities);
                badgeEditViewModel.Badge = badgeEdit as BadgeEdit;
                if (badgeEditViewModel.Badge.Priority == Int32.MaxValue)
                {
                    badgeEditViewModel.Badge.Priority = 0;
                }

                return(View(Mvc.BadgeManager.Views.EditBadge, badgeEditViewModel));
            }

            return(RedirectToAction(Mvc.Error.AccessDenied()));
        }
 internal static void Update_GroupContainer_Activities(GroupContainer groupContainer, ActivityCollection localCollection, ActivityCollection masterCollection)
 {
     localCollection.CollectionContent = masterCollection.CollectionContent;
     if (localCollection.OrderFilterIDList == null)
         localCollection.OrderFilterIDList = new List<string>();
 }
		public void TestConstructorNullException ()
		{
			ActivityCollection ac = new ActivityCollection (null);
		}
 internal override void FixUpParentChildRelationship(Activity definitionActivity, Activity parentActivity, Hashtable deserializedActivities)
 {
     CompositeActivity activity = definitionActivity as CompositeActivity;
     if (activity == null)
     {
         throw new ArgumentException("definitionActivity");
     }
     base.FixUpParentChildRelationship(definitionActivity, parentActivity, deserializedActivities);
     this.activities = new ActivityCollection(this);
     this.activities.ListChanging += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnListChangingEventHandler);
     this.activities.ListChanged += new EventHandler<ActivityCollectionChangeEventArgs>(this.OnListChangedEventHandler);
     string dottedPath = base.DottedPath;
     int num = 0;
     foreach (Activity activity2 in activity.activities)
     {
         Activity activity3 = (Activity) deserializedActivities[(dottedPath.Length == 0) ? num.ToString(CultureInfo.InvariantCulture) : (dottedPath + "." + num.ToString(CultureInfo.InvariantCulture))];
         this.activities.InnerAdd(activity3);
         activity3.FixUpParentChildRelationship(activity2, this, deserializedActivities);
         num++;
     }
 }
示例#38
0
		public CompositeActivity ()
		{
			activities = new ActivityCollection (this);
			modify_activities = true;
		}
        internal static void Update_MapContainer_MarkerSourceActivities(MapContainer mapContainer, ActivityCollection localCollection, ActivityCollection masterCollection)
        {
            mapContainer.MapMarkers.CollectionContent.RemoveAll(
                marker => marker.MarkerSource == MapMarker.MarkerSourceActivityValue);
            var locationActivities =
                masterCollection.CollectionContent.Select(
                    activity => new {Activity = activity, Locations = activity.LocationCollection.GetIDSelectedArray()});
            Dictionary<string, LocationSpot> locDict = new Dictionary<string, LocationSpot>();
            foreach(var locAct in locationActivities)
            {
                foreach(var location in locAct.Locations)
                {
                    string key = location.Location.GetLocationText();
                    LocationSpot locSpot;
                    locDict.TryGetValue(key, out locSpot);
                    if(locSpot == null)
                    {
                        locSpot = new LocationSpot {LocationText = key, Location = location.Location};
                        locDict.Add(key, locSpot);
                    }
                    locSpot.AddActivity(locAct.Activity);
                }
            }
            List<MapMarker> markers = new List<MapMarker>();
            foreach(var dictItem in locDict)
            {
                var locSpot = dictItem.Value;
                foreach(var catItem in locSpot.CategorizedActivites)
                {
                    MapMarker marker = MapMarker.CreateDefault();
                    marker.Location = locSpot.Location;
                    marker.MarkerSource = MapMarker.MarkerSourceActivityValue;
                    marker.IconUrl = GetIconUrlForCategory(catItem.CategoryName);
                    marker.CategoryName = GetMarkerCategoryName(catItem.CategoryName);
                    //marker.IconUrl = "../oip-additions/oip-assets/oip-images/oip-markers/OIP-marker-meeting.png";
                    marker.LocationText = locSpot.LocationText;
                    marker.SetLocationTextFromLocation(locSpot.Location);
                    marker.PopupTitle = catItem.GetCategoryTitle();
                    StringBuilder strBuilder = new StringBuilder();
                    foreach(var act in catItem.Activities)
                    {
                        ReferenceToInformation referenceToInformation = act.ReferenceToInformation;
                        appendMarkerLink(strBuilder, referenceToInformation);
                    }
                    marker.PopupContent = strBuilder.ToString();
                    markers.Add(marker);
                }
            }

            mapContainer.MapMarkers.CollectionContent.AddRange(markers);
        }
 internal static void Update_NodeSummaryContainer_NodeSourceActivities(NodeSummaryContainer nodeSummaryContainer, ActivityCollection localCollection, ActivityCollection masterCollection)
 {
     const string DefaultAuthorValue = "Aalto Global Impact";
     var nodes = nodeSummaryContainer.Nodes;
     nodes.CollectionContent.RemoveAll(node => node.TechnicalSource == NodeSourceTypeActivity);
     var activityNodes = masterCollection.CollectionContent.Select(getNodeFromActivity).ToArray();
     nodes.CollectionContent.AddRange(activityNodes);
     nodes.CollectionContent.ForEach(node =>
         {
             if (node.Authors.CollectionContent.Count == 0)
                 node.Authors.CollectionContent.Add(getShortTextObject(DefaultAuthorValue));
             else
             {
             var firstAuthorObject = node.Authors.CollectionContent[0];
                 if (String.IsNullOrWhiteSpace(firstAuthorObject.Content))
                 {
                     firstAuthorObject.Content = DefaultAuthorValue;
                 }
             }
         });
     cleanUpRenderedNodes(nodes);
 }