public async Task <IActionResult> AddChangelog(Guid id, bool update = false)
        {
            User user            = Helpers.UserHelper.GetCurrentUser(User, db);
            ReferenceGeometry rg = await db.Geometries.FindAsync(id);

            if (rg != null)
            {
                ChangeLog cl = new ChangeLog()
                {
                    User = user, Log = "Created new geometry"
                };
                if (update)
                {
                    cl.Log = "Changed geometry";
                }
                ChangeLogGeometry clg = new ChangeLogGeometry()
                {
                    ChangeLog = cl, Geometry = rg
                };
                db.ChangeLogs.Add(cl);
                db.ChangeLogsGeometries.Add(clg);

                await db.SaveChangesAsync();

                return(Json("OK"));
            }
            return(Json("GeometryId not found"));
        }
Beispiel #2
0
 /// <summary>
 /// Show a list of further actions (including copying the guid)
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void GUIDButton_Clicked(object sender, EventArgs e)
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         string formAction = await DisplayActionSheet("Optionen", "Abbrechen", null, "Geometrie entfernen", "GUID Kopieren", "Geometriename editieren");
         if (formAction == "Geometrie entfernen")
         {
             DeleteButton_Clicked(sender, e);
         }
         else if (formAction == "GUID Kopieren")
         {
             GroupedFormRec formRec = ((Button)sender).BindingContext as GroupedFormRec;
             var geom  = formRec.Geom;
             var extId = geom.geometryId;
             ViewModel.CopyGUID(extId);
             await DisplayAlert("BDC GUID kopiert", "", "OK");
         }
         else if (formAction == "Geometriename editieren")
         {
             GroupedFormRec formRec = ((Button)sender).BindingContext as GroupedFormRec;
             var geom          = formRec.Geom;
             string newName    = await DisplayPromptAsync("Geometriename", "Editieren Sie bitte der Geometriename", accept: "OK", cancel: "Abbrechen", initialValue: geom.geometryName, keyboard: Keyboard.Text);
             geom.geometryName = newName;
             geom.timestamp    = DateTime.Now;
             if (geom.status != -1)
             {
                 geom.status = 2;
             }
             ReferenceGeometry.SaveGeometry(geom);
             ViewModel.UpdateRecords();
         }
     });
 }
