Exemple #1
0
        public void UnwindToOverview(UIStoryboardSegue segue)
        {
            Console.WriteLine("Unwind to overview");

            var sourceController = segue.SourceViewController as Create_BaseSegueController;

            if (sourceController != null)
            {
                if (sourceController.wasCancelled && thisActivity == null)
                {
                    // If the user cancelled without any info being saved,
                    // return to the previous screen
                    NavigationController.DismissViewController(true, null);
                    return;
                }

                if (sourceController.thisActivity != null)
                {
                    thisActivity = sourceController.thisActivity;
                    if (TableView.Source != null)
                    {
                        (TableView.Source as CreateViewSource).Rows = (List <LearningTask>)thisActivity.LearningTasks;
                        TableView.ReloadData();
                    }
                }

                var suppress = SaveProgress();
            }
        }
        private async Task <List <LearningTask> > ProcessTasks(LearningActivity learningActivity, ApplicationUser currentUser, bool checkUpdated = false)
        {
            //Add each task in the activity to the database
            //If a task has child tasks, add those first
            List <LearningTask> finalTasks = new List <LearningTask>();
            int orderCount = 0;

            for (int i = 0; i < learningActivity.LearningTasks.Count(); i++)
            {
                LearningTask thisTask = learningActivity.LearningTasks.ElementAt(i);
                thisTask.Order = orderCount++;

                LearningTask dbTask = await AddTaskIfNeeded(thisTask, currentUser, checkUpdated);

                List <LearningTask> finalChildTasks = new List <LearningTask>();

                if (thisTask.ChildTasks != null)
                {
                    foreach (LearningTask childTask in thisTask.ChildTasks)
                    {
                        childTask.ParentTask = dbTask;
                        finalChildTasks.Add(await AddTaskIfNeeded(childTask, currentUser, checkUpdated));
                    }
                }

                dbTask.ChildTasks = finalChildTasks;
                await db.SaveChangesAsync();

                finalTasks.Add(dbTask);
            }

            return(finalTasks);
        }
Exemple #3
0
        public void SaveActivityProgress(LearningActivity activity, ICollection <AppTask> progress, string enteredUsername)
        {
            List <AppTask> trimmed = progress.Where(t => t != null).ToList();

            ActivityProgress latestProg = new ActivityProgress
            {
                ActivityId      = activity.Id,
                ActivityVersion = activity.ActivityVersionNumber,
                EnteredUsername = enteredUsername,
                JsonData        = JsonConvert.SerializeObject(activity,
                                                              new JsonSerializerSettings
                {
                    TypeNameHandling      = TypeNameHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                    MaxDepth = 5
                }),
                AppTaskJson = JsonConvert.SerializeObject(trimmed,
                                                          new JsonSerializerSettings
                {
                    TypeNameHandling      = TypeNameHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                    MaxDepth = 5
                }),
            };

            AddProgress(latestProg);
            ShouldRefreshFeed = true;
        }
        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;
            }
            }
        }
        private void RemoteActivityTapped(LearningActivity activity)
        {
            UIAlertController alert = UIAlertController.Create("What do you want to do?", "This activity's share code: " + activity.InviteCode, UIAlertControllerStyle.ActionSheet);

            alert.AddAction(UIAlertAction.Create("Open", UIAlertActionStyle.Default, (a) =>
            {
                var suppress = AppUtils.OpenActivity(activity, Storyboard, NavigationController);
            }));
            alert.AddAction(UIAlertAction.Create("Copy Share Code", UIAlertActionStyle.Default, (a) =>
            {
                UIPasteboard clipboard = UIPasteboard.General;
                clipboard.String       = activity.InviteCode;
                Toast.ShowToast("Copied Code");
            }));
            alert.AddAction(UIAlertAction.Create("Edit", UIAlertActionStyle.Default, (a) =>
            {
                activityToEdit = activity;
                PerformSegue("CreateActivitySegue", this);
            }));
            alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));

            // On iPad, it's a pop up. Stick it in the center of the screen
            UIPopoverPresentationController popCont = alert.PopoverPresentationController;

            if (popCont != null)
            {
                popCont.SourceView = View;
                popCont.SourceRect = new CGRect(View.Bounds.GetMidX(), View.Bounds.GetMidY(), 0, 0);
                popCont.PermittedArrowDirections = 0;
            }

            PresentViewController(alert, true, null);
        }
