Esempio n. 1
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Campus campus;
            CampusService campusService = new CampusService();

            int campusId = int.Parse( hfCampusId.Value );

            if ( campusId == 0 )
            {
                campus = new Campus();
                campusService.Add( campus, CurrentPersonId );
            }
            else
            {
                campus = campusService.Get( campusId );
            }

            campus.Name = tbCampusName.Text;
            campus.ShortCode = tbCampusCode.Text;

            if ( !campus.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            RockTransactionScope.WrapTransaction( () =>
            {
                campusService.Save( campus, CurrentPersonId );
            } );

            NavigateToParentPage();
        }
Esempio n. 2
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="campusId">The campus identifier.</param>
        public void ShowDetail( int campusId )
        {
            pnlDetails.Visible = true;

            // Load depending on Add(0) or Edit
            Campus campus = null;

            if ( !campusId.Equals( 0 ) )
            {
                campus = new CampusService( new RockContext() ).Get( campusId );
                lActionTitle.Text = ActionTitle.Edit(Campus.FriendlyTypeName).FormatAsHtmlTitle();
            }

            if ( campus == null )
            {
                campus = new Campus { Id = 0 };
                lActionTitle.Text = ActionTitle.Add( Campus.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            hfCampusId.Value = campus.Id.ToString();
            tbCampusName.Text = campus.Name;
            cbIsActive.Checked = !campus.IsActive.HasValue || campus.IsActive.Value;
            tbDescription.Text = campus.Description;
            tbUrl.Text = campus.Url;
            tbPhoneNumber.Text = campus.PhoneNumber;
            acAddress.SetValues( campus.Location );

            tbCampusCode.Text = campus.ShortCode;
            ppCampusLeader.SetValue( campus.LeaderPersonAlias != null ? campus.LeaderPersonAlias.Person : null );
            kvlServiceTimes.Value = campus.ServiceTimes;

            campus.LoadAttributes();
            phAttributes.Controls.Clear();
            Rock.Attribute.Helper.AddEditControls( campus, phAttributes, true, BlockValidationGroup );

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Campus.FriendlyTypeName );
            }

            if ( campus.IsSystem )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Campus.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( Campus.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            tbCampusName.ReadOnly = readOnly;
            btnSave.Visible = !readOnly;
        }
        public ActionResult Edit(Campus model)
        {
            if (model.CampusID > 0) {
                // EDIT MODE
                try {
                    model = db.Campuses.Find(model.CampusID);

                    UpdateModel(model);

                    db.SaveChanges();

                    //return RedirectToAction("Campuses", new { id = model.ID });
                    return RedirectToAction("Index");
                } catch (Exception) {
                    ModelState.AddModelError("", "Edit Failure, see inner exception");
                }

                return View(model);
            } else {

                // ADD MODE
                if (ModelState.IsValid) {
                    db.Campuses.Add(model);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                } else {
                    return View(model);
                }
            }
        }
        public ActionResult Edit(int? id)
        {
            Campus campus = db.Campuses.SingleOrDefault(s => s.CampusID == id);
            if (campus == null)
                campus = new Campus() { CampusID = 0 };

            return View(campus);
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            // return if unexpected itemKey
            if ( itemKey != "campusId" )
            {
                return;
            }

            pnlDetails.Visible = true;

            // Load depending on Add(0) or Edit
            Campus campus = null;
            if ( !itemKeyValue.Equals( 0 ) )
            {
                campus = new CampusService( new RockContext() ).Get( itemKeyValue );
                lActionTitle.Text = ActionTitle.Edit(Campus.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                campus = new Campus { Id = 0 };
                lActionTitle.Text = ActionTitle.Add(Campus.FriendlyTypeName).FormatAsHtmlTitle();
            }

            hfCampusId.Value = campus.Id.ToString();
            tbCampusName.Text = campus.Name;
            tbCampusCode.Text = campus.ShortCode;
            tbPhoneNumber.Text = campus.PhoneNumber;
            ppCampusLeader.SetValue( campus.LeaderPersonAlias != null ? campus.LeaderPersonAlias.Person : null );

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if ( !IsUserAuthorized( Authorization.EDIT ) )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( Campus.FriendlyTypeName );
            }

            if ( campus.IsSystem )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem( Campus.FriendlyTypeName );
            }

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( Campus.FriendlyTypeName );
                btnCancel.Text = "Close";
            }

            tbCampusName.ReadOnly = readOnly;
            btnSave.Visible = !readOnly;
        }
Esempio n. 6
0
        public ActionResult Create(Campus campus)
        {
            if (ModelState.IsValid)
            {
                db.Campus.Add(campus);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(campus);
        }
        public IHttpActionResult Insert(Campus campus)
        {
            _loggerService.CreateLog(_user, "API", "CampusController", "Campus", "Insert", campus.ToString(), null);
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var createdCampus = _campusRepository.InsertCampus(campus);

            if (createdCampus == null)
            {
                BadRequest("There was a problem inserting your record. Please try again.");
            }

            return(Created($"api/campus?id={createdCampus.Id}", createdCampus));
        }
Esempio n. 8
0
        /// <summary>
        /// Binds the attributes.
        /// </summary>
        private void BindAttributes()
        {
            // Parse the attribute filters
            AvailableAttributes = new List <AttributeCache>();

            int entityTypeId = new Campus().TypeId;

            foreach (var attributeModel in new AttributeService(new RockContext()).Queryable()
                     .Where(a =>
                            a.EntityTypeId == entityTypeId &&
                            a.IsGridColumn)
                     .OrderBy(a => a.Order)
                     .ThenBy(a => a.Name))
            {
                AvailableAttributes.Add(AttributeCache.Get(attributeModel));
            }
        }
Esempio n. 9
0
 public IActionResult Edit(CampusEditViewModel viewModel)
 {
     if (!ModelState.IsValid)
     {
         return(View(viewModel));
     }
     else
     {
         string uniqueFileName = null;
         if (viewModel.Photos != null && viewModel.Photos.Count > 0)
         {
             foreach (IFormFile photo in viewModel.Photos)
             {
                 var extension = Path.GetExtension(photo.FileName).ToLower();
                 if (extension == ".jpg" || extension == ".jpeg" || extension == ".png")
                 {
                     string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");
                     uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                     string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                     photo.CopyTo(new FileStream(filePath, FileMode.Create));
                 }
                 else
                 {
                     throw new Exception("Dosya türü .JPG , .JPEG veya .PNG olmalıdır..");
                 }
             }
         }
         Campus editedCampus = new Campus()
         {
             Id             = viewModel.Id,
             Name           = viewModel.Name,
             Description    = viewModel.Description,
             EditorContent  = viewModel.EditorContent,
             ImageUrl       = uniqueFileName,
             StatusId       = viewModel.StatusId,
             Address        = viewModel.Address,
             Telephone      = viewModel.Telephone,
             EmailAddress   = viewModel.EmailAddress,
             Fax            = viewModel.Fax,
             EditDate       = DateTime.Now,
             EditorMemberId = 1
         };
         _campusService.Edit(editedCampus);
         return(RedirectToAction("Index"));
     }
 }
Esempio n. 10
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Campus campus = db.Campuses.Find(id);

            if (campus == null)
            {
                return(HttpNotFound());
            }
            var state = States();

            campus.States = GetStatesListItems(state);
            return(View(campus));
        }
Esempio n. 11
0
        /// <summary>
        /// 插入Campus
        /// </summary>
        /// <param name="campus">Campus</param>
        public int InsertCampus(Campus campus)
        {
            int _id = -1;

            try
            {
                //_daoManager.BeginTransaction();
                _id = _campusDao.InsertCampus(campus);
                //_daoManager.CommitTransaction();
            }
            catch (Exception ex)
            {
                //_daoManager.RollBackTransaction();
                throw ex;
            }
            return(_id);
        }