Beispiel #3
0
        private NetTopologySuite.Features.Feature getFeature(ReferenceGeometry g, GeomType type)
        {
            List <Coordinate> coordinatesSwissGrid = new List <Coordinate>();

            Coordinate[] coordinates;
            if (type == GeomType.Point)
            {
                coordinates = g.Point.Coordinates;
            }
            else if (type == GeomType.Line)
            {
                coordinates = g.Line.Coordinates;
            }
            else if (type == GeomType.Polygon)
            {
                coordinates = g.Polygon.Coordinates;
            }
            else
            {
                coordinates = null;
            }
            foreach (Coordinate coor in coordinates)
            {
                // Convert Coordinates to LV03
                double x = 0, y = 0, h = 0;
                CoordinateConverter.WGS84toLV03(coor.Y, coor.X, 0, ref x, ref y, ref h);

                Coordinate newcoord = new Coordinate(x, y);
                coordinatesSwissGrid.Add(newcoord);
            }
            try
            {
                var      gf = new GeometryFactory();
                Geometry polygonSwissGrid = null;
                if (type == GeomType.Point)
                {
                    polygonSwissGrid = gf.CreatePoint(coordinatesSwissGrid[0]);
                }
                else if (type == GeomType.Line)
                {
                    polygonSwissGrid = gf.CreateLineString(coordinatesSwissGrid.ToArray());
                }
                else if (type == GeomType.Polygon)
                {
                    polygonSwissGrid = gf.CreatePolygon(coordinatesSwissGrid.ToArray());
                }

                NetTopologySuite.Features.AttributesTable attribute = new NetTopologySuite.Features.AttributesTable();
                attribute.Add("id", g.GeometryId);
                attribute.Add("name", g.GeometryName);


                NetTopologySuite.Features.Feature i = new NetTopologySuite.Features.Feature(polygonSwissGrid, attribute);
                return(i);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
        public async Task <IActionResult> Move(Guid from, Guid to)
        {
            Record r = await db.Records.Where(m => m.RecordId == from).FirstOrDefaultAsync();

            if (r == null)
            {
                return(Content("Error"));
            }
            ReferenceGeometry rg = await db.Geometries.Where(m => m.GeometryId == to).FirstOrDefaultAsync();

            if (rg == null)
            {
                return(Content("Error"));
            }

            r.GeometryId      = rg.GeometryId;
            db.Entry(r).State = EntityState.Modified;
            User      user = Helpers.UserHelper.GetCurrentUser(User, db);
            ChangeLog cl   = new ChangeLog()
            {
                Log = "Moved Record to new Geometry", User = user
            };
            ChangeLogRecord cr = new ChangeLogRecord()
            {
                ChangeLog = cl, Record = r
            };

            db.ChangeLogs.Add(cl);
            db.ChangeLogsRecords.Add(cr);

            await db.SaveChangesAsync();

            return(Content("OK"));
        }
        public async void Execute(object parameter)
        {
            var response = await App.Current.MainPage.DisplayActionSheet("Möchten Sie diese Geometrie vom Gerät entfernen?", "Abbrechen", "Entfernen");

            if (response == "Entfernen")
            {
                var geom = parameter as ReferenceGeometry;
                ReferenceGeometry.DeleteGeometry(geom.Id);
            }
        }
Beispiel #6
0
        /// <summary>
        /// Delete a geometry
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void DeleteButton_Clicked(object sender, EventArgs e)
        {
            string formAction = await DisplayActionSheet("Möchten Sie diese Geometrie vom Gerät entfernen?", "Abbrechen", "Entfernen");

            if (formAction == "Entfernen")
            {
                GroupedFormRec formRec = ((Button)sender).BindingContext as GroupedFormRec;
                var            geom    = formRec.Geom;
                if (ViewModel.Object_pk == geom.Id)
                {
                    ViewModel.Object_pk = null;
                }
                ReferenceGeometry.DeleteGeometry(geom.Id);
            }
        }
        /// <summary>
        /// Save the temporary geometry
        /// </summary>
        private void SaveNewGeom()
        {
            MessagingCenter.Subscribe <MapPage, string>(this, "GeometryName", (sender, arg) =>
            {
                var geomName = arg as string;
                ReferenceGeometry.SaveGeometry(TempCoordinates, geomName);
                RemoveTempGeometry();
                RefreshShapes();
                MessagingCenter.Unsubscribe <MapPage, string>(this, "GeometryName");
            });
            Mapsui.Geometries.Point point = TempCoordinates[0];
            var coords      = point.ToDoubleArray();
            var coordString = coords[1].ToString("#.000#") + ", " + coords[0].ToString("#.000#");

            MessagingCenter.Send <MapPageVM, string>(this, "RequestGeometryName", coordString);
        }
        public async Task <IActionResult> Rename(Guid id, string newName)
        {
            User user = Helpers.UserHelper.GetCurrentUser(User, db);

            ReferenceGeometry rg = await db.Geometries
                                   .Include(m => m.ProjectGroup).ThenInclude(pg => pg.Group).ThenInclude(g => g.GroupUsers)
                                   .Where(m => m.GeometryId == id).FirstOrDefaultAsync();

            if (rg == null)
            {
                return(StatusCode(404));
            }
            // No right for it, User is not in Group

            if ((rg.ProjectGroup.Group.GroupUsers.Any(m => m.UserId == user.UserId)) || User.IsInRole("DM"))
            {
                rg.GeometryName = newName;
                ChangeLog cl = new ChangeLog()
                {
                    Log = "renamed geometry to " + newName, User = user
                };
                db.ChangeLogs.Add(cl);
                ChangeLogGeometry clg = new ChangeLogGeometry()
                {
                    ChangeLog = cl, Geometry = rg
                };
                db.ChangeLogsGeometries.Add(clg);

                db.Entry(rg).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(Content("OK"));
            }

            // No right for it, User is not in Group

            return(StatusCode(403));
        }
        public async Task <IActionResult> Details(Guid id)
        {
            User user = Helpers.UserHelper.GetCurrentUser(User, db);

            ReferenceGeometry g = await db.Geometries
                                  .Include(m => m.Records).ThenInclude(u => u.TextData).ThenInclude(td => td.FormField)
                                  .Include(m => m.Records).ThenInclude(u => u.NumericData).ThenInclude(td => td.FormField)
                                  .Include(m => m.Records).ThenInclude(u => u.BooleanData).ThenInclude(td => td.FormField)
                                  .Include(m => m.Records).ThenInclude(u => u.Form).ThenInclude(f => f.FormFormFields).ThenInclude(fff => fff.FormField)
                                  .Include(m => m.Records).ThenInclude(u => u.Form).ThenInclude(f => f.FormFormFields).ThenInclude(fff => fff.FormField).ThenInclude(mo => mo.PublicMotherFormField)
                                  .Include(m => m.Records).ThenInclude(u => u.ProjectGroup.Group)
                                  .Include(m => m.Records).ThenInclude(u => u.RecordChangeLogs).ThenInclude(rcl => rcl.ChangeLog).ThenInclude(cl => cl.User)
                                  .Where(m => m.GeometryId == id)
                                  .Where(m => m.StatusId != StatusEnum.deleted).FirstOrDefaultAsync();

            if (g == null)
            {
                return(StatusCode(500));
            }

            List <Project> projects           = new List <Project>();
            List <Project> erfassendeProjects = new List <Project>();

            if (User.IsInRole("DM"))
            {
                projects = await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.DM);

                erfassendeProjects = projects;
            }
            else if (User.IsInRole("EF"))
            {
                erfassendeProjects = await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.EF);
            }
            if (User.IsInRole("PK"))
            {
                projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PK));
                erfassendeProjects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PK));
            }
            if (User.IsInRole("PL"))
            {
                projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PL));
                erfassendeProjects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PL));
            }

            projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.LE));
            projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.LE_OGD));
            projects.AddRange(erfassendeProjects);

            if (!projects.Any(m => m.ProjectId == g.ProjectGroupProjectId))
            {
                return(StatusCode(StatusCodes.Status403Forbidden));
            }
            if (!erfassendeProjects.Any(m => m.ProjectId == g.ProjectGroupProjectId))
            {
                ViewData["ReadOnly"] = true;
            }
            else
            {
                ViewData["ReadOnly"] = false;
            }

            GeometrieViewModel gvm = new GeometrieViewModel()
            {
                Geometry = g
            };

            gvm.Records = new List <RecordViewModel>();

            List <Group> myGroups;

            if (User.IsInRole("DM"))
            {
                myGroups = await db.Groups.ToListAsync();
            }
            else if ((User.IsInRole("PK")) || (User.IsInRole("PL")))
            {
                Project p = await db.Projects.Where(m => m.ProjectId == g.ProjectGroupProjectId).Include(m => m.ProjectConfigurator).Include(m => m.ProjectManager).FirstAsync();

                if ((p.ProjectConfigurator.UserId == user.UserId) || (p.ProjectManager.UserId == user.UserId))
                {
                    myGroups = await db.Groups.ToListAsync();
                }
                else
                {
                    myGroups = await db.Groups.Where(m => m.GroupUsers.Any(u => u.UserId == user.UserId)).ToListAsync();
                }
            }
            else
            {
                myGroups = await db.Groups.Where(m => m.GroupUsers.Any(u => u.UserId == user.UserId)).ToListAsync();
            }

            await RecordsController.CreateDynamicView(db, g, g.ProjectGroup, myGroups, gvm);

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

            // Are there any plugins for the forms?
            foreach (IReferenceGeometryPlugin rge in _referenceGeometryExtension.Plugins)
            {
                if (g.Records.Any(m => m.FormId == rge.FormId))
                {
                    pluginslist.Add(rge.GetName());
                }
            }

            ViewBag.plugins = pluginslist;

            return(View(gvm));
        }
        /// <summary>
        /// On creating the view controller for a specific recordId, the form is checked to see which parameters are required, and the relevant input fields are queued up for adding to the page.
        /// The relevant data is then extracted from the database for the specific field, and added as the initial value for that field.
        /// </summary>
        /// <param name="recId">recordID</param>
        public FormPageVM(int recId)
        {
            using (SQLiteConnection conn = new SQLiteConnection(Preferences.Get("databaseLocation", "")))
            {
                //Get the record and its corresponding variable values
                var queriedrec = conn.GetWithChildren <Record>(recId);
                ReadOnly = queriedrec.readOnly;
                RecId    = recId;
                var txts  = queriedrec.texts;
                var nums  = queriedrec.numerics;
                var bools = queriedrec.booleans;
                //Compile the GUID
                BDCGUIDtext = "<<BDC><" + queriedrec.recordId + ">>";

                var formId   = queriedrec.formId;
                var formTemp = conn.Table <Form>().Where(Form => Form.formId == formId).FirstOrDefault();
                formType = conn.GetWithChildren <Form>(formTemp.Id);
                foreach (var formField in formType.formFields.OrderBy(f => f.order))
                {
                    var label = new Label();
                    if (formField.title != null && formField.title != String.Empty)
                    {
                        label.Text = formField.title;
                    }
                    else
                    {
                        label.Text = formField.description;
                    }
                    if (formField.mandatory)
                    {
                        label.Text = label.Text + " *";
                    }
                    label.FontAttributes = FontAttributes.Bold;
                    label.Margin         = new Thickness(0, 10, 0, 0);
                    label.SetAppThemeColor(Label.TextColorProperty, Color.Black, Color.White);
                    if (formField.typeId != 31) //Add label next to checkbox for boolean
                    {
                        Assets.Add(label);
                    }



                    if (formField.typeId == 11 || formField.typeId == 61)
                    {
                        try
                        {
                            var text      = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).FirstOrDefault();
                            var textField = new CustomEntry();

                            if (text == null)
                            {
                                //CreateNew
                                var txt = new TextData {
                                    textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId
                                };
                                conn.Insert(txt);
                                txts.Add(txt);
                                queriedrec.texts = txts;
                                conn.UpdateWithChildren(queriedrec);
                                text = txt;
                            }
                            textField = new CustomEntry {
                                Text = text.value.ToString()
                            };
                            textField.Keyboard              = Keyboard.Text;
                            textField.Placeholder           = formField.description;
                            textField.ClearButtonVisibility = ClearButtonVisibility.WhileEditing;
                            textField.ReturnType            = ReturnType.Done;
                            textField.Margin       = new Thickness(0, 0, 0, 10);
                            textField.ValueId      = text.Id;
                            textField.TypeId       = formField.typeId;
                            textField.TextChanged += TextFieldChanged;
                            textField.IsEnabled    = !ReadOnly;
                            textField.Mandatory    = formField.mandatory;
                            var empty = String.IsNullOrEmpty(textField.Text);
                            if (formField.mandatory)
                            {
                                Validation.Add((int)textField.ValueId, !empty);
                            }
                            if (ReadOnly)
                            {
                                textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                            }
                            Assets.Add(textField);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not create field" + e);
                        }
                    }
                    else if (formField.typeId == 41)
                    {
                        try
                        {
                            var text        = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).Take(1).FirstOrDefault();
                            var dateField   = new CustomDatePicker();
                            var timeField   = new CustomTimePicker();
                            var nowButton   = new Button();
                            var clearButton = new Button();

                            var stack = new CustomStackLayout()
                            {
                                Orientation = StackOrientation.Horizontal,
                                Children    =
                                {
                                    dateField, timeField, nowButton, clearButton
                                }
                            };
                            stack.WidthRequest      = 350;
                            stack.HorizontalOptions = LayoutOptions.Start;

                            if (text == null)
                            {
                                //CreateNew
                                var txt = new TextData {
                                    textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId
                                };
                                conn.Insert(txt);
                                txts.Add(txt);
                                queriedrec.texts = txts;
                                conn.UpdateWithChildren(queriedrec);
                                text = txt;
                            }
                            List <string> choices = Form.FetchFormChoicesForDropdown(formField.fieldId);

                            try
                            {
                                var dt = DateTime.ParseExact(text.value, "yyyy-MM-ddTHH:mm:sszzz", null);

                                if (text.value != null && text.value != String.Empty)
                                {
                                    dateField.NullableDate = dt.Date;
                                    timeField.NullableDate = new TimeSpan(dt.TimeOfDay.Hours, dt.TimeOfDay.Minutes, 0);
                                }
                            }
                            catch (Exception exp)
                            {
                                Console.WriteLine(exp);
                            }

                            dateField.Margin           = new Thickness(0, 0, 0, 10);
                            dateField.ValueId          = text.Id;
                            dateField.TypeId           = formField.typeId;
                            dateField.Format           = "dd MMMM yyyy";
                            dateField.IsEnabled        = !ReadOnly;
                            dateField.WidthRequest     = 170;
                            dateField.HeightRequest    = 40;
                            dateField.Mandatory        = formField.mandatory;
                            dateField.VerticalOptions  = LayoutOptions.StartAndExpand;
                            dateField.PropertyChanged += DateFieldChanged;
                            var empty = (dateField.NullableDate == null);
                            if (formField.mandatory)
                            {
                                Validation.Add((int)dateField.ValueId, !empty);
                            }
                            if (ReadOnly)
                            {
                                dateField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                            }
                            timeField.Margin           = new Thickness(0, 0, 0, 0);
                            timeField.ValueId          = text.Id;
                            timeField.TypeId           = formField.typeId;
                            timeField.Format           = "HH:mm";
                            timeField.IsEnabled        = !ReadOnly;
                            timeField.WidthRequest     = 70;
                            timeField.HeightRequest    = 40;
                            timeField.VerticalOptions  = LayoutOptions.StartAndExpand;
                            timeField.Mandatory        = formField.mandatory;
                            timeField.PropertyChanged += TimeFieldChanged;
                            if (ReadOnly)
                            {
                                timeField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                            }


                            Dictionary <String, Object> dic = new Dictionary <string, object>();
                            dic.Add("text", text);
                            dic.Add("date", dateField);
                            dic.Add("time", timeField);

                            var nowCommand = new Command(FillOutDate);

                            nowButton.Text             = "JETZT";
                            nowButton.TextTransform    = TextTransform.Uppercase;
                            nowButton.FontSize         = 12;
                            nowButton.Style            = (Style)Xamarin.Forms.Application.Current.Resources["TransparentButtonStyle"];
                            nowButton.Command          = nowCommand;
                            nowButton.CommandParameter = dic;
                            nowButton.Margin           = new Thickness(10, 0, 0, 0);
                            nowButton.WidthRequest     = 40;
                            nowButton.HeightRequest    = 40;
                            nowButton.VerticalOptions  = LayoutOptions.StartAndExpand;
                            nowButton.IsVisible        = !ReadOnly;

                            var clearCommand = new Command(ClearDate);

                            clearButton.Text             = "ⓧ";
                            clearButton.FontSize         = 20;
                            clearButton.Style            = (Style)Xamarin.Forms.Application.Current.Resources["TransparentButtonStyle"];
                            clearButton.Command          = clearCommand;
                            clearButton.CommandParameter = dic;
                            clearButton.Margin           = new Thickness(10, 0, 10, 0);
                            clearButton.WidthRequest     = 30;
                            clearButton.HeightRequest    = 40;
                            clearButton.VerticalOptions  = LayoutOptions.StartAndExpand;
                            clearButton.IsVisible        = !ReadOnly;

                            stack.Margin  = new Thickness(0, 0, 0, 10);
                            stack.ValueId = text.Id;
                            stack.TypeId  = formField.typeId;

                            Assets.Add(stack);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not create field" + e);
                        }
                    }
                    else if (formField.typeId == 51)
                    {
                        try
                        {
                            var text      = conn.Table <TextData>().Select(t => t).Where(TextData => TextData.record_fk == RecId).Where(TextData => TextData.formFieldId == formField.fieldId).Take(1).FirstOrDefault();
                            var textField = new CustomPicker();
                            if (text == null)
                            {
                                //CreateNew
                                var txt = new TextData {
                                    textId = Guid.NewGuid().ToString(), title = String.Empty, value = String.Empty, formFieldId = formField.fieldId, record_fk = recId
                                };
                                conn.Insert(txt);
                                txts.Add(txt);
                                queriedrec.texts = txts;
                                conn.UpdateWithChildren(queriedrec);
                                text = txt;
                            }
                            List <string> choices = Form.FetchFormChoicesForDropdown(formField.Id);
                            textField.ItemsSource = choices;
                            textField.ValueId     = text.Id;
                            textField.TypeId      = formField.Id;
                            textField.Title       = formField.description;
                            textField.IsEnabled   = !ReadOnly;
                            textField.Mandatory   = formField.mandatory;
                            if (formField.mandatory)
                            {
                                Validation.Add((int)textField.ValueId, textField.SelectedItem != null || (text.value != null && text.value != String.Empty));
                            }
                            if (ReadOnly)
                            {
                                textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                            }
                            textField.SelectedIndexChanged += DidSelectFromChoices;

                            if (text.fieldChoiceId != null)
                            {
                                textField.SelectedIndex = choices.FindIndex(a => a.Contains(text.value));
                                if (textField.SelectedIndex == -1 && (text.value != null && text.value != String.Empty))
                                {
                                    textField.Title = text.value;
                                }
                                textField.SelectedItem = text.value;
                            }
                            else if (text.value != null && text.value != String.Empty)
                            {
                                textField.Title = text.value;
                            }
                            textField.Margin = new Thickness(0, 0, 0, 10);

                            Assets.Add(textField);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not create field" + e);
                        }
                    }
                    else if (formField.typeId == 21)
                    {
                        try
                        {
                            var num       = conn.Table <NumericData>().Select(n => n).Where(NumericData => NumericData.record_fk == RecId).Where(NumericData => NumericData.formFieldId == formField.fieldId).Take(1).FirstOrDefault();
                            var textField = new CustomEntry();
                            if (num == null)
                            {
                                //CreateNew
                                var nm = new NumericData {
                                    numericId = Guid.NewGuid().ToString(), title = String.Empty, value = null, formFieldId = formField.fieldId, record_fk = recId
                                };
                                conn.Insert(nm);
                                nums.Add(nm);
                                queriedrec.texts = txts;
                                conn.UpdateWithChildren(queriedrec);
                                num = nm;
                            }

                            textField = new CustomEntry {
                                Text = ((double)num.value).ToString("F", CultureInfo.CreateSpecificCulture("de-CH"))
                            };
                            textField.Keyboard = Keyboard.Numeric;
                            textField.ClearButtonVisibility = ClearButtonVisibility.WhileEditing;
                            textField.ReturnType            = ReturnType.Done;
                            textField.Margin    = new Thickness(0, 0, 0, 10);
                            textField.ValueId   = num.Id;
                            textField.TypeId    = formField.typeId;
                            textField.IsEnabled = !ReadOnly;
                            textField.Mandatory = formField.mandatory;
                            var empty = String.IsNullOrEmpty(textField.Text);
                            if (formField.mandatory)
                            {
                                Validation.Add((int)textField.ValueId, !empty);
                            }
                            if (ReadOnly)
                            {
                                textField.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                            }
                            textField.TextChanged += NumericFieldChanged;
                            Assets.Add(textField);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not create field" + e);
                        }
                    }
                    else if (formField.typeId == 31)
                    {
                        try
                        {
                            var boolValue = conn.Table <BooleanData>().Select(n => n).Where(BooleanData => BooleanData.record_fk == RecId).Where(BooleanData => BooleanData.formFieldId == formField.fieldId).Take(1).FirstOrDefault();
                            var checkBox  = new CustomCheckBox();
                            if (boolValue == null)
                            {
                                //CreateNew
                                boolValue = new BooleanData {
                                    booleanId = Guid.NewGuid().ToString(), title = String.Empty, value = false, formFieldId = formField.fieldId, record_fk = recId
                                };
                                conn.Insert(boolValue);
                                bools.Add(boolValue);
                                queriedrec.booleans = bools;
                                conn.UpdateWithChildren(queriedrec);
                            }
                            if (boolValue != null)
                            {
                                checkBox.IsChecked = (bool)boolValue.value;
                            }
                            checkBox.Margin    = new Thickness(0, 0, 0, 0);
                            checkBox.ValueId   = boolValue.Id;
                            checkBox.TypeId    = formField.typeId;
                            checkBox.IsEnabled = !ReadOnly;
                            if (ReadOnly)
                            {
                                checkBox.Color = Color.LightGray;
                            }
                            checkBox.CheckedChanged    += BooleanFieldChanged;
                            checkBox.VerticalOptions    = LayoutOptions.Fill;
                            checkBox.HorizontalOptions  = LayoutOptions.Start;
                            label.VerticalOptions       = LayoutOptions.Fill;
                            label.VerticalTextAlignment = TextAlignment.Center;
                            label.Margin = new Thickness(0, 0, 0, 0);
                            var stack = new CustomStackLayout()
                            {
                                Orientation       = StackOrientation.Horizontal,
                                HorizontalOptions = LayoutOptions.Start,
                                VerticalOptions   = LayoutOptions.Fill,
                                Children          =
                                {
                                    checkBox, label
                                }
                            };
                            stack.Margin = new Thickness(0, 0, 0, 10);
                            Assets.Add(stack);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not create field" + e);
                        }
                    }
                }

                var geomlabel = new Label();
                geomlabel.Text           = "Zugeordnete Geometrie";
                geomlabel.FontAttributes = FontAttributes.Bold;
                geomlabel.Margin         = new Thickness(0, 10, 0, 0);
                Assets.Add(geomlabel);

                AssociatedGeometry = new CustomPicker();
                Geoms = ReferenceGeometry.GetAllGeometries().Where(g => g.status < 3).OrderBy(g => g.geometryName).ToList();
                foreach (var gm in Geoms)
                {
                    if (gm.geometryName == null)
                    {
                        gm.geometryName = String.Empty; //Avoid a crash on android from null strings
                    }
                }
                var general = new ReferenceGeometry()
                {
                    geometryName = "Allgemeine Beobachtung"
                };
                AssociatedGeometry.ItemsSource = Geoms;
                AssociatedGeometry.ItemsSource.Insert(0, general);
                AssociatedGeometry.ItemDisplayBinding = new Binding("geometryName");
                AssociatedGeometry.TypeId             = -999;

                if (queriedrec.geometry_fk != null)
                {
                    var geom = ReferenceGeometry.GetGeometry((int)queriedrec.geometry_fk);
                    var selectedGeomIndex = Geoms.FindIndex(a => a.Id == geom.Id);
                    AssociatedGeometry.SelectedIndex = selectedGeomIndex++;
                }
                else
                {
                    AssociatedGeometry.SelectedIndex = 0;
                }
                AssociatedGeometry.Margin    = new Thickness(0, 0, 0, 10);
                AssociatedGeometry.IsEnabled = !ReadOnly;
                if (ReadOnly)
                {
                    AssociatedGeometry.SetAppThemeColor(Label.BackgroundColorProperty, Color.FromRgb(0.95, 0.95, 0.95), Color.FromRgb(0.2, 0.2, 0.2));
                }
                AssociatedGeometry.SelectedIndexChanged += DidSelectNewGeometry;

                Assets.Add(AssociatedGeometry);
            }

            var DeleteButton = new Button();

            DeleteCommand              = new Command(OnDelete, ValidateDelete);
            DeleteButton.ImageSource   = "delete.png";
            DeleteButton.Command       = DeleteCommand;
            DeleteButton.Style         = (Style)Xamarin.Forms.Application.Current.Resources["DangerButtonStyle"];
            DeleteButton.Margin        = new Thickness(0, 10);
            DeleteButton.CornerRadius  = 10;
            DeleteButton.TextTransform = TextTransform.Uppercase;
            DeleteButton.WidthRequest  = 50;
            var GUIDButton = new Button();

            GUIDCommand                  = new Command(CopyGUID);
            GUIDButton.Text              = "GUID";
            GUIDButton.BackgroundColor   = (Color)Xamarin.Forms.Application.Current.Resources["BioDivGreen"];
            GUIDButton.Command           = GUIDCommand;
            GUIDButton.HorizontalOptions = LayoutOptions.FillAndExpand;
            GUIDButton.TextColor         = Color.White;
            GUIDButton.Margin            = new Thickness(0, 10);
            GUIDButton.CornerRadius      = 10;
            GUIDButton.TextTransform     = TextTransform.Uppercase;
            GUIDButton.WidthRequest      = 250;
            var buttonLayout = new FlexLayout
            {
                Children =
                {
                    DeleteButton, GUIDButton
                }
            };

            buttonLayout.Direction         = FlexDirection.Row;
            buttonLayout.JustifyContent    = FlexJustify.SpaceAround;
            buttonLayout.HorizontalOptions = LayoutOptions.FillAndExpand;
            buttonLayout.AlignContent      = FlexAlignContent.SpaceAround;

            Assets.Add(buttonLayout);

            SaveCommand           = new Command(OnSave, ValidateSave);
            CancelCommand         = new Command(OnCancel);
            this.PropertyChanged +=
                (_, __) => SaveCommand.ChangeCanExecute();
        }