Exemple #6
0
        public override UICollectionViewCell GetCell(UICollectionView collectionView, Foundation.NSIndexPath indexPath)
        {
            LearningActivity row = Rows[indexPath.Section]?.Items[indexPath.Row];

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

            var cell = (ActivityCollectionCell)collectionView.DequeueReusableCell(ActivityCollectionCell.Key, indexPath);


            string url = (!string.IsNullOrWhiteSpace(row.ImageUrl)) ? AppUtils.GetPathForLocalFile(row.ImageUrl) : "";

            if (!File.Exists(url))
            {
                url = (string.IsNullOrWhiteSpace(row.ImageUrl)) ?
                      "" :
                      Common.ServerUtils.GetUploadUrl(row.ImageUrl);
            }

            cell.UpdateContent(row.Name, row.Description, url);

            return(cell);
        }
        public async Task <HttpResponseMessage> Approve(int id)
        {
            ApplicationUser thisUser = await GetUser();

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

            if (!thisUser.Trusted)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "You do not have permission to approve activities"));
            }

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

            LearningActivity activity = await db.LearningActivities.FindAsync(id);

            if (activity != null)
            {
                activity.Approved = true;
                await db.SaveChangesAsync();

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
        }
        public async Task <HttpResponseMessage> DeleteLearningActivity(int id)
        {
            LearningActivity learningActivity = await db.LearningActivities.FindAsync(id);

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

            ApplicationUser thisUser = await GetUser();

            if (thisUser == null || !thisUser.Trusted && learningActivity.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
            learningActivity.SoftDeleted = true;

            await db.SaveChangesAsync();

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
 public TaskViewSource(LearningActivity data, List <AppTask> taskProgress, Action <AppTask> startTaskAction, Action <AppTask, string, int> resultClicked, Action nameEdit) : base()
 {
     activity   = data;
     Rows       = taskProgress.OrderBy(task => task.Order).ToList();
     startTask  = startTaskAction;
     resClicked = resultClicked;
     editName   = nameEdit;
 }
Exemple #10
0
        public static async Task <bool> PrepActivityFiles(Activity context, LearningActivity act)
        {
            ProgressDialog loadingDialog = null;

            try
            {
                context.RunOnUiThread(() => {
                    loadingDialog = new ProgressDialog(context);
                    loadingDialog.SetTitle(Resource.String.PleaseWait);
                    loadingDialog.SetMessage(context.Resources.GetString(Resource.String.actLoadStart));
                    loadingDialog.Indeterminate = true;
                    loadingDialog.SetCancelable(false);
                    loadingDialog.Show();
                });

                string baseMessage = context.Resources.GetString(Resource.String.actLoadMessage);

                // Get all tasks in this activity which use uploaded files
                List <TaskFileInfo> fileUrls = GetFileTasks(act);

                using (WebClient webClient = new WebClient())
                {
                    // Loop over and pre-prepare listed files
                    for (int i = 0; i < fileUrls.Count; i++)
                    {
                        string thisUrl   = ServerUtils.GetUploadUrl(fileUrls[i].fileUrl);
                        string cachePath = GetCacheFilePath(thisUrl, act.Id, fileUrls[i].extension);

                        try
                        {
                            context.RunOnUiThread(() => loadingDialog.SetMessage(string.Format(baseMessage, i + 1, fileUrls.Count)));

                            if (File.Exists(cachePath))
                            {
                                continue;
                            }

                            await webClient.DownloadFileTaskAsync(new Uri(thisUrl), cachePath).ConfigureAwait(false);
                        }
                        catch (System.Exception e)
                        {
                            File.Delete(cachePath);
                            Console.WriteLine(e.Message);
                            return(false);
                        }
                    }
                }
                return(true);
            }
            finally
            {
                context.RunOnUiThread(() =>
                {
                    loadingDialog?.Dismiss();
                    loadingDialog?.Dispose();
                });
            }
        }
Exemple #11
0
        public void StartTask(LearningActivity activity, AppTask task, Action <string, int> dataCallback, UINavigationController navController)
        {
            thisActivity   = activity;
            thisTask       = task;
            returnWithData = dataCallback;

            this.navController = navController;
            navController.PushViewController(this, true);
        }
Exemple #12
0
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] global::Android.App.Result resultCode, Intent data)
        {
            if (resultCode != Result.Ok)
            {
                return;
            }

            switch (requestCode)
            {
            case AddTaskIntent:
            {
                LearningTask newTask = JsonConvert.DeserializeObject <LearningTask>(data.GetStringExtra("JSON"));
                adapter.Data.Add(newTask);
                adapter.NotifyDataSetChanged();
                break;
            }

            case ManageChildrenIntent:
            {
                List <LearningTask> childTasks = JsonConvert.DeserializeObject <List <LearningTask> >(data.GetStringExtra("JSON"));
                int parentInd = data.GetIntExtra("PARENT", -1);
                if (parentInd >= 0)
                {
                    newActivity.LearningTasks.ToList()[parentInd].ChildTasks = childTasks;
                    adapter.UpdateActivity(newActivity);
                }

                break;
            }

            case EditActivityIntent:
            {
                LearningActivity returned = JsonConvert.DeserializeObject <LearningActivity>(data.GetStringExtra("JSON"));
                if (returned != null)
                {
                    newActivity = returned;
                    adapter.UpdateActivity(returned);
                }

                break;
            }

            case EditTaskIntent:
            {
                LearningTask returned   = JsonConvert.DeserializeObject <LearningTask>(data.GetStringExtra("JSON"));
                int          foundIndex = adapter.Data.FindIndex((LearningTask t) => t.Id == returned.Id);
                if (foundIndex != -1)
                {
                    adapter.Data[foundIndex] = returned;
                    adapter.NotifyDataSetChanged();
                }

                break;
            }
            }
        }