Esempio n. 12
0
 //Filter unit timetable by campus
 private void CampusSorter_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (UnitClassTimes != null)
     {
         UnitController UnitBoss = (UnitController)Application.Current.FindResource("UnitBoss");
         if (UnitClassTimes.Count != 0)
         {
             UnitClassGrid.Items.Clear();
             Campus           cam = (Campus)e.AddedItems[0];
             List <UnitClass> SortedUnitClassTimes = UnitBoss.Filter(cam, UnitClassTimes);
             foreach (UnitClass Classes in SortedUnitClassTimes)
             {
                 UnitClassGrid.Items.Add(Classes);
             }
         }
     }
 }
        private static void Main()
        {
            IList<Campus> campuses = new List<Campus>();

            Console.Clear();
            Console.WriteLine();

            // Create a new campus
            Campus campus0 = new Campus("city0","region0",4);
            campuses.Add(campus0);
            Console.WriteLine("[New campus created : campus0]");
            Console.WriteLine(campus0.ToString());
            Console.WriteLine();

            // Create a registered (id != 0) student and add it to this campus
            Student student1 = new Student("foo1","bar1",1);
            Console.WriteLine("[New student created : student1]");
            Console.WriteLine(student1.ToString());
            Console.WriteLine();

            Console.WriteLine(campus0.AddStudent(student1)
                                  ? "[student1 added to campus0]"
                                  : "[student1 not added to campus0]");

            Console.WriteLine("[ordered list of students in campus0] - list's size : "+campus0.Students.Count());
            foreach (var student in campus0.Students)
                Console.WriteLine(student.ToString());
            Console.WriteLine();

            // Exporting list of created campuses to xml files
            // You will be able to retrieve thoses files in this application's directory under bin/Debug/ or bin/Release/
            XmlSerializer serializer = new XmlSerializer(typeof(Campus));
            // write
            foreach (var campus in campuses)
                using (var stream = File.Create(campus.City + "_" + campus.Region + ".xml"))
                    serializer.Serialize(stream, campus);

            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            Console.WriteLine("Xml files created under ["+path+"] with the following rule : campusCity_campusRegion.xml for each campuses.");
            Console.WriteLine();

            // Prevent automatic closing of the output window, waiting for the user to press enter ...
            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
Esempio n. 14
0
        public SessionTrackerMainForm(IDatabase database, IMessageHandler messageHandler, string cookie, Campus campus)
        {
            InitializeComponent();

            this.activeCookie       = cookie;
            this.activeCampus       = campus;
            this.database           = database;
            this.messageHandler     = messageHandler;
            this.dataReader         = new DatabaseReader();
            this.dataWriter         = new DatabaseWriter();
            this.signInDataBuffer   = new BindingList <SignInData>();
            this.loggedSessionCache = new HashSet <SignInData>();

            this.Text = $"Session Tracker - {this.activeCampus.Name}";

            this.InitializeDataGridView();
            this.StartBackgroundWorker();
        }
Esempio n. 15
0
 private void CampFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (this.TimeTable_Grid != null)
     {
         //Get selected index
         int selInt = CampFilter.SelectedIndex;
         //get selection as Category enum
         Campus selCamp = (Campus)selInt;
         if (selInt != 0)
         {
             this.TimeTable_Grid.ItemsSource = Listcontroler.FilterClassListByCampus(UnfilteredTimeTable, selCamp);
         }
         else
         {
             this.TimeTable_Grid.ItemsSource = UnfilteredTimeTable;
         }
     }
 }
Esempio n. 16
0
        public Campus InsertCampus(Campus campus)
        {
            try
            {
                campus.CreatedDateTime = DateTime.Now;
                db.Campus.Add(campus);
                db.SaveChanges();

                _loggerService.CreateLog("Jordan", "Campus", "Create", campus.ToString());

                return(campus);
            }
            catch (Exception e)
            {
                _loggerService.CreateLog("Jordan", "Campus", "Create", campus.ToString(), "Error creating this record: " + e.Message);
                return(null);
            }
        }
        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <param name="obj">The object to compare with the current object.</param>
        /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            var result = false;

            if (obj is CheckpointDTO item)
            {
                result  = ID == item.ID;
                result &= IP.Equals(item.IP);
                result &= Campus.Equals(item.Campus);
                result &= Row.Equals(item.Row);
                result &= Description.Equals(item.Description);
                result &= Status.Equals(item.Status);
                result &= Type.Equals(item.Type);
                result &= Admissions.Equals(item.Admissions);
                return(result);
            }
            return(false);
        }
Esempio n. 18
0
 public int RegistrationRules(User user, Campus campus)
 {
     try
     {
         if (user.Name.Equals(string.Empty))
         {
             return(1);
         }
         else if (user.LastName.Equals(string.Empty))
         {
             return(2);
         }
         else if (user.Username.Equals(string.Empty))
         {
             return(3);
         }
         else if (user.Password.Equals(string.Empty))
         {
             return(4);
         }
         else if (user.UniversityCard.Equals(string.Empty))
         {
             return(6);
         }
         else if (campus.Id.Equals(string.Empty))
         {
             return(7);
         }
         else if (campus.Name.Equals(string.Empty))
         {
             return(8);
         }
         else
         {
             userData.InsertUser(user, campus);
             return(0);
         }
     }
     catch (SqlException)
     {
         return(5);
     }
 }
        public async Task <IActionResult> EditChurch(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Church church = await _context.Churchs.FindAsync(id);

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

            Campus campus = await _context.Campuses.FirstOrDefaultAsync(d => d.Churchs.FirstOrDefault(c => c.Id == church.Id) != null);

            church.IdCampus = campus.Id;
            return(View(church));
        }
Esempio n. 20
0
        public bool UpdateAsync(Campus model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model不能为null");
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException("Name不能为null");
            }

            if (model.Id <= 0)
            {
                throw new ArgumentException("Id错误");
            }

            return(_campusRepository.UpdateAsync(model));
        }
        public async Task <IActionResult> EditCampus(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Campus campus = await _context.Campuses.FindAsync(id);

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

            District district = await _context.Districts.FirstOrDefaultAsync(c => c.Campuses.FirstOrDefault(d => d.Id == department.Id) != null);

            campus.IdDistrict = district.Id;
            return(View(campus));
        }