Beispiel #11
0
        /// <summary>
        /// Based on the current sorting and filtering methods, read the groups into which the records should be sorted, then read the records associated with each of these groups. When reading the records, we also need to know their associated forms and geometries
        /// </summary>
        public void UpdateRecords()
        {
            Activity = true;
            var recs = new List <GroupedFormRec>();

            if (recs != null && SortBy != "Formulartyp")
            {
                if (FilterBy == "Formulartyp")
                {
                    var frm = Form.FetchForm((int)Form_pk);
                    foreach (var group in App.RecordLists.RecordsByGeometry)
                    {
                        var newGroup = new GroupedFormRec();
                        newGroup.LongGeomName  = group.LongGeomName;
                        newGroup.ShortGeomName = group.ShortGeomName;
                        newGroup.GeomId        = group.GeomId;
                        newGroup.ShowButton    = group.ShowButton;
                        newGroup.Geom          = group.Geom;

                        foreach (FormRec form in group)
                        {
                            if (form.FormId == frm.formId)
                            {
                                newGroup.Add(form);
                            }
                        }
                        recs.Add(newGroup);
                    }
                }

                else if (FilterBy == "Geometrie" && Object_pk != null)
                {
                    var obj = ReferenceGeometry.GetGeometry((int)Object_pk);
                    foreach (var group in App.RecordLists.RecordsByGeometry)
                    {
                        try
                        {
                            if (group.GeomId == obj.Id)
                            {
                                recs.Add(group);
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                }
                else
                {
                    recs = App.RecordLists.RecordsByGeometry;
                }
                Records = new ObservableCollection <GroupedFormRec>(recs);
            }
            else if (recs != null && SortBy == "Formulartyp")
            {
                if (FilterBy == "Formulartyp")
                {
                    var frm = Form.FetchForm((int)Form_pk);
                    foreach (var group in App.RecordLists.RecordsByForm)
                    {
                        var newGroup = new GroupedFormRec();
                        newGroup.LongGeomName  = group.LongGeomName;
                        newGroup.ShortGeomName = group.ShortGeomName;
                        newGroup.GeomId        = group.GeomId;
                        newGroup.ShowButton    = group.ShowButton;
                        newGroup.Geom          = group.Geom;

                        foreach (FormRec form in group)
                        {
                            if (form.FormId == frm.formId)
                            {
                                newGroup.Add(form);
                            }
                        }
                        recs.Add(newGroup);
                    }
                }
                else if (FilterBy == "Geometrie" && Object_pk != null)
                {
                    var obj = ReferenceGeometry.GetGeometry((int)Object_pk);
                    foreach (var group in App.RecordLists.RecordsByForm)
                    {
                        var newGroup = new GroupedFormRec();
                        newGroup.LongGeomName  = group.LongGeomName;
                        newGroup.ShortGeomName = group.ShortGeomName;
                        newGroup.GeomId        = group.GeomId;
                        newGroup.ShowButton    = group.ShowButton;
                        newGroup.Geom          = group.Geom;

                        foreach (FormRec form in group)
                        {
                            if (form.GeomId == obj.Id)
                            {
                                newGroup.Add(form);
                            }
                        }
                        recs.Add(newGroup);
                    }
                }
                else
                {
                    recs = App.RecordLists.RecordsByForm;
                }
                Records = new ObservableCollection <GroupedFormRec>(recs);
            }
            else
            {
                Records = new ObservableCollection <GroupedFormRec>();
            }

            OnPropertyChanged("Records");
            Activity = false;
        }
        public static async Task CreateDynamicView(BioDivContext db, ReferenceGeometry rg, ProjectGroup g, List <Group> myGroups, GeometrieViewModel gvm)
        {
            foreach (Record r in rg.Records.Where(m => m.StatusId != StatusEnum.deleted))
            {
                bool isReadOnly = true;
                if (g == null)
                {
                    isReadOnly = false;
                }
                else if ((g.GroupStatusId != GroupStatusEnum.Gruppendaten_gueltig) && (g.GroupStatusId != GroupStatusEnum.Gruppendaten_erfasst))
                {
                    if (myGroups.Where(m => m.GroupId == r.ProjectGroupGroupId).Count() > 0)
                    {
                        isReadOnly = false;
                    }
                }

                RecordViewModel rvm = new RecordViewModel()
                {
                    Record = r
                };

                List <PropertyVm> dynamicForm = new List <PropertyVm>();

                // BDC Guid
                PropertyVm dynamicFieldGUID = new PropertyVm(typeof(string), "Field_" + r.RecordId);
                dynamicFieldGUID.DisplayName         = "BDCGuid";
                dynamicFieldGUID.Value               = r.BDCGuid;
                dynamicFieldGUID.GetCustomAttributes = () => new object[] { new Helpers.FormFactory.GuidAttribute() };
                dynamicForm.Add(dynamicFieldGUID);

                if (r.Form != null)
                {
                    foreach (FormField ff in r.Form.FormFormFields.Select(fff => fff.FormField).OrderBy(m => m.Order))
                    {
                        FormField origFormField = ff;
                        if (ff.PublicMotherFormField != null)
                        {
                            origFormField = ff.PublicMotherFormField;
                        }

                        if (origFormField.FieldTypeId == FieldTypeEnum.Text)
                        {
                            PropertyVm dynamicField = new PropertyVm(typeof(string), "Field_" + ff.FormFieldId.ToString());
                            dynamicField.DisplayName = origFormField.Title;
                            TextData td = r.TextData.Where(m => m.FormField == ff).FirstOrDefault();
                            if (td != null)
                            {
                                dynamicField.Value = td.Value;
                            }

                            dynamicField.NotOptional = ff.Mandatory;
                            dynamicForm.Add(dynamicField);
                        }
                        else if (origFormField.FieldTypeId == FieldTypeEnum.DateTime)
                        {
                            PropertyVm dynamicField = new PropertyVm(typeof(DateTime), "Field_" + ff.FormFieldId.ToString());
                            dynamicField.DisplayName = origFormField.Title;
                            TextData td   = r.TextData.Where(m => m.FormField == ff).FirstOrDefault();
                            DateTime myDT = new DateTime();
                            try
                            {
                                myDT = DateTime.ParseExact(td.Value.Replace("{0:", " ").Replace("}", ""), formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
                            }
                            catch (Exception e)
                            {
                            }

                            if (td != null)
                            {
                                dynamicField.Value = myDT;
                            }

                            dynamicField.NotOptional = ff.Mandatory;
                            dynamicForm.Add(dynamicField);
                        }
                        else if (origFormField.FieldTypeId == FieldTypeEnum.Choice)
                        {
                            PropertyVm dynamicField = new PropertyVm(typeof(string), "Field_" + ff.FormFieldId.ToString());
                            dynamicField.DisplayName = origFormField.Title;
                            TextData td = r.TextData.Where(m => m.FormField == ff).FirstOrDefault();
                            if (td != null)
                            {
                                dynamicField.Value = td.Value;
                            }

                            await db.Entry(origFormField).Collection(m => m.FieldChoices).LoadAsync();

                            if (origFormField.FieldChoices != null)
                            {
                                List <string> choices = new List <string>();
                                foreach (FieldChoice fc in origFormField.FieldChoices.OrderBy(m => m.Order))
                                {
                                    choices.Add(fc.Text);
                                }
                                dynamicField.Choices = choices;
                            }
                            dynamicField.NotOptional = ff.Mandatory;
                            dynamicForm.Add(dynamicField);
                        }
                        else if (origFormField.FieldTypeId == FieldTypeEnum.Boolean)
                        {
                            PropertyVm dynamicField = new PropertyVm(typeof(bool), "Field_" + ff.FormFieldId.ToString());
                            dynamicField.DisplayName = origFormField.Title;
                            BooleanData bd = r.BooleanData.Where(m => m.FormField == ff).FirstOrDefault();
                            if (bd != null)
                            {
                                dynamicField.Value = bd.Value;
                            }
                            dynamicField.NotOptional         = ff.Mandatory;
                            dynamicField.GetCustomAttributes = () => new object[] { new FormFactory.Attributes.LabelOnRightAttribute() };
                            dynamicForm.Add(dynamicField);
                        }
                    }

                    PropertyVm dynamicHiddenField = new PropertyVm(typeof(string), "RecordId");
                    dynamicHiddenField.Value       = r.RecordId.ToString();
                    dynamicHiddenField.NotOptional = true;
                    dynamicHiddenField.IsHidden    = true;
                    dynamicForm.Add(dynamicHiddenField);

                    if (isReadOnly)
                    {
                        foreach (PropertyVm pv in dynamicForm)
                        {
                            pv.Readonly = true;
                        }
                    }
                    rvm.Readonly    = isReadOnly;
                    rvm.DynamicForm = dynamicForm;
                    rvm.Group       = r.ProjectGroup.Group;
                    gvm.Records.Add(rvm);
                }
            }

            return;
        }
        public async Task <IActionResult> AddToGeometry(Guid GeometryId, Guid ProjectId, Guid GroupId, int FormId, bool CopyFromLast = false)
        {
            User         user     = Helpers.UserHelper.GetCurrentUser(User, db);
            List <Group> myGroups = await db.Groups.Where(m => m.GroupUsers.Any(u => u.UserId == user.UserId)).ToListAsync();

            List <Project> projects = new List <Project>();

            if (User.IsInRole("DM"))
            {
                projects = await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.DM);
            }

            if (User.IsInRole("EF"))
            {
                projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.EF));
            }
            if (User.IsInRole("PK"))
            {
                projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PK));
            }
            if (User.IsInRole("PL"))
            {
                projects.AddRange(await DB.Helpers.ProjectManager.UserProjectsAsync(db, user, RoleEnum.PL));
            }


            ReferenceGeometry rg = await db.Geometries.FindAsync(GeometryId);

            Form f = await db.Forms.FindAsync(FormId);

            // Check if correct rights for user
            if ((myGroups.Any(m => m.GroupId == GroupId)) && (projects.Any(m => m.ProjectId == ProjectId)) && (rg != null) && (f != null))
            {
                Record r = new Record()
                {
                    Form = f, Geometry = rg, ProjectGroupGroupId = GroupId, ProjectGroupProjectId = ProjectId
                };
                ChangeLog cl = new ChangeLog()
                {
                    Log = "created new record", User = user
                };
                db.ChangeLogs.Add(cl);
                ChangeLogRecord clr = new ChangeLogRecord()
                {
                    ChangeLog = cl, Record = r
                };
                db.ChangeLogsRecords.Add(clr);
                db.Records.Add(r);
                await db.SaveChangesAsync();

                if (CopyFromLast)
                {
                    CopyRecordFromLastEntry(r, f, user);
                }
                await db.SaveChangesAsync();

                return(Content("OK"));
            }


            return(StatusCode(403));
        }
Beispiel #14
0
 public abstract Task <IViewComponentResult> InvokeAsync(ReferenceGeometry referenceGeometry);