Exemple #13
0
        public static void DeleteInProgress(LearningActivity act)
        {
            List <FileUpload> files = GetFilesForCreation(act);

            foreach (FileUpload file in files)
            {
                string filePath = Path.Combine(fileCacheFolder, file.LocalFilePath);
                File.Delete(filePath);
            }
        }
Exemple #14
0
        public static async Task OpenActivity(LearningActivity act, UIStoryboard storyboard, UINavigationController navController)
        {
            // Save this activity to the database for showing in the 'recent' feed section
            (await Storage.GetDatabaseManager()).AddActivity(act);

            ActivityController taskController = storyboard.InstantiateViewController("ActivityController") as ActivityController;

            taskController.DisplayedActivity = act;
            navController.PushViewController(taskController, true);
        }
        private TreeNode CreateNode(LearningActivity la)
        {
            var node = new TreeNode(la.Name)
            {
                ContextMenuStrip = cmsHierarcy,
                Tag = la
            };

            SetTreeNodeIcon(node);

            return(node);
        }
        private void ActivityChosen(LearningActivity chosen)
        {
            if (chosen == null)
            {
                return;
            }

            using (Intent myIntent = new Intent(this, typeof(CreateCollectionOverviewActivity)))
            {
                myIntent.PutExtra("JSON", JsonConvert.SerializeObject(chosen));
                SetResult(Result.Ok, myIntent);
                base.Finish();
            }
        }
Exemple #17
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 <ImageViewAsync>(Resource.Id.activityIcon);
            continueButton = FindViewById <Button>(Resource.Id.continueBtn);

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

#if DEBUG
            titleInput.Text = "DEBUG TITLE";
            descInput.Text  = "DEBUG DESCRIPTION";
#endif

            string jsonData = Intent.GetStringExtra("JSON") ?? "";
            newActivity = JsonConvert.DeserializeObject <LearningActivity>(jsonData, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto
            });

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

                if (!string.IsNullOrWhiteSpace(newActivity.ImageUrl))
                {
                    if (newActivity.ImageUrl.StartsWith("upload"))
                    {
                        selectedImage = global::Android.Net.Uri.Parse(newActivity.ImageUrl);
                        ImageService.Instance.LoadUrl(ServerUtils.GetUploadUrl(selectedImage.ToString()))
                        .Transform(new CircleTransformation())
                        .Into(imageView);
                    }
                    else
                    {
                        selectedImage = global::Android.Net.Uri.FromFile(new Java.IO.File(newActivity.ImageUrl));
                        ImageService.Instance.LoadFile(selectedImage.Path).Transform(new CircleTransformation()).Into(imageView);
                    }
                }
            }
        }