Esempio n. 22
0
        public bool DeleteCampus(int campusID)
        {
            try
            {
                Campus cs = context.Campus.Where(c => c.CampusID == campusID).FirstOrDefault();

                if (cs != null)
                {
                    context.Campus.Remove(cs);
                    context.SaveChanges();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                logs.Error("An error occurred deleting the Campus with CampusID: " + campusID, ex);
            }
            return(false);
        }
Esempio n. 23
0
        /// <summary>
        /// Raised when a datasource is binded to the cities ASP.NET Repeater.
        /// Get the subrepeater to link the campus's projects.
        /// </summary>
        /// <param name="sender">Element which raised the event.</param>
        /// <param name="repeaterItemEventArgs">Event arguments</param>
        protected void repeaterCampuses_ItemDataBound(object sender, RepeaterItemEventArgs repeaterItemEventArgs)
        {
            Campus campus = repeaterItemEventArgs.Item.DataItem as Campus;

            if (campus != null)
            {
                IEnumerable <Project> projects = (from pv in _projectsCampuses
                                                  where pv.Campus == campus
                                                  select pv).First().Projects;

                Repeater subrepeater = (repeaterItemEventArgs.Item.FindControl("repeaterProjects") as Repeater);

                if (subrepeater != null)
                {
                    subrepeater.DataSource = projects;
                    subrepeater.DataBind();
                }
            }
        }
Esempio n. 24
0
 public int UpdateCampus(Campus campus)
 {
     try
     {
         if (campus.Name.Equals(string.Empty))
         {
             return(1);
         }
         else
         {
             campusData.UpdateCampus(campus);
             return(0);
         }
     }
     catch (SqlException)
     {
         return(2);
     }
 }
Esempio n. 25
0
        private SignInData BuildDataRow(JToken element, Campus campus)
        {
            string currentCampusName = element[(int)Constants.JsonDataIndex.Campus].ToString();

            if (!string.IsNullOrEmpty(currentCampusName))
            {
                if (currentCampusName == campus.Name)
                {
                    return(new SignInData(
                               element[(int)Constants.JsonDataIndex.Center].ToString(),
                               element[(int)Constants.JsonDataIndex.Campus].ToString(),
                               this.ExtractStudentID(element[(int)Constants.JsonDataIndex.StudentID].ToString()),
                               element[(int)Constants.JsonDataIndex.StudentName].ToString(),
                               this.ExtractCourseName(element[(int)Constants.JsonDataIndex.Course].ToString())
                               ));
                }
            }

            return(null);
        }
Esempio n. 26
0
        public void InsertUser(User user, Campus campus)
        {
            SqlConnection connection = ManageDatabaseConnection("Open");

            using (SqlCommand insert = new SqlCommand(@"InsertUser", connection))
            {
                insert.CommandType = CommandType.StoredProcedure;
                insert.Parameters.Add("@Name", SqlDbType.VarChar).Value       = user.Name;
                insert.Parameters.Add("@LastName", SqlDbType.VarChar).Value   = user.LastName;
                insert.Parameters.Add("@UserName", SqlDbType.VarChar).Value   = user.Username;
                insert.Parameters.Add("@Password", SqlDbType.VarChar).Value   = EncryptPassword(user.Password);
                insert.Parameters.Add("@RoleId", SqlDbType.Int).Value         = user.Role.Id;
                insert.Parameters.Add("@RoleName", SqlDbType.VarChar).Value   = user.Role.Name;
                insert.Parameters.Add("@UniversityCard", SqlDbType.Int).Value = user.UniversityCard;
                insert.Parameters.Add("@CampusId", SqlDbType.Int).Value       = campus.Id;
                insert.Parameters.Add("@CampusName", SqlDbType.VarChar).Value = campus.Name;
                insert.ExecuteNonQuery();
            }
            connection = ManageDatabaseConnection("Close");
        }
Esempio n. 27
0
        public int FetchOrCreateCampusId(string name)
        {
            var c = Campus.SingleOrDefault(pp => pp.Description == name);

            if (c == null)
            {
                var max = 10;
                if (Campus.Any())
                {
                    max = Campus.Max(mm => mm.Id) + 10;
                }
                c = new Campu()
                {
                    Id = max, Description = name, Code = name.Truncate(20)
                };
                Campus.InsertOnSubmit(c);
                SubmitChanges();
            }
            return(c.Id);
        }
Esempio n. 28
0
    protected void btnOK_Click(object sender, EventArgs e)
    {
        try
        {
            string result = new Campus().deleteCampus(code);

            if (result == "OK")
            {
                Response.Redirect("list_Campus.aspx");
            }
            else
            {
                Response.Redirect("list_Campus.aspx");
            }
        }
        catch
        {
            Response.Redirect("list_Campus.aspx");
        }
    }
Esempio n. 29
0
        public HttpResponseMessage CreateCampus(Campus campus)
        {
            dbcontext.Campuses.Add(campus);
            try
            {
                dbcontext.SaveChanges();
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex));
            }

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, campus);

            response.StatusCode = HttpStatusCode.Created;

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            return(response);
        }
Esempio n. 30
0
        public bool InsertAsync(Campus model)
        {
            using (var conn = DapperFactory.GetConnection())
            {
                var fields = model.ToFields(removeFields: new List <string> {
                    "Id"
                });
                if (fields == null || fields.Count == 0)
                {
                    return(false);
                }

                model.CreateTime = DateTime.Now;
                model.ModifyTime = DateTime.Now;
                model.Status     = 1;

                string sql = string.Format("insert into [Campus] ({0}) values ({1});", string.Join(",", fields), string.Join(",", fields.Select(n => "@" + n)));
                return(conn.Execute(sql, model) > 0);
            }
        }
        public async Task <IActionResult> AddCampus(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            District district = await _context.Districts.FindAsync(id);

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

            Campus model = new Campus {
                IdDistrict = district.Id
            };

            return(View(model));
        }
Esempio n. 32
0
        public PCOUsage(Campus location, DateTime itemDate, PCOItem songItem, int songSlot)
        {
            this.Location = location;
            this.dates    = new List <DateTime>();
            intializeSlots();
            this.dates.Add(itemDate);
            if (this.slots.ContainsKey(songSlot))
            {
                this.slots[songSlot] += 1;
            }
            else
            {
                this.slots.Add(songSlot, 1);
            }

            this.title      = songItem.SongTitle;
            this.artist     = songItem.SongAuthor;
            this.songID     = songItem.SongID;
            this.ccliNumber = songItem.CCLINumber;
        }
        public async Task <IActionResult> AddChurch(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Campus campus = await _context.Campuses.FindAsync(id);

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

            Church model = new Church {
                IdCampus = campus.Id
            };

            return(View(model));
        }
Esempio n. 34
0
        // ---------
        // Menu-item
        // ---------
        static void Item01()
        {
            using var context = new EFCoreMappingContext();
            var campus = new Campus
            {
                Naam  = "VDAB Wondelgem",
                Adres = new Adres
                {
                    Straat     = "Industrieweg",
                    Huisnummer = "50",
                    Postcode   = "9032",
                    Gemeente   = "Gent"
                }
            };
            var johan = new Docent
            {
                Voornaam       = "Johan",
                Familienaam    = "Vandaele",
                Wedde          = 1000m,
                InDienst       = new DateTime(2016, 2, 1),
                HeeftRijbewijs = true,
                AdresThuis     = new Adres
                {
                    Straat     = "Ter Lake",
                    Huisnummer = "7",
                    Postcode   = "8310",
                    Gemeente   = "Brugge"
                },
                AdresWerk = new Adres
                {
                    Straat     = "Hertsbergsestraat",
                    Huisnummer = "91",
                    Postcode   = "8020",
                    Gemeente   = "Oostkamp"
                },
                Campus = campus
            };

            context.Add(johan);
            context.SaveChanges();
        }
        public async Task <IActionResult> AddChurch(Church church)
        {
            if (ModelState.IsValid)
            {
                Campus campus = await _context.Campuses
                                .Include(d => d.Churchs)
                                .FirstOrDefaultAsync(c => c.Id == church.IdCampus);

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

                try
                {
                    church.Id = 0;
                    campus.Churchs.Add(church);
                    _context.Update(campus);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction($"{nameof(DetailsCampus)}/{campus.Id}"));
                }
                catch (DbUpdateException dbUpdateException)
                {
                    if (dbUpdateException.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "There are a record with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, dbUpdateException.InnerException.Message);
                    }
                }
                catch (Exception exception)
                {
                    ModelState.AddModelError(string.Empty, exception.Message);
                }
            }

            return(View(church));
        }
Esempio n. 36
0
        public async Task <ActionResult> Create(CampusViewModel campusViewModel)
        {
            var existingCampus = await _campusService.FindByCode(campusViewModel.Code);


            if (existingCampus == null)
            {
                var campus = new Campus
                {
                    Name = campusViewModel.Name,
                    Code = campusViewModel.Code
                };
                await _campusService.Create(campus);

                return(Ok());
            }
            else
            {
                return(BadRequest("Ya existe un campus con este codigo"));
            }
        }
Esempio n. 37
0
        protected void InsertCampus(Campus campus)
        {
            if (campus != null)
            {
                switch (campusRules.InsertCampus(campus))
                {
                case 0:
                    textboxCampus.Value = "";
                    buttonStyle.buttonStyleBlue(buttonErrors, "Campus added successful.");
                    break;

                case 1:
                    buttonStyle.buttonStyleWhite(buttonErrors, "Campus name field is empty.");
                    break;

                case 2:
                    buttonStyle.buttonStyleRed(buttonErrors, "An error ocurred creating the campus, please check data or contact we us.");
                    break;
                }
            }
        }
