/// <summary> /// Executes this instance. /// </summary> public void Execute() { using ( var rockContext = new RockContext() ) { var binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( BinaryFileGuid ); if ( binaryFile != null ) { string guidAsString = BinaryFileGuid.ToString(); // If any attribute still has this file as a default value, don't delete it if ( new AttributeService( rockContext ).Queryable().Any( a => a.DefaultValue == guidAsString ) ) { return; } // If any attribute value still has this file as a value, don't delete it if ( new AttributeValueService( rockContext ).Queryable().Any( a => a.Value == guidAsString ) ) { return; } binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } }
/// <summary> /// Handles the Delete event of the gBinaryFile control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gBinaryFile_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); BinaryFile binaryFile = binaryFileService.Get( e.RowKeyId ); if ( binaryFile != null ) { string errorMessage; if ( !binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } Guid guid = binaryFile.Guid; bool clearDeviceCache = binaryFile.BinaryFileType.Guid.Equals( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid() ); binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); if ( clearDeviceCache ) { Rock.CheckIn.KioskDevice.FlushAll(); Rock.CheckIn.KioskLabel.Flush( guid ); } } BindGrid(); }
public IHttpActionResult Get(int seriesId) { var rockContext = new RockContext(); var contentItemService = new ContentChannelService(rockContext); var d = new DotLiquid.Context(); ContentChannel contentItem = null; var attrService = new AttributeService(rockContext); var dailyItems = new List<MessageArchiveItem>(); var ids = rockContext.Database.SqlQuery<int>("exec GetMessageArchivesBySeriesId @seriesId", new SqlParameter("seriesId", seriesId)).ToList(); contentItem = contentItemService.Get(11); var items = contentItem.Items.Where(a => ids.Contains(a.Id)).ToList(); foreach (var item in items) { item.LoadAttributes(rockContext); var link = GetVimeoLink(item.GetAttributeValue("VideoId")); var newItem = new MessageArchiveItem(); newItem.Id = item.Id; // newItem.Content = item.Content; newItem.Content = DotLiquid.StandardFilters.StripHtml(item.Content).Replace("\n\n", "\r\n\r\n"); newItem.Date = DateTime.Parse(item.GetAttributeValue("Date")).ToShortDateString(); newItem.Speaker = item.GetAttributeValue("Speaker"); newItem.SpeakerTitle = item.GetAttributeValue("SpeakerTitle"); newItem.Title = item.Title; newItem.VimeoLink = link; var notesAttr = item.Attributes["MessageNotes"]; var binaryFile = new BinaryFileService(new RockContext()).Get(notesAttr.Id); if (binaryFile != null) newItem.Notes = binaryFile.Url; var talkAttr = item.Attributes["TalkItOver"]; binaryFile = new BinaryFileService(new RockContext()).Get(talkAttr.Id); if (binaryFile != null) newItem.TalkItOver = binaryFile.Url; dailyItems.Add(newItem); } return Ok(dailyItems.AsQueryable()); }
/// <summary> /// Saves the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="personId">The person identifier.</param> /// <returns></returns> public override bool Save( FinancialTransactionImage item, int? personId ) { // ensure that the BinaryFile.IsTemporary flag is set to false for any BinaryFiles that are associated with this record BinaryFileService binaryFileService = new BinaryFileService( this.RockContext ); var binaryFile = binaryFileService.Get( item.BinaryFileId ); if ( binaryFile != null && binaryFile.IsTemporary ) { binaryFile.IsTemporary = false; } return base.Save( item, personId ); }
/// <summary> /// Sets the value. /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues"></param> /// <param name="value">The value.</param> public override void SetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues, string value ) { var fileUploader = control as Rock.Web.UI.Controls.FileUploader; if ( fileUploader != null ) { var binaryFile = new BinaryFileService( new RockContext() ).Get( value.AsGuid() ); if (binaryFile != null) { fileUploader.BinaryFileId = binaryFile.Id; } } }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { var binaryFileGuid = value.AsGuidOrNull(); if ( binaryFileGuid.HasValue ) { var binaryFileService = new BinaryFileService( new RockContext() ); var binaryFileInfo = binaryFileService.Queryable().Where( a => a.Guid == binaryFileGuid.Value ) .Select( s => new { s.FileName, s.MimeType, s.Guid } ) .FirstOrDefault(); if ( binaryFileInfo != null ) { if ( condensed ) { return binaryFileInfo.FileName; } else { var filePath = System.Web.VirtualPathUtility.ToAbsolute( "~/GetFile.ashx" ); // NOTE: Flash and Silverlight might crash if we don't set width and height. However, that makes responsive stuff not work string htmlFormat = @" <video src='{0}?guid={1}' class='js-media-video' type='{2}' controls='controls' style='width:100%;height:100%;' width='100%' height='100%' preload='auto' > </video> <script> Rock.controls.mediaPlayer.initialize(); </script> "; var html = string.Format( htmlFormat, filePath, binaryFileInfo.Guid, binaryFileInfo.MimeType ); return html; } } } // value or binaryfile was null return null; }
/// <summary> /// Reads new values entered by the user for the field /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues"></param> /// <returns></returns> public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues ) { var fileUploader = control as Rock.Web.UI.Controls.FileUploader; if ( fileUploader != null ) { var binaryFile = new BinaryFileService( new RockContext() ).Get( fileUploader.BinaryFileId ?? 0 ); if ( binaryFile != null ) { return binaryFile.Guid.ToString(); } } return null; }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { var binaryFileGuid = value.AsGuidOrNull(); if ( binaryFileGuid.HasValue ) { var binaryFileService = new BinaryFileService( new RockContext() ); var binaryFileInfo = binaryFileService.Queryable().Where( a => a.Guid == binaryFileGuid.Value ) .Select( s => new { s.FileName, s.MimeType, s.Guid } ) .FirstOrDefault(); if ( binaryFileInfo != null ) { if ( condensed ) { return binaryFileInfo.FileName; } else { var filePath = System.Web.VirtualPathUtility.ToAbsolute( "~/GetFile.ashx" ); string htmlFormat = @" <audio src='{0}?guid={1}' class='img img-responsive js-media-audio' type='{2}' controls > </audio> <script> Rock.controls.mediaPlayer.initialize(); </script> "; var html = string.Format( htmlFormat, filePath, binaryFileInfo.Guid, binaryFileInfo.MimeType ); return html; } } } // value or binaryfile was null return null; }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed ) { string formattedValue = string.Empty; int id = int.MinValue; if (Int32.TryParse( value, out id )) { var result = new BinaryFileService( new RockContext() ) .Queryable() .Select( f => new { f.Id, f.FileName } ) .Where( f => f.Id == id ) .FirstOrDefault(); if ( result != null ) { formattedValue = result.FileName; } } return base.FormatValue( parentControl, formattedValue, null, condensed ); }
/// <summary> /// Pres the save. /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="state">The state.</param> public override void PreSaveChanges(DbContext dbContext, System.Data.Entity.EntityState state) { if (state != System.Data.Entity.EntityState.Deleted) { // ensure that the BinaryFile.IsTemporary flag is set to false for any BinaryFiles that are associated with this record var fieldTypeCache = FieldTypeCache.Read(this.FieldTypeId); if (fieldTypeCache.Field is Rock.Field.Types.BinaryFileFieldType) { Guid?binaryFileGuid = DefaultValue.AsGuidOrNull(); if (binaryFileGuid.HasValue) { BinaryFileService binaryFileService = new BinaryFileService((RockContext)dbContext); var binaryFile = binaryFileService.Get(binaryFileGuid.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } } }
/// <summary> /// Saves the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="personId">The person identifier.</param> /// <returns></returns> public override bool Save(Person item, int?personId) { // Set the nickname if a value was not entered if (string.IsNullOrWhiteSpace(item.NickName)) { item.NickName = item.FirstName; } // ensure that the BinaryFile.IsTemporary flag is set to false for any BinaryFiles that are associated with this record if (item.PhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(this.RockContext); var binaryFile = binaryFileService.Get(item.PhotoId.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } return(base.Save(item, personId)); }
/// <summary> /// Handles the Delete event of the gBinaryFile control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gBinaryFile_Delete( object sender, RowEventArgs e ) { var rockContext = new RockContext(); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); BinaryFile binaryFile = binaryFileService.Get( e.RowKeyId ); if ( binaryFile != null ) { string errorMessage; if ( !binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } BindGrid(); }
/// <summary> /// Saves the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="personId">The person identifier.</param> /// <returns></returns> public override bool Save(Attribute item, int?personId) { // ensure that the BinaryFile.IsTemporary flag is set to false for any BinaryFiles that are associated with this record var fieldTypeImage = Rock.Web.Cache.FieldTypeCache.Read(Rock.SystemGuid.FieldType.IMAGE.AsGuid()); var fieldTypeBinaryFile = Rock.Web.Cache.FieldTypeCache.Read(Rock.SystemGuid.FieldType.BINARY_FILE.AsGuid()); if (item.FieldTypeId == fieldTypeImage.Id || item.FieldTypeId == fieldTypeBinaryFile.Id) { int?binaryFileId = item.DefaultValue.AsInteger(); if (binaryFileId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(this.RockContext); var binaryFile = binaryFileService.Get(binaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } return(base.Save(item, personId)); }
/// <summary> /// Delete the old binary file for UPDATE and DELETE and make sure new binary files are not temporary /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The entry.</param> protected void PreSaveBinaryFile(Rock.Data.DbContext dbContext, DbEntityEntry entry) { Guid?newBinaryFileGuid = null; Guid?oldBinaryFileGuid = null; if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { newBinaryFileGuid = Value.AsGuidOrNull(); } if (entry.State == EntityState.Modified || entry.State == EntityState.Deleted) { oldBinaryFileGuid = entry.OriginalValues["Value"]?.ToString().AsGuidOrNull(); } if (oldBinaryFileGuid.HasValue) { if (!newBinaryFileGuid.HasValue || !newBinaryFileGuid.Value.Equals(oldBinaryFileGuid.Value)) { var deleteBinaryFileAttributeMsg = new DeleteBinaryFileAttribute.Message() { BinaryFileGuid = oldBinaryFileGuid.Value }; deleteBinaryFileAttributeMsg.Send(); } } if (newBinaryFileGuid.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(( RockContext )dbContext); var binaryFile = binaryFileService.Get(newBinaryFileGuid.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } }
public TheDailyItem GetDailyItem(int id) { var rockContext = new RockContext(); var contentItemService = new ContentChannelItemService(rockContext); ContentChannelItem i = null; var attrService = new AttributeService(rockContext); var dailyItem = new TheDailyItem(); i = contentItemService.Get(id); if (i != null) { i.LoadAttributes(); i.Content = DotLiquid.StandardFilters.StripHtml(i.Content).Replace("\n\n", "\r\n\r\n"); var attributes = i.Attributes; var pdfAttr = i.Attributes["PDF"]; var binaryFile = new BinaryFileService(new RockContext()).Get(pdfAttr.Id); var pdfUrl = binaryFile.Url; var scriptureAttr = i.Attributes["ScriptureCards"]; binaryFile = new BinaryFileService(new RockContext()).Get(scriptureAttr.Id); var scriptureUrl = binaryFile.Url; dailyItem = (new TheDailyItem { Id = i.Id, Title = i.Title, Content = i.Content, DailyPDF = pdfUrl, ScriptiureCards = scriptureUrl }); } return dailyItem; }
protected void btnOpen_Click( object sender, EventArgs e ) { ceLabel.Label = "Label Contents"; btnSave.Visible = false; int? fileId = ddlLabel.SelectedValueAsInt(); if ( fileId.HasValue ) { hfBinaryFileId.Value = fileId.Value.ToString(); using ( var rockContext = new RockContext() ) { var file = new BinaryFileService( rockContext ).Get( fileId.Value ); if ( file != null ) { ceLabel.Text = file.ContentsToString(); SetLabelSize( ceLabel.Text ); ceLabel.Label = string.Format( file.FileName ); btnSave.Text = "Save " + file.FileName; btnSave.Visible = true; } } } }
/// <summary> /// Method that will be called on an entity immediately after the item is saved by context /// </summary> /// <param name="dbContext">The database context.</param> public override void PostSaveChanges(Rock.Data.DbContext dbContext) { // ensure any attachments have the binaryFile.IsTemporary set to False var attachmentBinaryFilesIds = this.Attachments.Select(a => a.BinaryFileId).ToList(); if (attachmentBinaryFilesIds.Any()) { using (var rockContext = new RockContext()) { var temporaryBinaryFiles = new BinaryFileService(rockContext).GetByIds(attachmentBinaryFilesIds).Where(a => a.IsTemporary == true).ToList(); { foreach (var binaryFile in temporaryBinaryFiles) { binaryFile.IsTemporary = false; } } rockContext.SaveChanges(); } } base.PostSaveChanges(dbContext); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); var mergeFields = GetMergeFields( action ); BenevolenceRequestService benevolenceRequestService = new BenevolenceRequestService( rockContext ); var benevolenceRequest = benevolenceRequestService.Get( GetAttributeValue( action, "BenevolenceRequest", true ).AsGuid() ); if (benevolenceRequest == null ) { var errorMessage = "Benevolence request could not be found."; errorMessages.Add( errorMessage ); action.AddLogEntry( errorMessage, true ); return false; } var binaryFile = new BinaryFileService(rockContext).Get(GetAttributeValue( action, "Document", true ).AsGuid()); if ( binaryFile == null ) { action.AddLogEntry( "The document to add to the benevolence request was not be found.", true ); return true; // returning true here to allow the action to run 'successfully' without a document. This allows the action to be easily used when the document is optional without a bunch of action filter tests. } BenevolenceRequestDocument requestDocument = new BenevolenceRequestDocument(); benevolenceRequest.Documents.Add( requestDocument ); requestDocument.BinaryFileId = binaryFile.Id; rockContext.SaveChanges(); action.AddLogEntry( "Added document to the benevolence request." ); return true; }
/// <summary> /// Updates the document status. /// </summary> /// <param name="signatureDocument">The signature document.</param> /// <param name="tempFolderPath">The temporary folder path.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public bool UpdateDocumentStatus(SignatureDocument signatureDocument, string tempFolderPath, out List <string> errorMessages) { errorMessages = new List <string>(); if (signatureDocument == null) { errorMessages.Add("Invalid Document."); } if (signatureDocument.SignatureDocumentTemplate == null) { errorMessages.Add("Document has an invalid document type."); } if (!errorMessages.Any()) { var provider = DigitalSignatureContainer.GetComponent(signatureDocument.SignatureDocumentTemplate.ProviderEntityType.Name); if (provider == null || !provider.IsActive) { errorMessages.Add("Digital Signature provider was not found or is not active."); } else { var originalStatus = signatureDocument.Status; if (provider.UpdateDocumentStatus(signatureDocument, out errorMessages)) { if (signatureDocument.Status == SignatureDocumentStatus.Signed && !signatureDocument.BinaryFileId.HasValue) { using (var rockContext = new RockContext()) { string documentPath = provider.GetDocument(signatureDocument, tempFolderPath, out errorMessages); if (!string.IsNullOrWhiteSpace(documentPath)) { var binaryFileService = new BinaryFileService(rockContext); BinaryFile binaryFile = new BinaryFile(); binaryFile.Guid = Guid.NewGuid(); binaryFile.IsTemporary = false; binaryFile.BinaryFileTypeId = signatureDocument.SignatureDocumentTemplate.BinaryFileTypeId; binaryFile.MimeType = "application/pdf"; var fi = new FileInfo(documentPath); binaryFile.FileName = fi.Name; binaryFile.FileSize = fi.Length; binaryFile.ContentStream = new FileStream(documentPath, FileMode.Open); binaryFileService.Add(binaryFile); rockContext.SaveChanges(); signatureDocument.BinaryFileId = binaryFile.Id; File.Delete(documentPath); } } } if (signatureDocument.Status != originalStatus) { signatureDocument.LastStatusDate = RockDateTime.Now; } } } } return(!errorMessages.Any()); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { // use the same rockContext for both services so we can join // TODO: Can/Should this be refactored to use UnitOfWorkScope? RockContext rockContext = new RockContext(); BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); SortProperty sortProperty = gBinaryFileType.SortProperty; // join so we can both get BinaryFileCount quickly and be able to sort by it (having SQL do all the work) var qry = from ft in binaryFileTypeService.Queryable() join bf in binaryFileService.Queryable().GroupBy( b => b.BinaryFileTypeId ) on ft.Id equals bf.Key into joinResult from x in joinResult.DefaultIfEmpty() select new { ft.Id, ft.Name, ft.Description, BinaryFileCount = x.Key == null ? 0 : x.Count(), StorageEntityType = ft.StorageEntityType != null ? ft.StorageEntityType.FriendlyName : string.Empty, ft.IsSystem, ft.AllowCaching }; if ( sortProperty != null ) { gBinaryFileType.DataSource = qry.Sort( sortProperty ).ToList(); } else { gBinaryFileType.DataSource = qry.OrderBy( p => p.Name ).ToList(); } gBinaryFileType.DataBind(); }
/// <summary> /// Saves an ExcelPackage as a BinaryFile and stores it in the database /// </summary> /// <param name="excel">The ExcelPackage object to save</param> /// <param name="fileName">The filename to save the workbook as</param> /// <param name="rockContext">The RockContext to use</param> /// <param name="binaryFileType">Optionally specifies the BinaryFileType to apply to this file for security purposes</param> /// <returns></returns> public static BinaryFile Save( ExcelPackage excel, string fileName, RockContext rockContext, BinaryFileType binaryFileType = null ) { if ( binaryFileType == null ) { binaryFileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid() ); } var ms = excel.ToMemoryStream(); var binaryFile = new BinaryFile() { Guid = Guid.NewGuid(), IsTemporary = true, BinaryFileTypeId = binaryFileType.Id, MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName = fileName, ContentStream = ms }; var binaryFileService = new BinaryFileService( rockContext ); binaryFileService.Add( binaryFile ); rockContext.SaveChanges(); return binaryFile; }
/// <summary> /// Handles the FileUploaded event of the fuTemplateBinaryFile 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 fuTemplateBinaryFile_FileUploaded( object sender, EventArgs e ) { nbFileTypeWarning.Visible = false; var mergeTemplateEntityType = EntityTypeCache.Read( ddlMergeTemplateType.SelectedValue.AsInteger() ); var binaryFile = new BinaryFileService( new RockContext() ).Get( fuTemplateBinaryFile.BinaryFileId ?? 0 ); if ( binaryFile != null ) { string fileExtension = Path.GetExtension( binaryFile.FileName ); fileExtension = fileExtension.TrimStart( '.' ); if ( string.IsNullOrWhiteSpace( fileExtension ) ) { // nothing more to do return; } MergeTemplateType mergeTemplateType = null; if ( mergeTemplateEntityType != null ) { mergeTemplateType = MergeTemplateTypeContainer.GetComponent( mergeTemplateEntityType.Name ); } else { // if a merge template type isn't selected, automatically pick the first matching one foreach ( var item in MergeTemplateTypeContainer.Instance.Components.Values ) { if ( item.Value.IsActive ) { var testMergeTemplateType = item.Value; if ( testMergeTemplateType.SupportedFileExtensions != null && testMergeTemplateType.SupportedFileExtensions.Any() ) { if ( testMergeTemplateType.SupportedFileExtensions.Contains( fileExtension ) ) { mergeTemplateType = testMergeTemplateType; var entityType = EntityTypeCache.Read( mergeTemplateType.EntityType.Id ); if ( entityType != null ) { ddlMergeTemplateType.SetValue( entityType.Id ); } break; } } } } } if ( mergeTemplateType == null ) { // couldn't automatically pick one, so warn that they need to pick it nbFileTypeWarning.Text = "Warning: Please select a template type."; nbFileTypeWarning.Visible = true; nbFileTypeWarning.Dismissable = true; return; } if ( mergeTemplateType.SupportedFileExtensions != null && mergeTemplateType.SupportedFileExtensions.Any() ) { if ( !mergeTemplateType.SupportedFileExtensions.Contains( fileExtension ) ) { nbFileTypeWarning.Text = string.Format( "Warning: The selected template type doesn't support '{0}' files. Please use a {1} file for this template type.", fileExtension, mergeTemplateType.SupportedFileExtensions.Select( a => a.Quoted() ).ToList().AsDelimited( ", ", " or " ) ); nbFileTypeWarning.Visible = true; nbFileTypeWarning.Dismissable = true; return; } } } if ( binaryFile != null && string.IsNullOrWhiteSpace( tbName.Text ) ) { tbName.Text = Path.GetFileNameWithoutExtension( binaryFile.FileName ).SplitCase().ReplaceWhileExists( " ", " " ); } }
/// <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 ) { MergeTemplate mergeTemplate; var rockContext = new RockContext(); MergeTemplateService mergeTemplateService = new MergeTemplateService( rockContext ); int mergeTemplateId = hfMergeTemplateId.Value.AsInteger(); int? origBinaryFileId = null; if ( mergeTemplateId == 0 ) { mergeTemplate = new MergeTemplate(); mergeTemplateService.Add( mergeTemplate ); } else { mergeTemplate = mergeTemplateService.Get( mergeTemplateId ); origBinaryFileId = mergeTemplate.TemplateBinaryFileId; } mergeTemplate.Name = tbName.Text; mergeTemplate.Description = tbDescription.Text; mergeTemplate.MergeTemplateTypeEntityTypeId = ddlMergeTemplateType.SelectedValue.AsInteger(); mergeTemplate.TemplateBinaryFileId = fuTemplateBinaryFile.BinaryFileId ?? 0; mergeTemplate.PersonAliasId = ppPerson.PersonAliasId; mergeTemplate.CategoryId = cpCategory.SelectedValue.AsInteger(); int personalMergeTemplateCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.PERSONAL_MERGE_TEMPLATE.AsGuid() ).Id; if ( mergeTemplate.PersonAliasId.HasValue ) { if ( mergeTemplate.CategoryId == 0 ) { // if the category picker isn't shown and/or the category isn't selected, and it's a personal filter... mergeTemplate.CategoryId = personalMergeTemplateCategoryId; } // ensure Personal templates are only in the Personal merge template category if ( mergeTemplate.CategoryId != personalMergeTemplateCategoryId ) { // prohibit personal templates from being in something other than the Personal category cpCategory.Visible = true; cpCategory.ShowErrorMessage( "Personal Merge Templates must be in Personal category" ); } } else { if ( mergeTemplate.CategoryId == personalMergeTemplateCategoryId ) { // prohibit global templates from being in Personal category cpCategory.ShowErrorMessage( "Person is required when using the Personal category" ); } } if ( !mergeTemplate.IsValid || !Page.IsValid ) { // Controls will render the error messages return; } BinaryFileService binaryFileService = new BinaryFileService( rockContext ); if ( origBinaryFileId.HasValue && origBinaryFileId.Value != mergeTemplate.TemplateBinaryFileId ) { // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up var oldBinaryFile = binaryFileService.Get( origBinaryFileId.Value ); if ( oldBinaryFile != null && !oldBinaryFile.IsTemporary ) { oldBinaryFile.IsTemporary = true; } } // ensure the IsTemporary is set to false on binaryFile associated with this MergeTemplate var binaryFile = binaryFileService.Get( mergeTemplate.TemplateBinaryFileId ); if ( binaryFile != null && binaryFile.IsTemporary ) { binaryFile.IsTemporary = false; } rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); qryParams["MergeTemplateId"] = mergeTemplate.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e ) { int? categoryId = null; var rockContext = new RockContext(); var service = new MergeTemplateService( rockContext ); var item = service.Get( hfMergeTemplateId.Value.AsInteger() ); if ( item != null ) { string errorMessage; if ( !service.CanDelete( item, out errorMessage ) ) { ShowReadonlyDetails( item ); mdDeleteWarning.Show( errorMessage, ModalAlertType.Information ); } else { categoryId = item.CategoryId; service.Delete( item ); rockContext.SaveChanges(); // set IsTemporary to true so that the file will eventually get cleaned up BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( item.TemplateBinaryFileId ); if ( binaryFile != null && binaryFile.IsTemporary ) { binaryFile.IsTemporary = false; } // reload page, selecting the deleted item's parent var qryParams = new Dictionary<string, string>(); if ( categoryId != null ) { qryParams["CategoryId"] = categoryId.ToString(); } qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); } } }
/// <summary> /// Handles the Click event of the lbPrintAttendanceRoster 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 lbPrintAttendanceRoster_Click( object sender, EventArgs e ) { // NOTE: lbPrintAttendanceRoster is a full postback since we are returning a download of the roster nbPrintRosterWarning.Visible = false; var rockContext = new RockContext(); Dictionary<int, object> mergeObjectsDictionary = new Dictionary<int, object>(); if ( _attendees != null ) { var personIdList = _attendees.Select( a => a.PersonId ).ToList(); var personList = new PersonService( rockContext ).GetByIds( personIdList ); foreach ( var person in personList.OrderBy( a => a.LastName ).ThenBy( a => a.NickName ) ) { mergeObjectsDictionary.AddOrIgnore( person.Id, person ); } } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); mergeFields.Add( "Group", this._group ); var mergeTemplate = new MergeTemplateService( rockContext ).Get( this.GetAttributeValue( "AttendanceRosterTemplate" ).AsGuid() ); if ( mergeTemplate == null ) { this.LogException( new Exception( "No Merge Template specified in block settings" ) ); nbPrintRosterWarning.Visible = true; nbPrintRosterWarning.Text = "Unable to print Attendance Roster"; return; } MergeTemplateType mergeTemplateType = mergeTemplate.GetMergeTemplateType(); if ( mergeTemplateType == null ) { this.LogException( new Exception( "Unable to determine Merge Template Type" ) ); nbPrintRosterWarning.Visible = true; nbPrintRosterWarning.Text = "Error printing Attendance Roster"; return; } BinaryFile outputBinaryFileDoc = null; var mergeObjectList = mergeObjectsDictionary.Select( a => a.Value ).ToList(); outputBinaryFileDoc = mergeTemplateType.CreateDocument( mergeTemplate, mergeObjectList, mergeFields ); // set the name of the output doc outputBinaryFileDoc = new BinaryFileService( rockContext ).Get( outputBinaryFileDoc.Id ); outputBinaryFileDoc.FileName = _group.Name + " Attendance Roster" + Path.GetExtension( outputBinaryFileDoc.FileName ?? "" ) ?? ".docx"; rockContext.SaveChanges(); if ( mergeTemplateType.Exceptions != null && mergeTemplateType.Exceptions.Any() ) { if ( mergeTemplateType.Exceptions.Count == 1 ) { this.LogException( mergeTemplateType.Exceptions[0] ); } else if ( mergeTemplateType.Exceptions.Count > 50 ) { this.LogException( new AggregateException( string.Format( "Exceptions merging template {0}. See InnerExceptions for top 50.", mergeTemplate.Name ), mergeTemplateType.Exceptions.Take( 50 ).ToList() ) ); } else { this.LogException( new AggregateException( string.Format( "Exceptions merging template {0}. See InnerExceptions", mergeTemplate.Name ), mergeTemplateType.Exceptions.ToList() ) ); } } var uri = new UriBuilder( outputBinaryFileDoc.Url ); var qry = System.Web.HttpUtility.ParseQueryString( uri.Query ); qry["attachment"] = true.ToTrueFalse(); uri.Query = qry.ToString(); Response.Redirect( uri.ToString(), false ); Context.ApplicationInstance.CompleteRequest(); }
/// <summary> /// Handles the OnSave event of the masterPage 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 masterPage_OnSave( object sender, EventArgs e ) { Page.Validate( BlockValidationGroup ); if ( Page.IsValid && _pageId.HasValue ) { var rockContext = new RockContext(); var pageService = new PageService( rockContext ); var routeService = new PageRouteService( rockContext ); var contextService = new PageContextService( rockContext ); var page = pageService.Get( _pageId.Value ); // validate/check for removed routes var editorRoutes = tbPageRoute.Text.SplitDelimitedValues().Distinct(); var databasePageRoutes = page.PageRoutes.ToList(); var deletedRouteIds = new List<int>(); var addedRoutes = new List<string>(); if ( editorRoutes.Any() ) { // validate for any duplicate routes var duplicateRoutes = routeService.Queryable() .Where( r => editorRoutes.Contains( r.Route ) && r.PageId != _pageId ) .Select( r => r.Route ) .Distinct() .ToList(); if ( duplicateRoutes.Any() ) { // Duplicate routes nbPageRouteWarning.Title = "Duplicate Route(s)"; nbPageRouteWarning.Text = string.Format( "<p>The page route <strong>{0}</strong>, already exists for another page. Please choose a different route name.</p>", duplicateRoutes.AsDelimited( "</strong> and <strong>" ) ); nbPageRouteWarning.Dismissable = true; nbPageRouteWarning.Visible = true; CurrentTab = "Advanced Settings"; rptProperties.DataSource = _tabs; rptProperties.DataBind(); ShowSelectedPane(); return; } } // validate if removed routes can be deleted foreach ( var pageRoute in databasePageRoutes ) { if ( !editorRoutes.Contains( pageRoute.Route ) ) { // make sure the route can be deleted string errorMessage; if ( !routeService.CanDelete( pageRoute, out errorMessage ) ) { nbPageRouteWarning.Text = string.Format( "The page route <strong>{0}</strong>, cannot be removed. {1}", pageRoute.Route, errorMessage ); nbPageRouteWarning.NotificationBoxType = NotificationBoxType.Warning; nbPageRouteWarning.Dismissable = true; nbPageRouteWarning.Visible = true; CurrentTab = "Advanced Settings"; rptProperties.DataSource = _tabs; rptProperties.DataBind(); ShowSelectedPane(); return; } } } // take care of deleted routes foreach ( var pageRoute in databasePageRoutes ) { if ( !editorRoutes.Contains( pageRoute.Route ) ) { // if they removed the Route, remove it from the database page.PageRoutes.Remove( pageRoute ); routeService.Delete( pageRoute ); deletedRouteIds.Add( pageRoute.Id ); } } // take care of added routes foreach ( string route in editorRoutes ) { // if they added the Route, add it to the database if ( !databasePageRoutes.Any( a => a.Route == route ) ) { var pageRoute = new PageRoute(); pageRoute.Route = route.TrimStart( new char[] { '/' } ); pageRoute.Guid = Guid.NewGuid(); page.PageRoutes.Add( pageRoute ); addedRoutes.Add( route ); } } int parentPageId = ppParentPage.SelectedValueAsInt() ?? 0; if ( page.ParentPageId != parentPageId ) { if ( page.ParentPageId.HasValue ) { PageCache.Flush( page.ParentPageId.Value ); } if ( parentPageId != 0 ) { PageCache.Flush( parentPageId ); } } page.InternalName = tbPageName.Text; page.PageTitle = tbPageTitle.Text; page.BrowserTitle = tbBrowserTitle.Text; if ( parentPageId != 0 ) { page.ParentPageId = parentPageId; } else { page.ParentPageId = null; } page.LayoutId = ddlLayout.SelectedValueAsInt().Value; int? orphanedIconFileId = null; page.IconCssClass = tbIconCssClass.Text; page.PageDisplayTitle = cbPageTitle.Checked; page.PageDisplayBreadCrumb = cbPageBreadCrumb.Checked; page.PageDisplayIcon = cbPageIcon.Checked; page.PageDisplayDescription = cbPageDescription.Checked; page.DisplayInNavWhen = ddlMenuWhen.SelectedValue.ConvertToEnumOrNull<DisplayInNavWhen>() ?? DisplayInNavWhen.WhenAllowed; page.MenuDisplayDescription = cbMenuDescription.Checked; page.MenuDisplayIcon = cbMenuIcon.Checked; page.MenuDisplayChildPages = cbMenuChildPages.Checked; page.BreadCrumbDisplayName = cbBreadCrumbName.Checked; page.BreadCrumbDisplayIcon = cbBreadCrumbIcon.Checked; page.RequiresEncryption = cbRequiresEncryption.Checked; page.EnableViewState = cbEnableViewState.Checked; page.IncludeAdminFooter = cbIncludeAdminFooter.Checked; page.OutputCacheDuration = tbCacheDuration.Text.AsIntegerOrNull() ?? 0; page.Description = tbDescription.Text; page.HeaderContent = ceHeaderContent.Text; // update PageContexts foreach ( var pageContext in page.PageContexts.ToList() ) { contextService.Delete( pageContext ); } page.PageContexts.Clear(); foreach ( var control in phContext.Controls ) { if ( control is RockTextBox ) { var tbContext = control as RockTextBox; if ( !string.IsNullOrWhiteSpace( tbContext.Text ) ) { var pageContext = new PageContext(); pageContext.Entity = tbContext.ID.Substring( 8 ).Replace( '_', '.' ); pageContext.IdParameter = tbContext.Text; page.PageContexts.Add( pageContext ); } } } // save page and it's routes if ( page.IsValid ) { rockContext.SaveChanges(); // remove any routes that were deleted foreach (var deletedRouteId in deletedRouteIds ) { var existingRoute = RouteTable.Routes.OfType<Route>().FirstOrDefault( a => a.RouteId() == deletedRouteId ); if ( existingRoute != null ) { RouteTable.Routes.Remove( existingRoute ); } } // ensure that there aren't any other extra routes for this page in the RouteTable foreach (var routeTableRoute in RouteTable.Routes.OfType<Route>().Where(a => a.PageId() == page.Id)) { if ( !editorRoutes.Any( a => a == routeTableRoute.Url ) ) { RouteTable.Routes.Remove( routeTableRoute ); } } // Add any routes that were added foreach ( var pageRoute in new PageRouteService( rockContext ).GetByPageId( page.Id ) ) { if ( addedRoutes.Contains( pageRoute.Route ) ) { RouteTable.Routes.AddPageRoute( pageRoute ); } } if ( orphanedIconFileId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedIconFileId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } Rock.Web.Cache.PageCache.Flush( page.Id ); string script = "if (typeof window.parent.Rock.controls.modal.close === 'function') window.parent.Rock.controls.modal.close('PAGE_UPDATED');"; ScriptManager.RegisterStartupScript( this.Page, this.GetType(), "close-modal", script, true ); } } }
/// <summary> /// Gets the name of the facebook user. /// </summary> /// <param name="facebookUser">The facebook user.</param> /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param> /// <param name="accessToken">The access token.</param> /// <returns></returns> public static string GetFacebookUserName( FacebookUser facebookUser, bool syncFriends = false, string accessToken = "" ) { string username = string.Empty; string facebookId = facebookUser.id; string facebookLink = facebookUser.link; string userName = "******" + facebookId; UserLogin user = null; using ( var rockContext = new RockContext() ) { // Query for an existing user var userLoginService = new UserLoginService( rockContext ); user = userLoginService.GetByUserName( userName ); // If no user was found, see if we can find a match in the person table if ( user == null ) { // Get name/email from Facebook login string lastName = facebookUser.last_name.ToStringSafe(); string firstName = facebookUser.first_name.ToStringSafe(); string email = string.Empty; try { email = facebookUser.email.ToStringSafe(); } catch { } Person person = null; // If person had an email, get the first person with the same name and email address. if ( !string.IsNullOrWhiteSpace( email ) ) { var personService = new PersonService( rockContext ); var people = personService.GetByMatch( firstName, lastName, email ); if ( people.Count() == 1) { person = people.First(); } } var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id; var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id; rockContext.WrapTransaction( () => { if ( person == null ) { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = firstName; person.LastName = lastName; person.Email = email; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; try { if ( facebookUser.gender.ToString() == "male" ) { person.Gender = Gender.Male; } else if ( facebookUser.gender.ToString() == "female" ) { person.Gender = Gender.Female; } else { person.Gender = Gender.Unknown; } } catch { } if ( person != null ) { PersonService.SaveNewPerson( person, rockContext, null, false ); } } if ( person != null ) { int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id; user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true ); } } ); } if ( user != null ) { username = user.UserName; if ( user.PersonId.HasValue ) { var converter = new ExpandoObjectConverter(); var personService = new PersonService( rockContext ); var person = personService.Get( user.PersonId.Value ); if ( person != null ) { // If person does not have a photo, try to get their Facebook photo if ( !person.PhotoId.HasValue ) { var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId ) ); var restRequest = new RestRequest( Method.GET ); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader( "Accept", "application/json" ); var restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { dynamic picData = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter ); bool isSilhouette = picData.data.is_silhouette; string url = picData.data.url; // If Facebook returned a photo url if ( !isSilhouette && !string.IsNullOrWhiteSpace( url ) ) { // Download the photo from the url provided restClient = new RestClient( url ); restRequest = new RestRequest( Method.GET ); restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { var bytes = restResponse.RawBytes; // Create and save the image BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() ); if ( fileType != null ) { var binaryFileService = new BinaryFileService( rockContext ); var binaryFile = new BinaryFile(); binaryFileService.Add( binaryFile ); binaryFile.IsTemporary = false; binaryFile.BinaryFileType = fileType; binaryFile.MimeType = "image/jpeg"; binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg"; binaryFile.ContentStream = new MemoryStream( bytes ); rockContext.SaveChanges(); person.PhotoId = binaryFile.Id; rockContext.SaveChanges(); } } } } } // Save the facebook social media link var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() ); if ( facebookAttribute != null ) { person.LoadAttributes( rockContext ); person.SetAttributeValue( facebookAttribute.Key, facebookLink ); person.SaveAttributeValues( rockContext ); } if ( syncFriends && !string.IsNullOrWhiteSpace( accessToken ) ) { // Get the friend list (only includes friends who have also authorized this app) var restRequest = new RestRequest( Method.GET ); restRequest.AddParameter( "access_token", accessToken ); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader( "Accept", "application/json" ); var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/friends", facebookId ) ); var restResponse = restClient.Execute( restRequest ); if ( restResponse.StatusCode == HttpStatusCode.OK ) { // Get a list of the facebook ids for each friend dynamic friends = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter ); var facebookIds = new List<string>(); foreach ( var friend in friends.data ) { facebookIds.Add( friend.id ); } // Queue a transaction to add/remove friend relationships in Rock var transaction = new Rock.Transactions.UpdateFacebookFriends( person.Id, facebookIds ); Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } } } } return username; } }
private static Guid? SaveFile( AttributeCache binaryFileAttribute, string url, string fileName ) { // get BinaryFileType info if ( binaryFileAttribute != null && binaryFileAttribute.QualifierValues != null && binaryFileAttribute.QualifierValues.ContainsKey( "binaryFileType" ) ) { Guid? fileTypeGuid = binaryFileAttribute.QualifierValues["binaryFileType"].Value.AsGuidOrNull(); if ( fileTypeGuid.HasValue ) { RockContext rockContext = new RockContext(); BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid.Value ); if ( binaryFileType != null ) { byte[] data = null; using ( WebClient wc = new WebClient() ) { data = wc.DownloadData( url ); } BinaryFile binaryFile = new BinaryFile(); binaryFile.Guid = Guid.NewGuid(); binaryFile.IsTemporary = true; binaryFile.BinaryFileTypeId = binaryFileType.Id; binaryFile.MimeType = "application/pdf"; binaryFile.FileName = fileName; binaryFile.ContentStream = new MemoryStream( data ); var binaryFileService = new BinaryFileService( rockContext ); binaryFileService.Add( binaryFile ); rockContext.SaveChanges(); return binaryFile.Guid; } } } return null; }
/// <summary> /// Pres the save. /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The entry.</param> public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.Infrastructure.DbEntityEntry entry) { var attributeCache = AttributeCache.Read(this.AttributeId); if (attributeCache != null) { // Check to see if this attribute value if for a Field or Image field type // ( we don't want BinaryFileFieldType as that type of attribute's file can be used by more than one attribute ) var field = attributeCache.FieldType.Field; if (field != null && ( field is Rock.Field.Types.FileFieldType || field is Rock.Field.Types.ImageFieldType)) { Guid?newBinaryFileGuid = null; Guid?oldBinaryFileGuid = null; if (entry.State == System.Data.Entity.EntityState.Added || entry.State == System.Data.Entity.EntityState.Modified) { newBinaryFileGuid = Value.AsGuidOrNull(); } if (entry.State == System.Data.Entity.EntityState.Modified || entry.State == System.Data.Entity.EntityState.Deleted) { if (entry.OriginalValues["Value"] != null) { oldBinaryFileGuid = entry.OriginalValues["Value"].ToString().AsGuidOrNull(); } } if (oldBinaryFileGuid.HasValue) { if (!newBinaryFileGuid.HasValue || !newBinaryFileGuid.Value.Equals(oldBinaryFileGuid.Value)) { var transaction = new Rock.Transactions.DeleteAttributeBinaryFile(oldBinaryFileGuid.Value); Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction); } } if (newBinaryFileGuid.HasValue) { BinaryFileService binaryFileService = new BinaryFileService((RockContext)dbContext); var binaryFile = binaryFileService.Get(newBinaryFileGuid.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } // Check to see if this attribute is for a person or group, and if so, save history if (attributeCache.EntityTypeId.HasValue && (attributeCache.EntityTypeId.Value == EntityTypeCache.Read(typeof(Person)).Id || attributeCache.EntityTypeId.Value == EntityTypeCache.Read(typeof(Group)).Id)) { string oldValue = string.Empty; string newValue = string.Empty; HistoryEntityTypeId = attributeCache.EntityTypeId.Value; HistoryEntityId = EntityId; switch (entry.State) { case System.Data.Entity.EntityState.Added: { newValue = Value; break; } case System.Data.Entity.EntityState.Modified: { oldValue = entry.OriginalValues["Value"].ToStringSafe(); newValue = Value; break; } case System.Data.Entity.EntityState.Deleted: { HistoryEntityId = entry.OriginalValues["EntityId"].ToStringSafe().AsIntegerOrNull(); oldValue = entry.OriginalValues["Value"].ToStringSafe(); return; } } if (oldValue != newValue) { oldValue = oldValue.IsNotNullOrWhitespace() ? attributeCache.FieldType.Field.FormatValue(null, oldValue, attributeCache.QualifierValues, true) : string.Empty; newValue = newValue.IsNotNullOrWhitespace() ? attributeCache.FieldType.Field.FormatValue(null, newValue, attributeCache.QualifierValues, true) : string.Empty; HistoryChanges = new List <string>(); History.EvaluateChange(HistoryChanges, attributeCache.Name, oldValue, newValue); } } } base.PreSaveChanges(dbContext, entry); }
/// <summary> /// Reads the specified label by id. /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public static KioskLabel Read( int id ) { string cacheKey = KioskLabel.CacheKey( id ); ObjectCache cache = MemoryCache.Default; KioskLabel label = cache[cacheKey] as KioskLabel; if ( label != null ) { return label; } else { var file = new BinaryFileService( new RockContext() ).Get( id ); if ( file != null ) { label = new KioskLabel(); label.Guid = file.Guid; label.Url = string.Format( "{0}GetFile.ashx?id={1}", System.Web.VirtualPathUtility.ToAbsolute( "~" ), file.Id ); label.MergeFields = new Dictionary<string, string>(); label.FileContent = System.Text.Encoding.Default.GetString( file.Data.Content ); file.LoadAttributes(); string attributeValue = file.GetAttributeValue( "MergeCodes" ); if ( !string.IsNullOrWhiteSpace( attributeValue ) ) { string[] nameValues = attributeValue.Split( new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries ); foreach ( string nameValue in nameValues ) { string[] nameAndValue = nameValue.Split( new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries ); if ( nameAndValue.Length == 2 && !label.MergeFields.ContainsKey( nameAndValue[0] ) ) { label.MergeFields.Add( nameAndValue[0], nameAndValue[1] ); int definedValueId = int.MinValue; if ( int.TryParse( nameAndValue[1], out definedValueId ) ) { var definedValue = DefinedValueCache.Read( definedValueId ); if ( definedValue != null ) { string mergeField = definedValue.GetAttributeValue( "MergeField" ); if ( mergeField != null ) { label.MergeFields[nameAndValue[0]] = mergeField; } } } } } } var cachePolicy = new CacheItemPolicy(); cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds( 60 ); cache.Set( cacheKey, label, cachePolicy ); return label; } } return null; }
/// <summary> /// Sends the specified communication. /// </summary> /// <param name="communication">The communication.</param> /// <exception cref="System.NotImplementedException"></exception> public override void Send( Rock.Model.Communication communication ) { using ( var rockContext = new RockContext() ) { // Requery the Communication object communication = new CommunicationService( rockContext ) .Queryable( "CreatedByPersonAlias.Person" ) .FirstOrDefault( c => c.Id == communication.Id ); if ( communication != null && communication.Status == Model.CommunicationStatus.Approved && communication.Recipients.Where( r => r.Status == Model.CommunicationRecipientStatus.Pending ).Any() && ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo( RockDateTime.Now ) <= 0 ) ) { var currentPerson = communication.CreatedByPersonAlias.Person; var globalAttributes = Rock.Web.Cache.GlobalAttributesCache.Read(); var globalConfigValues = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields( currentPerson ); // From - if none is set, use the one in the Organization's GlobalAttributes. string fromAddress = communication.GetMediumDataValue( "FromAddress" ); if ( string.IsNullOrWhiteSpace( fromAddress ) ) { fromAddress = globalAttributes.GetValue( "OrganizationEmail" ); } string fromName = communication.GetMediumDataValue( "FromName" ); if ( string.IsNullOrWhiteSpace( fromName ) ) { fromName = globalAttributes.GetValue( "OrganizationName" ); } // Resolve any possible merge fields in the from address fromAddress = fromAddress.ResolveMergeFields( globalConfigValues, currentPerson ); fromName = fromName.ResolveMergeFields( globalConfigValues, currentPerson ); MailMessage message = new MailMessage(); message.From = new MailAddress( fromAddress, fromName ); // Reply To string replyTo = communication.GetMediumDataValue( "ReplyTo" ); if ( !string.IsNullOrWhiteSpace( replyTo ) ) { message.ReplyToList.Add( new MailAddress( replyTo ) ); } CheckSafeSender( message, globalAttributes ); // CC string cc = communication.GetMediumDataValue( "CC" ); if ( !string.IsNullOrWhiteSpace( cc ) ) { foreach ( string ccRecipient in cc.SplitDelimitedValues() ) { message.CC.Add( new MailAddress( ccRecipient ) ); } } // BCC string bcc = communication.GetMediumDataValue( "BCC" ); if ( !string.IsNullOrWhiteSpace( bcc ) ) { foreach ( string bccRecipient in bcc.SplitDelimitedValues() ) { message.Bcc.Add( new MailAddress( bccRecipient ) ); } } message.IsBodyHtml = true; message.Priority = MailPriority.Normal; using ( var smtpClient = GetSmtpClient() ) { // Add Attachments string attachmentIds = communication.GetMediumDataValue( "Attachments" ); if ( !string.IsNullOrWhiteSpace( attachmentIds ) ) { var binaryFileService = new BinaryFileService( rockContext ); foreach ( string idVal in attachmentIds.SplitDelimitedValues() ) { int binaryFileId = int.MinValue; if ( int.TryParse( idVal, out binaryFileId ) ) { var binaryFile = binaryFileService.Get( binaryFileId ); if ( binaryFile != null ) { message.Attachments.Add( new Attachment( binaryFile.ContentStream, binaryFile.FileName ) ); } } } } var historyService = new HistoryService( rockContext ); var recipientService = new CommunicationRecipientService( rockContext ); var personEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; var communicationEntityTypeId = EntityTypeCache.Read( "Rock.Model.Communication" ).Id; var communicationCategoryId = CategoryCache.Read( Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), rockContext ).Id; bool recipientFound = true; while ( recipientFound ) { var recipient = Rock.Model.Communication.GetNextPending( communication.Id, rockContext ); if ( recipient != null ) { if ( string.IsNullOrWhiteSpace( recipient.PersonAlias.Person.Email ) ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "No Email Address"; } else { try { message.To.Clear(); message.Headers.Clear(); message.AlternateViews.Clear(); message.To.Add( new MailAddress( recipient.PersonAlias.Person.Email, recipient.PersonAlias.Person.FullName ) ); // Create merge field dictionary var mergeObjects = recipient.CommunicationMergeValues( globalConfigValues ); // Subject message.Subject = communication.Subject.ResolveMergeFields( mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny (for example "Hey “double-quotes†from ‘single quote’") message.Subject = message.Subject.ReplaceWordChars(); // Add any additional headers that specific SMTP provider needs AddAdditionalHeaders( message, recipient ); // Add text view first as last view is usually treated as the preferred view by email readers (gmail) string plainTextBody = Rock.Communication.Medium.Email.ProcessTextBody( communication, globalAttributes, mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny plainTextBody = plainTextBody.ReplaceWordChars(); if ( !string.IsNullOrWhiteSpace( plainTextBody ) ) { AlternateView plainTextView = AlternateView.CreateAlternateViewFromString( plainTextBody, new System.Net.Mime.ContentType( MediaTypeNames.Text.Plain ) ); message.AlternateViews.Add( plainTextView ); } // Add Html view string htmlBody = Rock.Communication.Medium.Email.ProcessHtmlBody( communication, globalAttributes, mergeObjects, currentPerson ); // convert any special microsoft word characters to normal chars so they don't look funny htmlBody = htmlBody.ReplaceWordChars(); if ( !string.IsNullOrWhiteSpace( htmlBody ) ) { AlternateView htmlView = AlternateView.CreateAlternateViewFromString( htmlBody, new System.Net.Mime.ContentType( MediaTypeNames.Text.Html ) ); message.AlternateViews.Add( htmlView ); } smtpClient.Send( message ); recipient.Status = CommunicationRecipientStatus.Delivered; string statusNote = StatusNote; if ( !string.IsNullOrWhiteSpace( statusNote ) ) { recipient.StatusNote = statusNote; } recipient.TransportEntityTypeName = this.GetType().FullName; historyService.Add( new History { CreatedByPersonAliasId = communication.SenderPersonAliasId, EntityTypeId = personEntityTypeId, CategoryId = communicationCategoryId, EntityId = recipient.PersonAlias.PersonId, Summary = string.Format( "Sent communication from <span class='field-value'>{0}</span>.", message.From.DisplayName ), Caption = message.Subject, RelatedEntityTypeId = communicationEntityTypeId, RelatedEntityId = communication.Id } ); } catch ( Exception ex ) { recipient.Status = CommunicationRecipientStatus.Failed; recipient.StatusNote = "Exception: " + ex.Message; } } rockContext.SaveChanges(); } else { recipientFound = false; } } } } } }
/// <summary> /// Pres the save. /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="entry">The entry.</param> public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.Infrastructure.DbEntityEntry entry) { var attributeCache = AttributeCache.Get(this.AttributeId); if (attributeCache != null) { // Check to see if this attribute value if for a Field or Image field type // ( we don't want BinaryFileFieldType as that type of attribute's file can be used by more than one attribute ) var field = attributeCache.FieldType.Field; if (field != null && ( field is Rock.Field.Types.FileFieldType || field is Rock.Field.Types.ImageFieldType)) { Guid?newBinaryFileGuid = null; Guid?oldBinaryFileGuid = null; if (entry.State == System.Data.Entity.EntityState.Added || entry.State == System.Data.Entity.EntityState.Modified) { newBinaryFileGuid = Value.AsGuidOrNull(); } if (entry.State == System.Data.Entity.EntityState.Modified || entry.State == System.Data.Entity.EntityState.Deleted) { if (entry.OriginalValues["Value"] != null) { oldBinaryFileGuid = entry.OriginalValues["Value"].ToString().AsGuidOrNull(); } } if (oldBinaryFileGuid.HasValue) { if (!newBinaryFileGuid.HasValue || !newBinaryFileGuid.Value.Equals(oldBinaryFileGuid.Value)) { var transaction = new Rock.Transactions.DeleteAttributeBinaryFile(oldBinaryFileGuid.Value); Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction); } } if (newBinaryFileGuid.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(( RockContext )dbContext); var binaryFile = binaryFileService.Get(newBinaryFileGuid.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } // Check to see if this attribute is for a person or group, and if so, save to history table bool saveToHistoryTable = attributeCache.EntityTypeId.HasValue && (attributeCache.EntityTypeId.Value == EntityTypeCache.Get(typeof(Person)).Id || attributeCache.EntityTypeId.Value == EntityTypeCache.Get(typeof(Group)).Id); if (saveToHistoryTable || attributeCache.EnableHistory) { string oldValue = string.Empty; string newValue = string.Empty; HistoryEntityTypeId = attributeCache.EntityTypeId.Value; HistoryEntityId = EntityId; switch (entry.State) { case System.Data.Entity.EntityState.Added: { newValue = Value; break; } case System.Data.Entity.EntityState.Modified: { oldValue = entry.OriginalValues["Value"].ToStringSafe(); newValue = Value; break; } case System.Data.Entity.EntityState.Deleted: { HistoryEntityId = entry.OriginalValues["EntityId"].ToStringSafe().AsIntegerOrNull(); oldValue = entry.OriginalValues["Value"].ToStringSafe(); return; } } this.PostSaveAttributeValueHistoryCurrent = false; if (oldValue != newValue) { var formattedOldValue = oldValue.IsNotNullOrWhiteSpace() ? attributeCache.FieldType.Field.FormatValue(null, oldValue, attributeCache.QualifierValues, true) : string.Empty; var formattedNewValue = newValue.IsNotNullOrWhiteSpace() ? attributeCache.FieldType.Field.FormatValue(null, newValue, attributeCache.QualifierValues, true) : string.Empty; if (saveToHistoryTable) { HistoryChanges = new History.HistoryChangeList(); History.EvaluateChange(HistoryChanges, attributeCache.Name, formattedOldValue, formattedNewValue); } if (attributeCache.EnableHistory) { // value changed and attribute.EnableHistory = true, so flag PostSaveAttributeValueHistoryCurrent this.PostSaveAttributeValueHistoryCurrent = true; var attributeValueHistoricalService = new AttributeValueHistoricalService(dbContext as RockContext); if (this.Id > 0) { // this is an existing AttributeValue, so fetch the AttributeValue that is currently marked as CurrentRow for this attribute value (if it exists) bool hasAttributeValueHistoricalCurrentRow = attributeValueHistoricalService.Queryable().Where(a => a.AttributeValueId == this.Id && a.CurrentRowIndicator == true).Any(); if (!hasAttributeValueHistoricalCurrentRow) { // this is an existing AttributeValue but there isn't a CurrentRow AttributeValueHistorical for this AttributeValue yet, so create it off of the OriginalValues AttributeValueHistorical attributeValueHistoricalPreviousCurrentRow = new AttributeValueHistorical { AttributeValueId = this.Id, Value = oldValue, ValueFormatted = formattedOldValue, ValueAsNumeric = entry.OriginalValues["ValueAsNumeric"] as decimal?, ValueAsDateTime = entry.OriginalValues["ValueAsDateTime"] as DateTime?, ValueAsBoolean = entry.OriginalValues["ValueAsBoolean"] as bool?, ValueAsPersonId = entry.OriginalValues["ValueAsPersonId"] as int?, EffectiveDateTime = entry.OriginalValues["ModifiedDateTime"] as DateTime? ?? RockDateTime.Now, CurrentRowIndicator = true, ExpireDateTime = HistoricalTracking.MaxExpireDateTime }; attributeValueHistoricalService.Add(attributeValueHistoricalPreviousCurrentRow); } } } } } } base.PreSaveChanges(dbContext, entry); }
/// <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 ) { Location location; var rockContext = new RockContext(); LocationService locationService = new LocationService( rockContext ); AttributeService attributeService = new AttributeService( rockContext ); AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext ); int locationId = int.Parse( hfLocationId.Value ); if ( locationId == 0 ) { location = new Location(); location.Name = string.Empty; } else { location = locationService.Get( locationId ); FlushCampus( locationId ); } int? orphanedImageId = null; if ( location.ImageId != imgImage.BinaryFileId ) { orphanedImageId = location.ImageId; location.ImageId = imgImage.BinaryFileId; } location.Name = tbName.Text; location.IsActive = cbIsActive.Checked; location.LocationTypeValueId = ddlLocationType.SelectedValueAsId(); if ( gpParentLocation != null && gpParentLocation.Location != null ) { location.ParentLocationId = gpParentLocation.Location.Id; } else { location.ParentLocationId = null; } location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt(); acAddress.GetValues(location); location.GeoPoint = geopPoint.SelectedValue; if ( geopPoint.SelectedValue != null ) { location.IsGeoPointLocked = true; } location.GeoFence = geopFence.SelectedValue; location.IsGeoPointLocked = cbGeoPointLocked.Checked; location.LoadAttributes( rockContext ); Rock.Attribute.Helper.GetEditValues( phAttributeEdits, location ); if ( !Page.IsValid ) { return; } if ( !location.IsValid ) { // Controls will render the error messages return; } rockContext.WrapTransaction( () => { if ( location.Id.Equals( 0 ) ) { locationService.Add( location ); } rockContext.SaveChanges(); if (orphanedImageId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedImageId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } location.SaveAttributeValues( rockContext ); } ); var qryParams = new Dictionary<string, string>(); qryParams["LocationId"] = location.Id.ToString(); qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" ); NavigateToPage( RockPage.Guid, qryParams ); }
/// <summary> /// Handles the SaveClick event of the modalDetails 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 modalDetails_SaveClick( object sender, EventArgs e ) { int categoryId = 0; if ( hfIdValue.Value != string.Empty && !int.TryParse( hfIdValue.Value, out categoryId ) ) { categoryId = 0; } var rockContext = new RockContext(); var service = new CategoryService( rockContext ); Category category = null; if ( categoryId != 0 ) { CategoryCache.Flush( categoryId ); category = service.Get( categoryId ); } if ( category == null ) { category = new Category(); category.EntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.Attribute ) ).Id; category.EntityTypeQualifierColumn = "EntityTypeId"; var lastCategory = GetUnorderedCategories() .OrderByDescending( c => c.Order ).FirstOrDefault(); category.Order = lastCategory != null ? lastCategory.Order + 1 : 0; service.Add( category ); } category.Name = tbName.Text; category.Description = tbDescription.Text; string QualifierValue = null; if ( ( entityTypePicker.SelectedEntityTypeId ?? 0 ) != 0 ) { QualifierValue = entityTypePicker.SelectedEntityTypeId.ToString(); } category.EntityTypeQualifierValue = QualifierValue; category.IconCssClass = tbIconCssClass.Text; category.HighlightColor = tbHighlightColor.Text; List<int> orphanedBinaryFileIdList = new List<int>(); if ( category.IsValid ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); foreach ( int binaryFileId in orphanedBinaryFileIdList ) { var binaryFile = binaryFileService.Get( binaryFileId ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; } } rockContext.SaveChanges(); hfIdValue.Value = string.Empty; modalDetails.Hide(); BindGrid(); } }
/// <summary> /// Creates the document. /// </summary> /// <param name="mergeTemplate">The merge template.</param> /// <param name="mergeObjectList">The merge object list.</param> /// <param name="globalMergeFields">The global merge fields.</param> /// <returns></returns> public override BinaryFile CreateDocument( MergeTemplate mergeTemplate, List<object> mergeObjectList, Dictionary<string, object> globalMergeFields ) { this.Exceptions = new List<Exception>(); BinaryFile outputBinaryFile = null; var rockContext = new RockContext(); var binaryFileService = new BinaryFileService( rockContext ); var templateBinaryFile = binaryFileService.Get( mergeTemplate.TemplateBinaryFileId ); if ( templateBinaryFile == null ) { return null; } string templateHtml = templateBinaryFile.ContentsToString(); var htmlMergeObjects = GetHtmlMergeObjects( mergeObjectList, globalMergeFields ); string outputHtml = templateHtml.ResolveMergeFields( htmlMergeObjects ); HtmlDocument outputDoc = new HtmlDocument(); outputDoc.LoadHtml( outputHtml ); var outputStream = new MemoryStream(); outputDoc.Save( outputStream ); outputBinaryFile = new BinaryFile(); outputBinaryFile.IsTemporary = true; outputBinaryFile.ContentStream = outputStream; outputBinaryFile.FileName = "MergeTemplateOutput" + Path.GetExtension( templateBinaryFile.FileName ); outputBinaryFile.MimeType = templateBinaryFile.MimeType; outputBinaryFile.BinaryFileTypeId = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid() ).Id; binaryFileService.Add( outputBinaryFile ); rockContext.SaveChanges(); return outputBinaryFile; }
/// <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 ) { ConnectionOpportunity connectionOpportunity = null; using ( RockContext rockContext = new RockContext() ) { int? groupTypeId = ddlGroupType.SelectedValueAsInt(); if ( groupTypeId.HasValue && GroupsState.Any( g => g.Group.GroupTypeId != groupTypeId.Value ) ) { var groupType = new GroupTypeService( rockContext ).Get( groupTypeId.Value ); if ( groupType != null ) { nbInvalidGroupTypes.Text = string.Format( "<p>One or more of the selected groups is not a <strong>{0}</strong> type. Please select groups that have a group type of <strong>{0}</strong>.", groupType.Name ); nbInvalidGroupTypes.Visible = true; return; } } ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService( rockContext ); EventCalendarItemService eventCalendarItemService = new EventCalendarItemService( rockContext ); ConnectionWorkflowService connectionWorkflowService = new ConnectionWorkflowService( rockContext ); ConnectionOpportunityConnectorGroupService connectionOpportunityConnectorGroupsService = new ConnectionOpportunityConnectorGroupService( rockContext ); ConnectionOpportunityCampusService connectionOpportunityCampusService = new ConnectionOpportunityCampusService( rockContext ); ConnectionOpportunityGroupService connectionOpportunityGroupService = new ConnectionOpportunityGroupService( rockContext ); int connectionOpportunityId = hfConnectionOpportunityId.ValueAsInt(); if ( connectionOpportunityId != 0 ) { connectionOpportunity = connectionOpportunityService .Queryable( "ConnectionOpportunityGroups, ConnectionWorkflows" ) .Where( ei => ei.Id == connectionOpportunityId ) .FirstOrDefault(); } if ( connectionOpportunity == null ) { connectionOpportunity = new ConnectionOpportunity(); connectionOpportunity.Name = string.Empty; connectionOpportunity.ConnectionTypeId = PageParameter( "ConnectionTypeId" ).AsInteger(); connectionOpportunityService.Add( connectionOpportunity ); } connectionOpportunity.Name = tbName.Text; connectionOpportunity.Description = tbDescription.Text; connectionOpportunity.IsActive = cbIsActive.Checked; connectionOpportunity.PublicName = tbPublicName.Text; connectionOpportunity.IconCssClass = tbIconCssClass.Text; connectionOpportunity.GroupTypeId = ddlGroupType.SelectedValue.AsInteger(); connectionOpportunity.GroupMemberRoleId = ddlGroupRole.SelectedValue.AsInteger(); connectionOpportunity.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); int? orphanedPhotoId = null; if ( imgupPhoto.BinaryFileId != null ) { if ( connectionOpportunity.PhotoId != imgupPhoto.BinaryFileId ) { orphanedPhotoId = connectionOpportunity.PhotoId; } connectionOpportunity.PhotoId = imgupPhoto.BinaryFileId.Value; } // remove any workflows that removed in the UI var uiWorkflows = WorkflowsState.Where( w => w.ConnectionTypeId == null ).Select( l => l.Guid ); foreach ( var connectionOpportunityWorkflow in connectionOpportunity.ConnectionWorkflows.Where( l => !uiWorkflows.Contains( l.Guid ) ).ToList() ) { connectionOpportunity.ConnectionWorkflows.Remove( connectionOpportunityWorkflow ); connectionWorkflowService.Delete( connectionOpportunityWorkflow ); } // Add or Update workflows from the UI foreach ( ConnectionWorkflow connectionOpportunityWorkflowState in WorkflowsState.Where( w => w.ConnectionTypeId == null ) ) { ConnectionWorkflow connectionOpportunityWorkflow = connectionOpportunity.ConnectionWorkflows.Where( a => a.Guid == connectionOpportunityWorkflowState.Guid ).FirstOrDefault(); if ( connectionOpportunityWorkflow == null ) { connectionOpportunityWorkflow = new ConnectionWorkflow(); connectionOpportunity.ConnectionWorkflows.Add( connectionOpportunityWorkflow ); } connectionOpportunityWorkflow.CopyPropertiesFrom( connectionOpportunityWorkflowState ); connectionOpportunityWorkflow.ConnectionOpportunityId = connectionOpportunity.Id; } // remove any group campuses that removed in the UI var uiGroupCampuses = GroupCampusesState.Select( l => l.Guid ); foreach ( var connectionOpportunityConnectorGroups in connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( l => !uiGroupCampuses.Contains( l.Guid ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityConnectorGroups.Remove( connectionOpportunityConnectorGroups ); connectionOpportunityConnectorGroupsService.Delete( connectionOpportunityConnectorGroups ); } // Add or Update group campuses from the UI foreach ( var connectionOpportunityConnectorGroupsState in GroupCampusesState ) { ConnectionOpportunityConnectorGroup connectionOpportunityConnectorGroups = connectionOpportunity.ConnectionOpportunityConnectorGroups.Where( a => a.Guid == connectionOpportunityConnectorGroupsState.Guid ).FirstOrDefault(); if ( connectionOpportunityConnectorGroups == null ) { connectionOpportunityConnectorGroups = new ConnectionOpportunityConnectorGroup(); connectionOpportunity.ConnectionOpportunityConnectorGroups.Add( connectionOpportunityConnectorGroups ); } connectionOpportunityConnectorGroups.CopyPropertiesFrom( connectionOpportunityConnectorGroupsState ); } // remove any campuses that removed in the UI var uiCampuses = cblCampus.SelectedValuesAsInt; foreach ( var connectionOpportunityCampus in connectionOpportunity.ConnectionOpportunityCampuses.Where( c => !uiCampuses.Contains( c.CampusId ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityCampuses.Remove( connectionOpportunityCampus ); connectionOpportunityCampusService.Delete( connectionOpportunityCampus ); } // Add or Update campuses from the UI foreach ( var campusId in uiCampuses ) { ConnectionOpportunityCampus connectionOpportunityCampus = connectionOpportunity.ConnectionOpportunityCampuses.Where( c => c.CampusId == campusId ).FirstOrDefault(); if ( connectionOpportunityCampus == null ) { connectionOpportunityCampus = new ConnectionOpportunityCampus(); connectionOpportunity.ConnectionOpportunityCampuses.Add( connectionOpportunityCampus ); } connectionOpportunityCampus.CampusId = campusId; } // Remove any groups that were removed in the UI var uiGroups = GroupsState.Select( r => r.Guid ); foreach ( var connectionOpportunityGroup in connectionOpportunity.ConnectionOpportunityGroups.Where( r => !uiGroups.Contains( r.Guid ) ).ToList() ) { connectionOpportunity.ConnectionOpportunityGroups.Remove( connectionOpportunityGroup ); connectionOpportunityGroupService.Delete( connectionOpportunityGroup ); } // Add or Update groups from the UI foreach ( var connectionOpportunityGroupState in GroupsState ) { ConnectionOpportunityGroup connectionOpportunityGroup = connectionOpportunity.ConnectionOpportunityGroups.Where( a => a.Guid == connectionOpportunityGroupState.Guid ).FirstOrDefault(); if ( connectionOpportunityGroup == null ) { connectionOpportunityGroup = new ConnectionOpportunityGroup(); connectionOpportunity.ConnectionOpportunityGroups.Add( connectionOpportunityGroup ); } connectionOpportunityGroup.CopyPropertiesFrom( connectionOpportunityGroupState ); } connectionOpportunity.LoadAttributes(); Rock.Attribute.Helper.GetEditValues( phAttributes, connectionOpportunity ); if ( !Page.IsValid ) { return; } if ( !connectionOpportunity.IsValid ) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction( () => { rockContext.SaveChanges(); connectionOpportunity.SaveAttributeValues( rockContext ); if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } ); var qryParams = new Dictionary<string, string>(); qryParams["ConnectionTypeId"] = PageParameter( "ConnectionTypeId" ); NavigateToParentPage( qryParams ); } }
/// <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 ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var person = personService.Get( CurrentPersonId ?? 0 ); if ( person != null ) { int? orphanedPhotoId = null; if ( person.PhotoId != imgPhoto.BinaryFileId ) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if ( orphanedPhotoId.HasValue ) { if ( person.PhotoId.HasValue ) { changes.Add( "Modified the photo." ); } else { changes.Add( "Deleted the photo." ); } } else if ( person.PhotoId.HasValue ) { changes.Add( "Added a photo." ); } } int? newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) ); person.TitleValueId = newTitleId; History.EvaluateChange( changes, "First Name", person.FirstName, tbFirstName.Text ); person.FirstName = tbFirstName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text); person.NickName = tbNickName.Text; History.EvaluateChange( changes, "Last Name", person.LastName, tbLastName.Text ); person.LastName = tbLastName.Text; int? newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) ); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if ( birthday.HasValue ) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while ( birthday.Value.CompareTo( today ) > 0 ) { birthday = birthday.Value.AddYears( -100 ); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate( null ); } History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth ); History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay ); History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear ); var newGender = rblGender.SelectedValue.ConvertToEnum<Gender>(); History.EvaluateChange( changes, "Gender", person.Gender, newGender ); person.Gender = newGender; var phoneNumberTypeIds = new List<int>(); bool smsSelected = false; foreach ( RepeaterItem item in rContactInfo.Items ) { HiddenField hfPhoneType = item.FindControl( "hfPhoneType" ) as HiddenField; PhoneNumberBox pnbPhone = item.FindControl( "pnbPhone" ) as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl( "cbUnlisted" ) as CheckBox; CheckBox cbSms = item.FindControl( "cbSms" ) as CheckBox; if ( hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null ) { if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { int phoneNumberTypeId; if ( int.TryParse( hfPhoneType.Value, out phoneNumberTypeId ) ) { var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneNumberTypeId ); string oldPhoneNumber = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add( phoneNumber ); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); // Only allow one number to have SMS selected if ( smsSelected ) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add( phoneNumberTypeId ); History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumberTypeId ) ), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode ); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService( rockContext ); foreach ( var phoneNumber in person.PhoneNumbers .Where( n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains( n.NumberTypeValueId.Value ) ) .ToList() ) { History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( phoneNumber.NumberTypeValueId ) ), phoneNumber.ToString(), string.Empty ); person.PhoneNumbers.Remove( phoneNumber ); phoneNumberService.Delete( phoneNumber ); } History.EvaluateChange( changes, "Email", person.Email, tbEmail.Text ); person.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference ); person.EmailPreference = newEmailPreference; if ( person.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } if ( orphanedPhotoId.HasValue ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( orphanedPhotoId.Value ); if ( binaryFile != null ) { // marked the old images as IsTemporary so they will get cleaned up later binaryFile.IsTemporary = true; rockContext.SaveChanges(); } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if ( imgPhoto.CropBinaryFileId.HasValue ) { if ( imgPhoto.CropBinaryFileId != person.PhotoId ) { BinaryFileService binaryFileService = new BinaryFileService( rockContext ); var binaryFile = binaryFileService.Get( imgPhoto.CropBinaryFileId.Value ); if ( binaryFile != null && binaryFile.IsTemporary ) { string errorMessage; if ( binaryFileService.CanDelete( binaryFile, out errorMessage ) ) { binaryFileService.Delete( binaryFile ); rockContext.SaveChanges(); } } } } } // save address if ( pnlAddress.Visible ) { Guid? familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull(); if ( familyGroupTypeGuid.HasValue ) { var familyGroup = new GroupService( rockContext ).Queryable() .Where( f => f.GroupType.Guid == familyGroupTypeGuid.Value && f.Members.Any( m => m.PersonId == person.Id ) ) .FirstOrDefault(); if ( familyGroup != null ) { Guid? addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull(); if ( addressTypeGuid.HasValue ) { var groupLocationService = new GroupLocationService( rockContext ); var dvHomeAddressType = DefinedValueCache.Read( addressTypeGuid.Value ); var familyAddress = groupLocationService.Queryable().Where( l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id ).FirstOrDefault(); if ( familyAddress != null && string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { // delete the current address History.EvaluateChange( changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty ); groupLocationService.Delete( familyAddress ); rockContext.SaveChanges(); } else { if ( !string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { if ( familyAddress == null ) { familyAddress = new GroupLocation(); groupLocationService.Add( familyAddress ); familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id; familyAddress.GroupId = familyGroup.Id; familyAddress.IsMailingLocation = true; familyAddress.IsMappedLocation = true; } else if ( hfStreet1.Value != string.Empty ) { // user clicked move so create a previous address var previousAddress = new GroupLocation(); groupLocationService.Add( previousAddress ); var previousAddressValue = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid() ); if ( previousAddressValue != null ) { previousAddress.GroupLocationTypeValueId = previousAddressValue.Id; previousAddress.GroupId = familyGroup.Id; Location previousAddressLocation = new Location(); previousAddressLocation.Street1 = hfStreet1.Value; previousAddressLocation.Street2 = hfStreet2.Value; previousAddressLocation.City = hfCity.Value; previousAddressLocation.State = hfState.Value; previousAddressLocation.PostalCode = hfPostalCode.Value; previousAddressLocation.Country = hfCountry.Value; previousAddress.Location = previousAddressLocation; } } familyAddress.IsMailingLocation = cbIsMailingAddress.Checked; familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked; var updatedHomeAddress = new Location(); acAddress.GetValues( updatedHomeAddress ); History.EvaluateChange( changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString() ); familyAddress.Location = updatedHomeAddress; rockContext.SaveChanges(); } } HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes ); } } } } NavigateToParentPage(); } } } ); }
/// <summary> /// Handles the Delete event to delete the photo. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param> protected void rGrid_Delete( object sender, RowEventArgs e ) { RockContext rockContext = new RockContext(); int currentRowsPersonId = (int)e.RowKeyValues["PersonId"]; GroupService groupService = new GroupService( rockContext ); BinaryFileService binaryFileService = new BinaryFileService( rockContext ); // Set their group member record to Active Group group = groupService.Get( Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid() ); GroupMember groupMember = group.Members.Where( m => m.PersonId == currentRowsPersonId ).FirstOrDefault(); if ( groupMember != null ) { binaryFileService.Delete( groupMember.Person.Photo ); groupMember.GroupMemberStatus = GroupMemberStatus.Active; groupMember.Person.Photo = null; groupMember.Person.PhotoId = null; rockContext.SaveChanges(); _photoRequestGroup = group; BindGrid(); } }