Exemple #18
0
        private async Task ContinueToNext()
        {
            if (newActivity == null)
            {
                ApplicationUser currentUser = (await Common.LocalData.Storage.GetDatabaseManager()).CurrentUser;

                newActivity = new LearningActivity
                {
                    Author = new LimitedApplicationUser()
                    {
                        Id        = currentUser.Id,
                        FirstName = currentUser.FirstName,
                        Surname   = currentUser.Surname
                    },
                    Id = new Random().Next() // Temp ID, used locally only
                };
            }

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

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

            Intent addTasksActivity = new Intent(this, typeof(CreateActivityOverviewActivity));
            string json             = JsonConvert.SerializeObject(newActivity, new JsonSerializerSettings
            {
                TypeNameHandling      = TypeNameHandling.Auto,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                MaxDepth = 5
            });

            addTasksActivity.PutExtra("JSON", json);

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

            Finish();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.CreateFinishActivity);

            rand = new Random();

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

            editingSubmitted = Intent.GetBooleanExtra("EDITING_SUBMITTED", false);
            activity         = JsonConvert.DeserializeObject <LearningActivity>(jsonData, new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.Auto
            });

            FindViewById <Button>(Resource.Id.uploadBtn).Click   += FinishClicked;
            FindViewById <Button>(Resource.Id.addPlaceBtn).Click += AddPlaceClicked;

            choicesRoot         = FindViewById <LinearLayout>(Resource.Id.placesRoot);
            activityPublic      = FindViewById <CheckBox>(Resource.Id.checkboxPublic);
            activityPublic.Text = string.Format(CultureInfo.InvariantCulture, activityPublic.Text, "Activity");
            reqUsername         = FindViewById <CheckBox>(Resource.Id.checkboxReqName);

            using (TextView publicBlurb = FindViewById <TextView>(Resource.Id.publicBlurb),
                   addPlaceTitle = FindViewById <TextView>(Resource.Id.addPlaceTitle),
                   addPlaceBlurb = FindViewById <TextView>(Resource.Id.addPlaceBlurb))
            {
                publicBlurb.Text   = string.Format(CultureInfo.InvariantCulture, publicBlurb.Text, "Activity");
                addPlaceTitle.Text = string.Format(CultureInfo.InvariantCulture, addPlaceTitle.Text, "Activity");
                addPlaceBlurb.Text = string.Format(CultureInfo.InvariantCulture, addPlaceBlurb.Text, "Activity");
            }

            chosenPlaces = new List <Place>();

            if (editingSubmitted)
            {
                activityPublic.Checked = activity.IsPublic;
                reqUsername.Checked    = activity.RequireUsername;

                if (activity.Places != null)
                {
                    foreach (Place place in activity.Places)
                    {
                        AddPlace(place);
                    }
                }
            }
        }
Exemple #20
0
        public CreatedTasksAdapter(Context context, LearningActivity learningAct, bool editingSubmitted, Action save)
        {
            this.editingSubmitted = editingSubmitted;

            if (learningAct.LearningTasks != null)
            {
                Data = (List <LearningTask>)learningAct.LearningTasks;
            }
            else
            {
                Data = new List <LearningTask>();
            }

            this.context     = context;
            learningActivity = learningAct;
            SaveProgress     = save;
        }
        private static LearningActivity CreateLa(bool isActivity, TreeNode parentNode, int?parentId = null)
        {
            var type = isActivity ? "Content" : "Container";

            var name = $"{type}{parentNode.Level + 1}.{parentNode.Nodes.Count}";

            var la = new LearningActivity(isActivity, name)
            {
                //Level = parentNode.Level; // todo
                Id = ++_idCounter
            };

            if (parentId != null)
            {
                la.ParentRelation.ParentRelationId = parentId.Value;
            }

            return(la);
        }
        public async Task <IHttpActionResult> PutLearningActivity(int id, LearningActivity learningActivity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            LearningActivity existing = db.LearningActivities.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(learningActivity.Places, thisUser, existing.Places.ToList());

            List <LearningTask> tasks = await ProcessTasks(learningActivity, thisUser, true);

            existing.AppVersionNumber      = learningActivity.AppVersionNumber;
            existing.ActivityVersionNumber = learningActivity.ActivityVersionNumber;
            existing.Approved        = thisUser.Trusted;
            existing.CreatedAt       = DateTime.UtcNow;
            existing.Description     = learningActivity.Description;
            existing.ImageUrl        = learningActivity.ImageUrl;
            existing.Name            = learningActivity.Name;
            existing.RequireUsername = learningActivity.RequireUsername;
            existing.IsPublic        = learningActivity.IsPublic;
            existing.Places          = places;
            existing.LearningTasks   = tasks;

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

            await db.SaveChangesAsync();

            return(StatusCode(HttpStatusCode.OK));
        }