Esempio n. 38
0
        public IActionResult Edit(Campus campus)
        {
            if (ModelState.IsValid)
            {
                db.Update(campus);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(campus);
        }
 private void CopyPerCampus(Campus campus)
 {
     CopyMails(_personen.Where(p => p.Campus == campus), appendIT: true);
 }
Esempio n. 40
0
        /// <summary>
        /// Saves a Campus to the Rock instance.  If the <see cref="campusId"/> is null, an add will be attempted, otherwise an update will be attempted.
        /// </summary>
        /// <param name="isSystem">A <see cref="System.Boolean"/> value that is <c>true<c> if the Campus is a system generated value.</param>
        /// <param name="name">A <see cref="System.String"/> representing the unique name of the campus..</param>
        /// <param name="shortCode">A <see cref="System.String"/> representing the optional short code for the campus. Defaults to null.</param>
        /// <param name="locationId">A nullable <see cref="System.Int32"/> that represents the LcoationId  of the <see cref="Rock.Model.Location"/> that is associated with the campus. Defaults to null.</param>
        /// <param name="phoneNumber">A <see cref="System.String"/> representing the phone number of the campus. Defaults to null.</param>
        /// <param name="leaderPersonAliasId">A <see cref="System.Int32"/> that represents the PersonAliasId of a <see cref="Rock.Model.PersonAlias"/> that is associated with the <see cref="Rock.Model.Person"/>
        /// who is the leader of the campus.</param>
        /// <param name="serviceTimes">A <see cref="System.String"/> representing a delimited list of service times for the campus.</param>
        /// <param name="foreignId">A <see cref="System.String"/> representing the identifier of the Campus in the foreign system that it was imported from.</param>
        /// <param name="campusId">A nullable <see cref="System.Int32"/> representing the internal Campus Identifier (primary key) of the campus. This will allow for the support of updates.</param>
        /// <returns>A nullable <see cref="System.Int32"/> representing the Id of the campus that was either added or updated. Will be null if an update is attempted and the campus was not found. </returns>
        public int? SaveCampus(bool isSystem, string name, string shortCode = null, int? locationId = null, string phoneNumber = null,  int? leaderPersonAliasId = null, string serviceTimes = null, string foreignId = null, int? campusId = null )
        {
            Campus c = null;

            CampusController controller = new CampusController( Service );

            if ( campusId == null || campusId <= 0 )
            {
                c = new Campus();
            }
            else
            {
                c = controller.GetById( (int)campusId );
            }

            // Update was attempted and campus was not found in Arena instance.
            if ( c == null )
            {
                return null;
            }

            c.IsSystem = isSystem;
            c.Name = name;
            c.ShortCode = shortCode;
            c.LocationId = locationId;
            c.LeaderPersonAliasId = leaderPersonAliasId;
            c.PhoneNumber = phoneNumber;
            c.ServiceTimes = serviceTimes;
            c.ForeignId = foreignId;
            c.IsActive = true;

            if ( c.Id > 0 )
            {
                c.ModifiedByPersonAliasId = Service.LoggedInPerson.PrimaryAliasId;
                controller.Update(c);
            }
            else
            {
                c.CreatedByPersonAliasId = Service.LoggedInPerson.PrimaryAliasId;
                controller.Add( c );
            }

            c = controller.GetByGuid( c.Guid );

            GetCampuses( true );
            return c.Id;
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="campus">Campus</param>
 /// <param name="conferences">Conferences to associate to the campus</param>
 public CampusConferences(Campus campus, IEnumerable<Conference> conferences)
 {
     Campus = campus;
     Conferences = conferences;
 }
Esempio n. 42
0
        public void PopulateDatabaseFromUnpivotedStaarTestDirectory(string parsedFilesDirectory, string logPath)
        {
            var completed = _ctx.StaarTests
                        .GroupBy(s => new
                        {
                            s.Year,
                            Subject = s.Subject.Name,
                            s.Grade,
                            s.Language.Name
                        })
                        .Select(s => new Complete
                        {
                            Year = s.Key.Year,
                            SubjectName = s.Key.Subject,
                            Grade = s.Key.Grade,
                            Language = s.Key.Name
                        }).ToList();
            var firstTime = true;
            string previousSubject = "",
                previousDemographic = "",
                previousCategory = "";
            var subject = new Subject();
            var dd = new DemographicDetail();
            var cd = new CategoryDetail();
            var log = File.CreateText(logPath);
            //     0        1       2       3           4       5       6       7               8       9           10          11    
            //     CAMPUS	YEAR	REGION	DISTRICT	DNAME	CNAME	Grade	LanguageEnum	Subject	Demographic	Category	Value


            foreach (var unzippedFile in Directory.GetFiles(parsedFilesDirectory, "*.csv", SearchOption.TopDirectoryOnly))
            {
                #region initialize

                var dems = new List<DemographicDetail>();
                var cats = new List<CategoryDetail>();
                var subjs = new List<Subject>();
                var camps = new List<Campus>();
                var dists = new List<District>();
                var regs = new List<Region>();
                var availableLanguages = new List<Language>();

                #endregion
                try
                {
                    var testsToAdd = new List<StaarTest>(90005);


                    //enumerate through file and grab rows we need.

                    List<string[]> testsNotInDb;
                    try
                    {
                        testsNotInDb = File.ReadLines(unzippedFile)
                        .Select(row => row.Split(','))
                        .Where(row => completed.All(c =>
                            c.Grade != row[6] &&
                            c.SubjectName != row[8] &&
                            c.Language != row[7] &&
                            c.Year.ToString().Substring(2, 2) != row[1]))
                        .ToList();
                        testsNotInDb.RemoveAt(0);

                        if (testsNotInDb.Count == 0)
                        {
                            log.WriteLine("{0} has had all recordes uploaded already", unzippedFile);
                            continue;
                        }
                        if (testsNotInDb[0].Length != 12)
                        {
                            log.WriteLine("{0} is not in the format of a parsed file", unzippedFile);
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.WriteLine("An error occured reading from {0}. The error is: {1}", unzippedFile, ex.Message);
                        continue;
                    }



                    //by this point, we know we have to know things

                    if (firstTime)
                    {
                        dems = _ctx.DemographicDetails.ToList();
                        cats = _ctx.CategoryDetails.ToList();
                        subjs = _ctx.Subjects.ToList();
                        camps = _ctx.Campuses.ToList();
                        dists = _ctx.Districts.ToList();
                        regs = _ctx.Regions.ToList();
                        availableLanguages = _ctx.Languages.ToList();
                        firstTime = false;
                    }


                    //get bits from file

                    var sortedCount = testsNotInDb.Count;
                    var fileLanguage = availableLanguages.Single(l => l.Name == testsNotInDb[0][7]);

                    var fileYear = int.Parse(testsNotInDb[0][1]);
                    if (fileYear >= 90 && fileYear < 100) fileYear += 1900;
                    else if (fileYear < 90) fileYear += 2000;


                    #region add all campuses first

                    var campusGroups = testsNotInDb.GroupBy(s => new
                    {
                        CampusNumber = Convert.ToInt32(s[0]),
                        Year = s[1],
                        RegionNumber = Convert.ToInt32(s[2]),
                        DistrictNumber = Convert.ToInt32(s[3]),
                        Dname = s[4],
                        Cname = s[5],

                    })
                        .Select(s => new
                        {
                            s.Key.CampusNumber,
                            s.Key.Year,
                            s.Key.RegionNumber,
                            s.Key.DistrictNumber,
                            s.Key.Dname,
                            s.Key.Cname
                        }).ToList();

                    var newRegs = new List<Region>();
                    var newDist = new List<District>();
                    var newCamps = new List<Campus>();

                    foreach (var campusGroup in campusGroups)
                    {
                        //Find the school. Create if not new

                        var campusNum = campusGroup.CampusNumber;
                        var regionNum = campusGroup.RegionNumber;
                        var districtNum = campusGroup.DistrictNumber;


                        //check region, district, and campus

                        var region = regs.FirstOrDefault(r => r.Number == regionNum);
                        if (region == null)
                        {
                            region = new Region
                            {
                                Name = string.Format("Region {0}", regionNum),
                                Number = regionNum
                            };
                            regs.Add(region);
                            newRegs.Add(region);
                        }

                        var district = dists.FirstOrDefault(r => r.Number == districtNum);
                        if (district == null)
                        {
                            district = new District
                            {
                                Name = campusGroup.Dname,
                                Number = districtNum,
                                Region = region
                            };
                            dists.Add(district);
                            newDist.Add(district);
                        }

                        var campus = camps.FirstOrDefault(r => r.Number == campusNum);
                        if (campus == null)
                        {
                            campus = new Campus
                            {
                                Name = campusGroup.Cname,
                                Number = campusNum,
                                District = district
                            };
                            camps.Add(campus);
                            newCamps.Add(campus);
                        }

                    }
                    _ctx.Regions.AddRange(newRegs);
                    _ctx.Districts.AddRange(newDist);
                    _ctx.Campuses.AddRange(newCamps);
                    _ctx.SaveChanges();

                    #endregion


                    #region go through records

                    for (var i = 0; i < sortedCount; i++)
                    {
                        var record = testsNotInDb[i];

                        var campusId = camps.First(c => c.Number == Convert.ToInt32(record[0])).Id;

                        //get new stuff

                        if (previousSubject != record[8])
                        {
                            subject = subjs.Single(s => s.Name == record[8]);
                        }

                        if (previousDemographic != record[9])
                        {
                            dd = dems.Single(s => s.Detail == record[9]);
                        }

                        if (previousCategory != record[10])
                        {
                            cd = cats.Single(s => s.Detail == record[10]);
                        }


                        //for each complex header whose category matches the current category make a demo and value

                        testsToAdd.Add(new StaarTest
                        {
                            Campus_Id = campusId,
                            CategoryDetail_Id = cd.Id,
                            DemographicDetail_Id = dd.Id,
                            Subject_Id = subject.Id,
                            Year = fileYear,
                            Language_Id = fileLanguage.Id,
                            Value = Convert.ToDecimal(record[11]),
                            Grade = record[6]
                        });

                        if (testsToAdd.Count >= 90000 || i == sortedCount - 1)
                        {
                            _ctx.BulkInsert(testsToAdd);
                            testsToAdd = new List<StaarTest>(90005);
                        }

                        previousSubject = record[8];
                        previousDemographic = record[9];
                        previousCategory = record[10];

                    }

                    #endregion


                    //add processed files to completed

                    var groupedImportsToComplete = testsNotInDb.GroupBy(s => new
                    {
                        Year = fileYear,
                        SubjectName = s[8],
                        Grade = s[6],
                        Langauge = fileLanguage.Name
                    }).Select(i => new Complete
                    {
                        Year = i.Key.Year,
                        SubjectName = i.Key.SubjectName,
                        Grade = i.Key.Grade,
                        Language = i.Key.Langauge
                    }).ToList();
                    completed.AddRange(groupedImportsToComplete);
                    log.WriteLine("{0} successfully uploaded", unzippedFile);


                    //memory management

                    testsNotInDb.Clear();
                    testsNotInDb = null;
                }
                catch (Exception ex)
                {
                    log.WriteLine("{0}\r\n{1}", ex.Message, ex.StackTrace);
                }
            }

            log.Flush();
            log.Close();
        }
Esempio n. 43
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                ShowDetail( PageParameter( "campusId" ).AsInteger() );
            }
            else
            {
                if ( pnlDetails.Visible )
                {
                    var rockContext = new RockContext();
                    Campus campus;
                    string itemId = PageParameter( "campusId" );
                    if ( !string.IsNullOrWhiteSpace( itemId ) && int.Parse( itemId ) > 0 )
                    {
                        campus = new CampusService( rockContext ).Get( int.Parse( PageParameter( "campusId" ) ) );
                    }
                    else
                    {
                        campus = new Campus { Id = 0 };
                    }
                    campus.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( campus, phAttributes, false, BlockValidationGroup );
                }
            }
        }
Esempio n. 44
0
 public ActionResult Edit(Campus campus)
 {
     if (ModelState.IsValid)
     {
         db.Entry(campus).State = EntityState.Modified;
         db.SaveChanges();
         return RedirectToAction("Index");
     }
     return View(campus);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="campus">City</param>
 /// <param name="projects">Projects list of the campus</param>
 public CampusProjects(Campus campus, IEnumerable<Project> projects)
 {
     Campus = campus;
     Projects = projects;
 }
        /// <summary>
        /// 搜尋資料
        /// </summary>
        /// <param name="args"></param>
        private void ProcessSearch(Campus.Windows.MessageArgs args)
        {
            #region 取得學生

            Dictionary<string, StudentRecord> SearchStudentDic = new Dictionary<string, StudentRecord>();
            StringBuilder sb_c = new StringBuilder();
            sb_c.Append("select student.id from student");
            sb_c.Append(" LEFT join class on class.id=student.ref_class_id");

            //取得系統內狀態為(一般 / 延修)之學生
            DataTable dTable = _QueryHelper.Select(sb_c.ToString());
            List<string> StudentList = new List<string>();
            foreach (DataRow row in dTable.Rows)
            {
                StudentList.Add("" + row[0]);
            }

            foreach (StudentRecord stud in Student.SelectByIDs(StudentList))
            {
                if (!SearchStudentDic.ContainsKey(stud.ID))
                {
                    SearchStudentDic.Add(stud.ID, stud);
                }
            }



            #endregion



            List<string> results = new List<string>();
            Regex rx = new Regex(SearEvArgs.Condition, RegexOptions.IgnoreCase);

            #region 社團名稱
            if (SearchClubName.Checked)
            {
                foreach (string each in AllClubDic.Keys)
                {
                    if (rx.Match(AllClubDic[each].ClubName).Success)
                    {
                        if (!results.Contains(each))
                            results.Add(each);
                    }
                }
            }
            #endregion

            #region 社團老師
            if (SearchClubTeacher.Checked)
            {
                foreach (string each in AllClubDic.Keys)
                {
                    if (TeacherDic.ContainsKey(AllClubDic[each].RefTeacherID))
                    {
                        string terName = TeacherDic[AllClubDic[each].RefTeacherID].Name;
                        string Nicname = TeacherDic[AllClubDic[each].RefTeacherID].Nickname;

                        if (rx.Match(terName).Success || rx.Match(Nicname).Success)
                        {
                            if (!results.Contains(each))
                                results.Add(each);
                        }
                    }
                }
            }
            #endregion

            #region 社團學生

            if (SearchStudentName.Checked)
            {
                //取得所有社團參與記錄
                List<SCJoin> list = _AccessHelper.Select<SCJoin>();

                foreach (SCJoin _join in list)
                {
                    if (SearchStudentDic.ContainsKey(_join.RefStudentID))
                    {
                        if (rx.Match(SearchStudentDic[_join.RefStudentID].Name).Success)
                        {
                            //是否為存在系統內的社團資料???
                            if (AllClubDic.ContainsKey(_join.RefClubID))
                            {
                                if (!results.Contains(_join.RefClubID))
                                    results.Add(_join.RefClubID);
                            }
                        }
                    }
                }
            }

            #endregion

            #region 場地
            if (SearchAddress.Checked)
            {
                foreach (string each in AllClubDic.Keys)
                {
                    if (rx.Match(AllClubDic[each].Location).Success)
                    {
                        if (!results.Contains(each))
                            results.Add(each);
                    }
                }
            }
            SearEvArgs.Result.AddRange(results);
            #endregion
        }
        /// <summary>
        /// 設定可搜尋欄位
        /// </summary>
        private MenuButton SetSearchButton(string MenuName, string BoolMenuName, Campus.Configuration.ConfigData cd)
        {
            MenuButton SearchName = SearchConditionMenu[MenuName];
            SearchName.AutoCheckOnClick = true;
            SearchName.AutoCollapseOnClick = false;
            SearchName.Checked = CheckStringIsBool(cd[BoolMenuName]);
            SearchName.Click += delegate
            {
                cd[BoolMenuName] = SearchName.Checked.ToString(); ;
                BackgroundWorker async = new BackgroundWorker();
                async.DoWork += delegate(object sender, DoWorkEventArgs e) { (e.Argument as Campus.Configuration.ConfigData).Save(); };
                async.RunWorkerAsync(cd);
            };

            return SearchName;
        }
Esempio n. 48
0
        protected string UpcomingDiscover(Campus theCampus, string theTitle)
        {
            string upcomingDiscovers = "";

            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);

            List<ContentChannelItem> contentChannelItemsList = new List<ContentChannelItem>();

            var upcoming =
                contentChannelItemService.Queryable().Where(a => a.ContentChannelId == 14 && a.Title.Contains(theTitle) && a.StartDateTime >= DateTime.Now);

            foreach (var x in upcoming)
            {
                x.LoadAttributes();

                var campus = x.AttributeValues["Campus"];

                if (campus.ValueFormatted == theCampus.Name)
                    {
                    contentChannelItemsList.Add(x);
                    }

            }

            foreach (var x in contentChannelItemsList)
            {
                x.LoadAttributes();

                string registrationLink = "";

                if (x.AttributeValues["RegistrationLink"].ValueFormatted != "")
                {
                    registrationLink = String.Format("<a href= \"{0}\">Register Now!</a>",
                        x.AttributeValues["RegistrationLink"].Value);
                }

                upcomingDiscovers += String.Format("Date: {0} at {1}. Location: {2}. {3} <br>", x.StartDateTime.ToShortDateString(),
                    x.StartDateTime.ToShortTimeString(), x.AttributeValues["Location"], registrationLink);
            }

            if (!contentChannelItemsList.Any())
            {
                upcomingDiscovers = String.Format("There are not upcoming {0} Opportinuties at the {1}.", theTitle,
                    theCampus.Name);
            }

            return upcomingDiscovers;
        }
Esempio n. 49
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="campus">Campus</param>
 /// <param name="membres">Members in the campus</param>
 /// <param name="alumnis">Alumnis</param>
 public CampusMembers(Campus campus, IEnumerable<Member> membres, IEnumerable<Member> alumnis)
 {
     Campus = campus;
     Members = membres;
     Alumnis = alumnis;
 }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Campus campus;
            var rockContext = new RockContext();
            CampusService campusService = new CampusService( rockContext );

            int campusId = int.Parse( hfCampusId.Value );

            if ( campusId == 0 )
            {
                campus = new Campus();
                campusService.Add( campus);
            }
            else
            {
                campus = campusService.Get( campusId );
            }

            campus.Name = tbCampusName.Text;
            campus.ShortCode = tbCampusCode.Text;
            campus.PhoneNumber = tbPhoneNumber.Text;

            var personService = new PersonService( rockContext );
            var leaderPerson = personService.Get( ppCampusLeader.SelectedValue ?? 0 );
            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            if ( !campus.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            rockContext.SaveChanges();

            Rock.Web.Cache.CampusCache.Flush( campus.Id );

            NavigateToParentPage();
        }
Esempio n. 51
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Campus campus;
            var rockContext = new RockContext();
            var campusService = new CampusService( rockContext );
            var locationService = new LocationService( rockContext );
            var locationCampusValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS.AsGuid());

            int campusId = int.Parse( hfCampusId.Value );

            if ( campusId == 0 )
            {
                campus = new Campus();
                campusService.Add( campus);
            }
            else
            {
                campus = campusService.Get( campusId );
            }

            campus.Name = tbCampusName.Text;
            campus.IsActive = cbIsActive.Checked;
            campus.Description = tbDescription.Text;
            campus.Url = tbUrl.Text;

            campus.PhoneNumber = tbPhoneNumber.Text;
            if ( campus.Location == null )
            {
                var location = locationService.Queryable()
                    .Where( l =>
                        l.Name.Equals( campus.Name, StringComparison.OrdinalIgnoreCase ) &&
                        l.LocationTypeValueId == locationCampusValue.Id )
                    .FirstOrDefault();
                if (location == null)
                {
                    location = new Location();
                    locationService.Add( location );
                }

                campus.Location = location;
            }

            campus.Location.Name = campus.Name;
            campus.Location.LocationTypeValueId = locationCampusValue.Id;

            string preValue = campus.Location.GetFullStreetAddress();
            acAddress.GetValues( campus.Location );
            string postValue = campus.Location.GetFullStreetAddress();

            campus.ShortCode = tbCampusCode.Text;

            var personService = new PersonService( rockContext );
            var leaderPerson = personService.Get( ppCampusLeader.SelectedValue ?? 0 );
            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;

            campus.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributes, campus );

            if ( !campus.IsValid && campus.Location.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();
                campus.SaveAttributeValues( rockContext );

                if (preValue != postValue && !string.IsNullOrWhiteSpace(campus.Location.Street1))
                {
                    locationService.Verify(campus.Location, true);
                }

            } );

            Rock.Web.Cache.CampusCache.Flush( campus.Id );

            NavigateToParentPage();
        }
Esempio n. 52
0
        /// <summary>
        /// Loads the family data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadFamily( CsvDataModel csvData )
        {
            // Required variables
            var lookupContext = new RockContext();
            var locationService = new LocationService( lookupContext );
            int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

            int numImportedFamilies = ImportedPeople.Select( p => p.ForeignId ).Distinct().Count();

            int homeLocationTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME ) ).Id;
            int workLocationTypeId = DefinedValueCache.Read( new Guid( "E071472A-F805-4FC4-917A-D5E3C095C35C" ) ).Id;

            var currentFamilyGroup = new Group();
            var newFamilyList = new List<Group>();
            var newGroupLocations = new Dictionary<GroupLocation, string>();

            string currentFamilyId = string.Empty;
            int completed = 0;

            ReportProgress( 0, string.Format( "Starting family import ({0:N0} already exist).", numImportedFamilies ) );

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ( ( row = csvData.Database.FirstOrDefault() ) != null )
            {
                string rowFamilyId = row[FamilyId];
                string rowFamilyName = row[FamilyName];

                if ( !string.IsNullOrWhiteSpace( rowFamilyId ) && rowFamilyId != currentFamilyGroup.ForeignId )
                {
                    currentFamilyGroup = ImportedPeople.FirstOrDefault( p => p.ForeignId == rowFamilyId );
                    if ( currentFamilyGroup == null )
                    {
                        currentFamilyGroup = new Group();
                        currentFamilyGroup.ForeignId = rowFamilyId;
                        currentFamilyGroup.Name = row[FamilyName];
                        currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        currentFamilyGroup.GroupTypeId = familyGroupTypeId;
                        newFamilyList.Add( currentFamilyGroup );
                    }

                    // Set the family campus
                    string campusName = row[Campus];
                    if ( !string.IsNullOrWhiteSpace( campusName ) )
                    {
                        var familyCampus = CampusList.Where( c => c.Name.StartsWith( campusName ) || c.ShortCode.StartsWith( campusName ) ).FirstOrDefault();
                        if ( familyCampus == null )
                        {
                            familyCampus = new Campus();
                            familyCampus.IsSystem = false;
                            familyCampus.Name = campusName;
                            lookupContext.Campuses.Add( familyCampus );
                            lookupContext.SaveChanges( true );
                        }

                        // This won't assign a campus if the family already exists because the context doesn't get saved
                        currentFamilyGroup.CampusId = familyCampus.Id;
                    }

                    // Add the family addresses since they exist in this file
                    string famAddress = row[Address];
                    string famAddress2 = row[Address2];
                    string famCity = row[City];
                    string famState = row[State];
                    string famZip = row[Zip];
                    string famCountry = row[Country];

                    // Use the core Rock location service to add or lookup an address
                    Location primaryAddress = locationService.Get( famAddress, famAddress2, famCity, famState, famZip, famCountry );
                    if ( primaryAddress != null )
                    {
                        primaryAddress.Name = currentFamilyGroup.Name + " Home";

                        var primaryLocation = new GroupLocation();
                        primaryLocation.LocationId = primaryAddress.Id;
                        primaryLocation.IsMailingLocation = true;
                        primaryLocation.IsMappedLocation = true;
                        primaryLocation.GroupLocationTypeValueId = homeLocationTypeId;
                        newGroupLocations.Add( primaryLocation, rowFamilyId );
                    }

                    string famSecondAddress = row[SecondaryAddress];
                    string famSecondAddress2 = row[SecondaryAddress2];
                    string famSecondCity = row[SecondaryCity];
                    string famSecondState = row[SecondaryState];
                    string famSecondZip = row[SecondaryZip];
                    string famSecondCountry = row[SecondaryCountry];

                    Location secondaryAddress = locationService.Get( famSecondAddress, famSecondAddress2, famSecondCity, famSecondState, famSecondZip, famSecondCountry );
                    if ( secondaryAddress != null )
                    {
                        secondaryAddress.Name = currentFamilyGroup.Name + " Work";

                        var secondaryLocation = new GroupLocation();
                        secondaryLocation.LocationId = primaryAddress.Id;
                        secondaryLocation.IsMailingLocation = true;
                        secondaryLocation.IsMappedLocation = true;
                        secondaryLocation.GroupLocationTypeValueId = workLocationTypeId;
                        newGroupLocations.Add( secondaryLocation, rowFamilyId );
                    }

                    completed++;
                    if ( completed % ( ReportingNumber * 10 ) < 1 )
                    {
                        ReportProgress( 0, string.Format( "{0:N0} families imported.", completed ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFamilies( newFamilyList, newGroupLocations );
                        ReportPartialProgress();

                        // Reset lookup context
                        lookupContext = new RockContext();
                        locationService = new LocationService( lookupContext );
                        newFamilyList.Clear();
                        newGroupLocations.Clear();
                    }
                }
            }

            // Check to see if any rows didn't get saved to the database
            if ( newGroupLocations.Any() )
            {
                SaveFamilies( newFamilyList, newGroupLocations );
            }

            ReportProgress( 0, string.Format( "Finished family import: {0:N0} families imported.", completed ) );
            return completed;
        }
Esempio n. 53
0
        /// <summary>
        /// Loads the family data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadFamily( CsvDataModel csvData )
        {
            // Required variables
            var lookupContext = new RockContext();
            var locationService = new LocationService( lookupContext );
            int familyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

            int numImportedFamilies = ImportedPeople.Select( p => p.ForeignId ).Distinct().Count();

            int homeLocationTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME ) ).Id;
            int workLocationTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ) ).Id;

            var newGroupLocations = new Dictionary<GroupLocation, string>();
            var currentFamilyGroup = new Group();
            var newFamilyList = new List<Group>();
            var updatedFamilyList = new List<Group>();

            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            string currentFamilyId = string.Empty;
            var importDate = DateTime.Now;
            int completed = 0;

            ReportProgress( 0, string.Format( "Starting family import ({0:N0} already exist).", numImportedFamilies ) );

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ( ( row = csvData.Database.FirstOrDefault() ) != null )
            {
                string rowFamilyId = row[FamilyId];
                string rowFamilyName = row[FamilyName];

                if ( !string.IsNullOrWhiteSpace( rowFamilyId ) && rowFamilyId != currentFamilyGroup.ForeignId )
                {
                    currentFamilyGroup = ImportedPeople.FirstOrDefault( p => p.ForeignId == rowFamilyId );
                    if ( currentFamilyGroup == null )
                    {
                        currentFamilyGroup = new Group();
                        currentFamilyGroup.ForeignId = rowFamilyId;
                        currentFamilyGroup.Name = row[FamilyName];
                        currentFamilyGroup.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        currentFamilyGroup.GroupTypeId = familyGroupTypeId;
                        newFamilyList.Add( currentFamilyGroup );
                    }
                    else
                    {
                        lookupContext.Groups.Attach( currentFamilyGroup );
                    }

                    // Set the family campus
                    string campusName = row[Campus];
                    if ( !string.IsNullOrWhiteSpace( campusName ) )
                    {
                        var familyCampus = CampusList.Where( c => c.Name.Equals( campusName, StringComparison.InvariantCultureIgnoreCase )
                            || c.ShortCode.Equals( campusName, StringComparison.InvariantCultureIgnoreCase ) ).FirstOrDefault();
                        if ( familyCampus == null )
                        {
                            familyCampus = new Campus();
                            familyCampus.IsSystem = false;
                            familyCampus.Name = campusName;
                            lookupContext.Campuses.Add( familyCampus );
                            lookupContext.SaveChanges( true );
                            CampusList.Add( familyCampus );
                        }

                        currentFamilyGroup.CampusId = familyCampus.Id;
                    }

                    // Add the family addresses since they exist in this file
                    string famAddress = row[Address];
                    string famAddress2 = row[Address2];
                    string famCity = row[City];
                    string famState = row[State];
                    string famZip = row[Zip];
                    string famCountry = row[Country];

                    Location primaryAddress = Extensions.GetWithoutVerify( famAddress, famAddress2, famCity, famState, famZip, famCountry, false );

                    if ( primaryAddress != null )
                    {
                        var primaryLocation = new GroupLocation();
                        primaryLocation.LocationId = primaryAddress.Id;
                        primaryLocation.IsMailingLocation = true;
                        primaryLocation.IsMappedLocation = true;
                        primaryLocation.GroupLocationTypeValueId = homeLocationTypeId;
                        newGroupLocations.Add( primaryLocation, rowFamilyId );
                    }

                    string famSecondAddress = row[SecondaryAddress];
                    string famSecondAddress2 = row[SecondaryAddress2];
                    string famSecondCity = row[SecondaryCity];
                    string famSecondState = row[SecondaryState];
                    string famSecondZip = row[SecondaryZip];
                    string famSecondCountry = row[SecondaryCountry];

                    Location secondaryAddress = Extensions.GetWithoutVerify( famSecondAddress, famSecondAddress2, famSecondCity, famSecondState, famSecondZip, famSecondCountry, false );

                    if ( secondaryAddress != null )
                    {
                        var secondaryLocation = new GroupLocation();
                        secondaryLocation.LocationId = secondaryAddress.Id;
                        secondaryLocation.IsMailingLocation = true;
                        secondaryLocation.IsMappedLocation = true;
                        secondaryLocation.GroupLocationTypeValueId = workLocationTypeId;
                        newGroupLocations.Add( secondaryLocation, rowFamilyId );
                    }

                    DateTime createdDateValue;
                    if ( DateTime.TryParseExact( row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue ) )
                    {
                        currentFamilyGroup.CreatedDateTime = createdDateValue;
                        currentFamilyGroup.ModifiedDateTime = importDate;
                    }
                    else
                    {
                        currentFamilyGroup.CreatedDateTime = importDate;
                        currentFamilyGroup.ModifiedDateTime = importDate;
                    }

                    completed++;
                    if ( completed % ( ReportingNumber * 10 ) < 1 )
                    {
                        ReportProgress( 0, string.Format( "{0:N0} families imported.", completed ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFamilies( newFamilyList, newGroupLocations );
                        ReportPartialProgress();

                        // Reset lookup context
                        lookupContext.SaveChanges();
                        lookupContext = new RockContext();
                        locationService = new LocationService( lookupContext );
                        newFamilyList.Clear();
                        newGroupLocations.Clear();
                    }
                }
            }

            // Check to see if any rows didn't get saved to the database
            if ( newGroupLocations.Any() )
            {
                SaveFamilies( newFamilyList, newGroupLocations );
            }

            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress( 0, string.Format( "Finished family import: {0:N0} families added or updated.", completed ) );
            return completed;
        }
Esempio n. 54
0
        public void PopulateDatabaseFromUnpivotedStaarTestFile(string parsedFilePath, string logPath)
        {
            var dems = _ctx.DemographicDetails.ToList();
            var cats = _ctx.CategoryDetails.ToList();
            var subjs = _ctx.Subjects.ToList();
            var camps = _ctx.Campuses.ToList();
            var dists = _ctx.Districts.ToList();
            var regs = _ctx.Regions.ToList();
            var langs = _ctx.Languages.ToList();
            var completed = _ctx.StaarTests
                .GroupBy(s => new
                {
                    s.Year,
                    Subject = s.Subject.Name,
                    s.Grade,
                    s.Language.Name
                })
                .Select(s => new
                {
                    s.Key.Year,
                    SubjectName = s.Key.Subject,
                    s.Key.Grade,
                    Language = s.Key.Name
                }).ToList();

            string previousCampus = "",
                previousSubject = "",
                previousDemographic = "",
                previousCategory = "";
            long campusId = 0;
            var subject = new Subject();
            var dd = new DemographicDetail();
            var cd = new CategoryDetail();
            var log = File.CreateText(logPath);

            //Validation

            if (!parsedFilePath.Contains(".csv"))
                throw new CustomException("This is not a csv file.");


            //read the lines in. First row is headers. save it then remove

            var rows = File.ReadAllLines(parsedFilePath).ToList();
            rows.RemoveAt(0); //headers

            if (rows.Count > 12) //this is our test to make sure they are parsed
                throw new CustomException(string.Format("{0} is not in the format of a parsed file", Path.GetFileName(parsedFilePath)));

            //Begin adding data

            var splitRows = rows.Select(row => row.Split(',')).ToList();


            //adjust year if it is off

            var year = int.Parse(splitRows[0][1]);
            if (year >= 90 && year < 100) year += 1900;
            else if (year < 90) year += 2000;

            var language = langs.Single(l => l.Name == splitRows[0][7]);
            var campusTests = new List<StaarTest>(90005);
            var sortedCount = splitRows.Count;


            for (var i = 0; i < sortedCount; i++)
            {
                try
                {
                    var record = splitRows[i];

                    if (completed.Any(c => c.SubjectName == record[8]
                                           && c.Grade == record[6]
                                           && c.Year == year
                                           && c.Language == language.Name))
                        continue;

                    //check if we're on a new school

                    if (previousCampus != record[0])
                    {
                        //Find the school. Create if not new

                        long campusNum = Convert.ToInt32(record[0]);
                        long regionNum = Convert.ToInt32(record[2]);
                        long districtNum = Convert.ToInt32(record[3]);

                        //check region, district, and campus

                        var region = regs.FirstOrDefault(r => r.Number == regionNum);
                        if (region == null)
                        {
                            region = new Region
                            {
                                Name = string.Format("Region {0}", regionNum),
                                Number = regionNum
                            };
                            _ctx.Regions.Add(region);
                        }

                        var district = dists.FirstOrDefault(r => r.Number == districtNum);
                        if (district == null)
                        {
                            district = new District
                            {
                                Name = record[4],
                                Number = districtNum,
                                Region_Id = region.Id
                            };
                            _ctx.Districts.Add(district);
                        }

                        var campus = camps.FirstOrDefault(r => r.Number == campusNum);
                        if (campus == null)
                        {
                            campus = new Campus
                            {
                                Name = record[5],
                                Number = campusNum,
                                District_Id = district.Id
                            };
                            _ctx.Campuses.Add(campus);
                        }

                        //TODO ctx.SaveChanges();
                        campusId = campus.Id;
                    }

                    if (previousSubject != record[8])
                    {
                        subject = subjs.Single(s => s.Name == record[8]);
                    }

                    if (previousDemographic != record[9])
                    {
                        dd = dems.Single(s => s.Detail == record[9]);
                    }

                    if (previousCategory != record[10])
                    {
                        cd = cats.Single(s => s.Detail == record[10]);
                    }


                    //for each complex header whose category matches the current category make a demo and value

                    campusTests.Add(new StaarTest
                    {
                        Campus_Id = campusId,
                        CategoryDetail_Id = cd.Id,
                        DemographicDetail_Id = dd.Id,
                        Subject_Id = subject.Id,
                        Year = year,
                        Language_Id = language.Id,
                        Value = Convert.ToDecimal(record[11]),
                        Grade = record[6]
                    });

                    if (campusTests.Count >= 90000 || i == sortedCount - 1)
                    {
                        //ctx.BulkInsert(campusTests);
                        campusTests = new List<StaarTest>(90005);
                    }

                    previousCampus = record[0];
                    previousSubject = record[8];
                    previousDemographic = record[9];
                    previousCategory = record[10];
                }
                catch (Exception ex)
                {
                    log.WriteLine("Message - {0}\r\nStackTrace - {1}", ex.Message, ex.StackTrace);
                    //throw;
                }
                finally
                {
                    log.Flush();
                    log.Close();
                }
            }
            //TODO ctx.SaveChanges();
            log.Flush();
            log.Close();
        }
Esempio n. 55
0
        private UserInfo MapUser(IDataReader reader)
        {
            UserInfo s = new UserInfo();
            UserTracks t = new UserTracks();
            Campus c = new Campus();
            int startingIndex = 0;

            s.Id = reader.GetSafeInt32(startingIndex++);
            s.FirstName = reader.GetSafeString(startingIndex++);
            s.LastName = reader.GetSafeString(startingIndex++);
            s.Email = reader.GetSafeString(startingIndex++);
            s.Gender = reader.GetSafeInt32(startingIndex++);
            s.Phone = reader.GetSafeString(startingIndex++);
            s.UserName = reader.GetSafeString(startingIndex++);
            s.UserId = reader.GetSafeString(startingIndex++);

            s.Bio = reader.GetSafeString(startingIndex++);
            s.DesiredTrack = reader.GetSafeInt32(startingIndex++);
            s.DesiredCampusLocation = reader.GetSafeInt32(startingIndex++);
            s.CoverPhotoPath = reader.GetSafeString(startingIndex++);
            s.AvatarPhotoPath = reader.GetSafeString(startingIndex++);
            s.CoverPhotoUrl = _fileService.GetFullUrl(s.CoverPhotoPath);
            s.AvatarPhotoUrl = _fileService.GetFullUrl(s.AvatarPhotoPath);
            t.Name = reader.GetSafeString(startingIndex++);
            c.Id = reader.GetSafeInt32(startingIndex++);
            c.Name = reader.GetSafeString(startingIndex++);
            s.AddressId = reader.GetSafeInt32(startingIndex++);
            s.Facebook = reader.GetSafeString(startingIndex++);
            s.LinkedIn = reader.GetSafeString(startingIndex++);
            s.Twitter = reader.GetSafeString(startingIndex++);
            s.Webpage = reader.GetSafeString(startingIndex++);

            s.Campuses = c;
            s.UserTracks = t;

            return s;
        }
 void _ChangeListener_StatusChanged(object sender, Campus.Windows.ChangeEventArgs e)
 {
     IsChangeNow = (e.Status == Campus.Windows.ValueStatus.Dirty);
 }
        /// <summary>
        /// Sets the campus context.
        /// </summary>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="refreshPage">if set to <c>true</c> [refresh page].</param>
        /// <returns></returns>
        protected Campus SetCampusContext( int campusId, bool refreshPage = false )
        {
            bool pageScope = GetAttributeValue( "ContextScope" ) == "Page";
            var campus = new CampusService( new RockContext() ).Get( campusId );
            if ( campus == null )
            {
                // clear the current campus context
                campus = new Campus()
                {
                    Name = GetAttributeValue( "NoCampusText" ),
                    Guid = Guid.Empty
                };
            }

            // set context and refresh below with the correct query string if needed
            RockPage.SetContextCookie( campus, pageScope, false );

            // Only redirect if refreshPage is true
            if ( refreshPage )
            {
                if ( !string.IsNullOrWhiteSpace( PageParameter( "campusId" ) ) || GetAttributeValue( "DisplayQueryStrings" ).AsBoolean() )
                {
                    var queryString = HttpUtility.ParseQueryString( Request.QueryString.ToStringSafe() );
                    queryString.Set( "campusId", campusId.ToString() );
                    Response.Redirect( string.Format( "{0}?{1}", Request.Url.AbsolutePath, queryString ), false );
                }
                else
                {
                    Response.Redirect( Request.RawUrl, false );
                }

                Context.ApplicationInstance.CompleteRequest();
            }

            return campus;
        }