Exemple #23
0
        public static async Task LaunchActivity(LearningActivity activity, Activity context, bool fromCollection = false)
        {
            if (activity == null)
            {
                return;
            }

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

            Dictionary <string, string> properties = new Dictionary <string, string>
            {
                { "UserId", (await GetDbManager().ConfigureAwait(false)).CurrentUser.Id },
                { "ActivityId", activity.Id.ToString(CultureInfo.InvariantCulture) }
            };

            Analytics.TrackEvent("MainActivity_LaunchActivity", properties);

            activity.LearningTasks = activity.LearningTasks.OrderBy(t => t.Order).ToList();
            ISharedPreferences preferences = PreferenceManager.GetDefaultSharedPreferences(context);

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

            MainLandingFragment.ForceRefresh = true;

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

            using (Intent performActivityIntent = new Intent(context, typeof(ActTaskListActivity)))
            {
                performActivityIntent.PutExtra("JSON", json);
                performActivityIntent.PutExtra("FromCollection", fromCollection);
                context.StartActivity(performActivityIntent);
            }
        }
Exemple #24
0
        public void UnwindToChildrenOverview(UIStoryboardSegue segue)
        {
            var sourceController = segue.SourceViewController as Create_BaseSegueController;

            if (sourceController != null)
            {
                if (sourceController.wasCancelled && thisActivity == null)
                {
                    // If the user cancelled without any info being saved,
                    // return to the previous screen
                    NavigationController.PopViewController(true);
                    return;
                }

                thisActivity = sourceController.thisActivity;
                thisTask     = thisActivity.LearningTasks.ToList()[parentTaskIndex];

                var suppress = SaveProgress();
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            screenBounds = UIScreen.MainScreen.Bounds;

            collectionView.RegisterNibForCell(ActivityCollectionCell.Nib, ActivityCollectionCell.Key);
            collectionView.RegisterNibForSupplementaryView(FeedSectionHeader.Nib, UICollectionElementKindSectionKey.Header, FeedSectionHeader.Key);

            source = new ActivityViewSource();

            refreshControl               = new UIRefreshControl();
            refreshControl.TintColor     = AppUtils.AppMainColour;
            refreshControl.ValueChanged += (sender, e) =>
            {
                RefreshFeed();
            };

            collectionView.ShowsHorizontalScrollIndicator = false;
            collectionView.RefreshControl  = refreshControl;
            collectionView.Source          = source;
            collectionView.AllowsSelection = true;
            collectionView.Delegate        = new SectionedClickableDelegate((section, index) =>
            {
                LearningActivity thisActivity = source.Rows[section]?.Activities[index];

                if (thisActivity == null)
                {
                    return;
                }

                if (unsubmittedActivities != null && unsubmittedActivities.Exists((LearningActivity obj) => { return(obj.Id == thisActivity.Id); }))
                {
                    LocalActivityTapped(thisActivity);
                }
                else
                {
                    RemoteActivityTapped(thisActivity);
                }
            });
        }
Exemple #26
0
        public static Task <ServerResponse <string> > UploadActivity(AppDataUpload upload, bool updateExisting = false)
        {
            LearningActivity  activity = JsonConvert.DeserializeObject <LearningActivity>(upload.JsonData);
            List <FileUpload> files    = JsonConvert.DeserializeObject <List <FileUpload> >(upload.FilesJson);

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

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

            // Update tasks (and their children) which have had files uploaded
            // to point at the new file URLs
            foreach (LearningTask parentTask in activity.LearningTasks)
            {
                string newJson = GetNewTaskJsonData(parentTask, files);
                if (!string.IsNullOrWhiteSpace(newJson))
                {
                    parentTask.JsonData = newJson;
                }

                if (parentTask.ChildTasks == null)
                {
                    continue;
                }

                foreach (LearningTask childTask in parentTask.ChildTasks)
                {
                    string newChildJson = GetNewTaskJsonData(childTask, files);
                    if (!string.IsNullOrWhiteSpace(newChildJson))
                    {
                        childTask.JsonData = newChildJson;
                    }
                }
            }

            return(updateExisting ? Put <string>(upload.UploadRoute, activity) :
                   Post <string>(upload.UploadRoute, activity));
        }
Exemple #27
0
        private async Task <ICollection <LearningActivity> > ProcessActivities(ICollection <LearningActivity> activities, ApplicationUser thisUser)
        {
            List <LearningActivity> finalActs = new List <LearningActivity>();

            if (activities == null)
            {
                return(finalActs);
            }

            foreach (LearningActivity act in activities)
            {
                LearningActivity existing = await db.LearningActivities.Where(a => a.Id == act.Id).FirstOrDefaultAsync();

                if (existing != null)
                {
                    finalActs.Add(existing);
                }
            }

            return(finalActs);
        }
Exemple #28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.CreateManageTasksActivity);

            editingSubmitted = Intent.GetBooleanExtra("EDITING_SUBMITTED", false);
            string jsonData = Intent.GetStringExtra("JSON") ?? "";

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

            adapter = new CreatedTasksAdapter(this, newActivity, editingSubmitted, SaveProgress);
            adapter.EditActivityClick       += Adapter_EditActivityClick;
            adapter.FinishClick             += Adapter_FinishClick;
            adapter.EditItemClick           += Adapter_EditItemClick;
            adapter.DeleteItemClick         += Adapter_DeleteItemClick;
            adapter.ManageChildrenItemClick += Adapter_ManageChildrenItemClick;

            fabPrompt = FindViewById <TextView>(Resource.Id.fabPrompt);

            RecyclerView recyclerView = FindViewById <RecyclerView>(Resource.Id.recyclerView);

            recyclerView.SetAdapter(adapter);

            ItemTouchHelper.Callback callback    = new DragHelper(adapter);
            ItemTouchHelper          touchHelper = new ItemTouchHelper(callback);

            touchHelper.AttachToRecyclerView(recyclerView);

            layoutManager = new LinearLayoutManager(this);
            recyclerView.SetLayoutManager(layoutManager);


            using (FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.createTaskFab))
            {
                fab.Click += Fab_Click;
            }
        }
        private void ContinuePressed(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ActivityTitle.Text))
            {
                AppUtils.ShowSimpleDialog(this, "Missing Title", "Please enter a title for your Activity!", "Got it");
                return;
            }

            if (string.IsNullOrWhiteSpace(ActivityDescription.Text))
            {
                AppUtils.ShowSimpleDialog(this, "Missing Description", "Please enter a short description describing what your Activity is about!", "Got it");
                return;
            }

            if (thisActivity == null)
            {
                thisActivity = new LearningActivity
                {
                    Id = (new Random()).Next()
                };
            }

            thisActivity.Name        = ActivityTitle.Text;
            thisActivity.Description = ActivityDescription.Text;

            if (!string.IsNullOrWhiteSpace(currentImagePath))
            {
                thisActivity.ImageUrl = Path.Combine(Directory.GetParent(currentImagePath).Name, Path.GetFileName(currentImagePath));

                if (!string.IsNullOrWhiteSpace(previousImagePath) && !previousImagePath.StartsWith("upload"))
                {
                    // new image replaces old one, delete the previous image
                    File.Delete(AppUtils.GetPathForLocalFile(previousImagePath));
                }
            }

            PerformSegue("UnwindToOverview", this);
        }
        private void Adapter_OpenLocationClick(object sender, int position)
        {
            position--;
            LearningActivity thisAct   = adapter.Collection.Activities[position];
            Place            thisPlace = thisAct.Places?.FirstOrDefault();

            if (thisPlace == null)
            {
                return;
            }

            global::Android.Net.Uri mapsIntentUri = global::Android.Net.Uri.Parse(
                string.Format(CultureInfo.InvariantCulture,
                              "geo:{0},{1}?q={0},{1}(Target+Location)",
                              thisPlace.Latitude,
                              thisPlace.Longitude));

            using (Intent mapIntent = new Intent(Intent.ActionView, mapsIntentUri))
            {
                mapIntent.SetPackage("com.google.android.apps.maps");
                StartActivity(mapIntent);
            }
        }