/// <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)
            {
                string itemId = PageParameter("binaryFileTypeId");
                if (!string.IsNullOrWhiteSpace(itemId))
                {
                    ShowDetail("binaryFileTypeId", int.Parse(itemId));
                }
                else
                {
                    pnlDetails.Visible = false;
                }
            }
            else
            {
                if (pnlDetails.Visible)
                {
                    var storageEntityType = EntityTypeCache.Read(cpStorageType.SelectedValue.AsGuid());
                    if (storageEntityType != null)
                    {
                        var binaryFileType = new BinaryFileType {
                            StorageEntityTypeId = storageEntityType.Id
                        };
                        binaryFileType.LoadAttributes();
                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, false);
                    }
                }
            }
        }
        /// <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("BinaryFileTypeId").AsInteger());
            }
            else
            {
                if (pnlDetails.Visible)
                {
                    var storageEntityType = EntityTypeCache.Get(cpStorageType.SelectedValue.AsGuid());
                    if (storageEntityType != null)
                    {
                        var binaryFileType = new BinaryFileType {
                            StorageEntityTypeId = storageEntityType.Id
                        };
                        binaryFileType.LoadAttributes();
                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, false, BlockValidationGroup);
                    }
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            Guid binaryFileTypeGuid = Guid.NewGuid();
            if ( Guid.TryParse( GetAttributeValue( "BinaryFileType" ), out binaryFileTypeGuid ) )
            {
                var service = new BinaryFileTypeService();
                binaryFileType = service.Get( binaryFileTypeGuid );
            }

            BindFilter();
            fBinaryFile.ApplyFilterClick += fBinaryFile_ApplyFilterClick;
            
            gBinaryFile.DataKeyNames = new string[] { "id" };
            gBinaryFile.Actions.ShowAdd = true;
            gBinaryFile.Actions.AddClick += gBinaryFile_Add;
            gBinaryFile.GridRebind += gBinaryFile_GridRebind;
            gBinaryFile.RowItemText = binaryFileType != null ? binaryFileType.Name : "Binary File";

            // Block Security and special attributes (RockPage takes care of "View")
            bool canAddEditDelete = IsUserAuthorized( "Edit" );
            gBinaryFile.Actions.ShowAdd = canAddEditDelete;
            gBinaryFile.IsDeleteEnabled = canAddEditDelete;
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            Guid binaryFileTypeGuid = Guid.NewGuid();
            if ( Guid.TryParse( GetAttributeValue( "BinaryFileType" ), out binaryFileTypeGuid ) )
            {
                var service = new BinaryFileTypeService( new RockContext() );
                binaryFileType = service.Get( binaryFileTypeGuid );
            }

            BindFilter();
            fBinaryFile.ApplyFilterClick += fBinaryFile_ApplyFilterClick;

            gBinaryFile.DataKeyNames = new string[] { "Id" };
            gBinaryFile.Actions.ShowAdd = true;
            gBinaryFile.Actions.AddClick += gBinaryFile_Add;
            gBinaryFile.GridRebind += gBinaryFile_GridRebind;
            gBinaryFile.RowItemText = binaryFileType != null ? binaryFileType.Name : "Binary File";

            // Block Security and special attributes (RockPage takes care of View)
            bool canAddEditDelete = IsUserAuthorized( Authorization.EDIT );
            gBinaryFile.Actions.ShowAdd = canAddEditDelete;
            gBinaryFile.IsDeleteEnabled = canAddEditDelete;
        }
 public ChunkInfo(BinaryFileType binaryFileType, Type type, ushort[] binaryTypes, string fileExtension, string folderName)
 {
     BinaryFileType = binaryFileType;
     Type           = type;
     BinaryTypes    = binaryTypes;
     FileExtension  = fileExtension;
     FolderName     = folderName;
 }
        public ResourceFileHandler(BinaryFileType binaryFileType)
        {
            if (binaryFileType == BinaryFileType.Particle)
            {
                throw new NotSupportedException($"{nameof(BinaryFileType.Particle)} is unsupported by {nameof(ResourceFileHandler)}, use {nameof(ParticleFileHandler)} instead.");
            }

            BinaryFileName = binaryFileType.ToString().ToLower(CultureInfo.InvariantCulture);
        }
Beispiel #7
0
        public virtual void ProcessRequest(HttpContext context)
        {
            request              = context.Request;
            response             = context.Response;
            response.ContentType = "text/plain";

            if (request.HttpMethod != "POST")
            {
                response.Write("Invalid request type.");
                response.StatusCode = 406;
                return;
            }
            var output = "";

            var    currentUser   = UserLoginService.GetCurrentUser();
            Person currentPerson = currentUser != null ? currentUser.Person : null;

            rockContext           = new RockContext();
            binaryFileTypeService = new BinaryFileTypeService(rockContext);

            binaryFileType = binaryFileTypeService.Get(Rock.SystemGuid.BinaryFiletype.COMMUNICATION_IMAGE.AsGuid());
            if (!binaryFileType.IsAuthorized("Edit", currentPerson))
            {
                response.Write("Unauthorized.");
                response.StatusCode = 401;
                return;
            }

            try
            {
                var videoUrl = request.Form["video_url"];
                if (videoUrl.IsNotNullOrWhiteSpace())
                {
                    foreach (var embedComponents in Rock.Communication.VideoEmbed.VideoEmbedContainer.Instance.Components)
                    {
                        var component = embedComponents.Value.Value;
                        if (Regex.IsMatch(videoUrl, component.RegexFilter))
                        {
                            output = component.GetThumbnail(videoUrl);
                        }
                    }

                    response.Write(output);
                    response.StatusCode = 200;
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, context);
            }
            if (string.IsNullOrWhiteSpace(output))
            {
                response.StatusCode = 404;
                response.Write("Not Found");
            }
        }
 public static string GetSubfolderName(this BinaryFileType binaryFileType)
 {
     return(binaryFileType switch
     {
         BinaryFileType.Audio => "res",
         BinaryFileType.Dd => "res",
         BinaryFileType.Core => "core",
         BinaryFileType.Particle => "dd",
         _ => throw new NotSupportedException($"{nameof(BinaryFileType)} '{binaryFileType}' is not supported in the {nameof(GetSubfolderName)} method."),
     });
Beispiel #9
0
        public virtual MenuItem CreateFileTypeMenuItem()
        {
            BinaryFileType binaryFileType = FileHandler.BinaryFileType;
            string         fileName       = binaryFileType.ToString().ToLower();

            MenuItem extractItem = new MenuItem {
                Header = $"Extract '{fileName}'"
            };
            MenuItem compressItem = new MenuItem {
                Header = $"Compress '{fileName}'"
            };
            MenuItem openModFileItem = new MenuItem {
                Header = $"Open .{fileName} mod file"
            };
            MenuItem saveModFileItem = new MenuItem {
                Header = $"Save .{fileName} mod file"
            };

            extractItem.Click     += (sender, e) => Extract_Click();
            compressItem.Click    += (sender, e) => Compress_Click();
            openModFileItem.Click += (sender, e) =>
            {
                ModFile modFile = OpenModFile();
                if (modFile == null)
                {
                    return;
                }
                UpdateAssetTabControls(modFile.Assets);
            };
            saveModFileItem.Click += (sender, e) =>
            {
                List <AbstractAsset>     assets     = GetAssets();
                List <AbstractUserAsset> userAssets = CreateUserAssets(assets);
                SaveModFile(userAssets);
            };

            MenuItem fileTypeMenuItem = new MenuItem {
                Header = fileName
            };

            fileTypeMenuItem.Items.Add(extractItem);
            fileTypeMenuItem.Items.Add(compressItem);
            fileTypeMenuItem.Items.Add(new Separator());
            fileTypeMenuItem.Items.Add(openModFileItem);
            fileTypeMenuItem.Items.Add(saveModFileItem);
            fileTypeMenuItem.Items.Add(new Separator());

            return(fileTypeMenuItem);
        }
Beispiel #10
0
        internal static string GetExtension(this BinaryFileType fileType, bool includeDot = true)
        {
            string extension;

            InputFileTypeExtensions.TryGetValue(fileType, out extension);
            if ((extension != null) && includeDot)
            {
                return("." + extension);
            }
            else
            {
                // Don't need to prepend a dot or we don't know the extension
                return(extension);
            }
        }
Beispiel #11
0
        public void CacheControlHeaderSettingsChangesShouldResetCacheControlHeader()
        {
            var model = new BinaryFileType();

            model.CacheControlHeaderSettings = "{\"RockCacheablityType\":3,\"MaxAge\":null,\"MaxSharedAge\":null}";
            var header = model.CacheControlHeader;

            Assert.That.IsNotNull(header);

            model.CacheControlHeaderSettings = "{\"RockCacheablityType\":0,\"MaxAge\":{\"Value\":31556952,\"Unit\":0},\"MaxSharedAge\":null}";
            var header2 = model.CacheControlHeader;

            Assert.That.IsNotNull(header2);
            Assert.That.AreNotEqual(header.RockCacheablityType, header2.RockCacheablityType);
        }
Beispiel #12
0
        public List <AbstractAsset> GetAssets(BinaryFileType binaryFileType, string assetType)
        {
            string id = $"{binaryFileType.ToString().ToLower(CultureInfo.InvariantCulture)}.{assetType.ToLower(CultureInfo.InvariantCulture)}";

            return(id switch
            {
                "audio.audio" => AudioAudioAssets.Cast <AbstractAsset>().ToList(),
                "core.shaders" => CoreShadersAssets.Cast <AbstractAsset>().ToList(),
                "dd.model bindings" => DdModelBindingsAssets.Cast <AbstractAsset>().ToList(),
                "dd.models" => DdModelsAssets.Cast <AbstractAsset>().ToList(),
                "dd.shaders" => DdShadersAssets.Cast <AbstractAsset>().ToList(),
                "dd.textures" => DdTexturesAssets.Cast <AbstractAsset>().ToList(),
                "particle.particles" => ParticleParticlesAssets.Cast <AbstractAsset>().ToList(),
                _ => throw new($"No asset data found for binary file type '{binaryFileType}' and asset type '{assetType}.'"),
            });
Beispiel #13
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="binaryFileId">The binary file identifier.</param>
        /// <param name="binaryFileTypeId">The binary file type id.</param>
        public void ShowDetail(int binaryFileId, int?binaryFileTypeId)
        {
            var        rockContext       = new RockContext();
            var        binaryFileService = new BinaryFileService(rockContext);
            BinaryFile binaryFile        = null;

            if (!binaryFileId.Equals(0))
            {
                binaryFile = binaryFileService.Get(binaryFileId);
                pdAuditDetails.SetEntity(binaryFile, ResolveRockUrl("~"));
            }

            if (binaryFile == null)
            {
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;

                BinaryFileType binaryFileType = null;
                if (binaryFileTypeId.HasValue)
                {
                    binaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFileTypeId.Value);
                }

                if (binaryFileType != null)
                {
                    binaryFile = new BinaryFile {
                        Id = 0, IsSystem = false, BinaryFileTypeId = binaryFileTypeId
                    };
                    lActionTitle.Text = ActionTitle.Add(binaryFileType.Name).FormatAsHtmlTitle();
                }
                else
                {
                    pnlDetails.Visible = false;
                    return;
                }
            }
            else
            {
                lActionTitle.Text = ActionTitle.Edit(binaryFile.BinaryFileType.Name).FormatAsHtmlTitle();
            }

            binaryFile.LoadAttributes(rockContext);

            // initialize the fileUploader BinaryFileId to whatever file we are editing/viewing
            fsFile.BinaryFileId = binaryFile.Id;

            ShowBinaryFileDetail(binaryFile);
        }
Beispiel #14
0
        public void CacheControlHeaderSettingsNoChangeShouldNotResetCacheControlHeader()
        {
            var model = new BinaryFileType();

            model.CacheControlHeaderSettings = "{\"RockCacheablityType\":3,\"MaxAge\":null,\"MaxSharedAge\":null}";

            var header = model.CacheControlHeader;

            Assert.That.IsNotNull(header);

            model.CacheControlHeaderSettings = "{\"RockCacheablityType\":3,\"MaxAge\":null,\"MaxSharedAge\":null}";
            var header2 = model.CacheControlHeader;

            Assert.That.IsNotNull(header2);
            Assert.That.AreEqual(header, header2);
        }
Beispiel #15
0
        public BinaryPathControl(string header, BinaryFileType binaryFileType, AssetType assetTypeForColor)
        {
            InitializeComponent();

            BinaryFileType = binaryFileType;

            Header.Content = header;

            Progress = new ProgressWrapper(
                new Progress <string>(value => App.Instance.Dispatcher.Invoke(() => ProgressDescription.Text = value)),
                new Progress <float>(value => App.Instance.Dispatcher.Invoke(() => ProgressBar.Value         = value)));

            ProgressBar.Foreground = new SolidColorBrush(EditorUtils.FromRgbTuple(assetTypeForColor.GetColor()) * 0.25f);

            _binaryPath = Path.Combine(UserHandler.Instance.Settings.DevilDaggersRootFolder, binaryFileType.GetSubfolderName(), binaryFileType.ToString().ToLower(CultureInfo.InvariantCulture));
            UpdateGui();
        }
Beispiel #16
0
        public static string GetSubfolderName(this BinaryFileType binaryFileType)
        {
            switch (binaryFileType)
            {
            case BinaryFileType.Audio:
            case BinaryFileType.DD:
                return("res");

            case BinaryFileType.Core:
                return("core");

            case BinaryFileType.Particle:
                return("dd");

            default: throw new Exception($"{nameof(BinaryFileType)} '{binaryFileType}' has not been implemented in this method.");
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="binaryFileId">The binary file identifier.</param>
        /// <param name="binaryFileTypeId">The binary file type id.</param>
        public void ShowDetail(int binaryFileId, int?binaryFileTypeId)
        {
            var        rockContext       = new RockContext();
            var        binaryFileService = new BinaryFileService(rockContext);
            BinaryFile binaryFile        = null;

            if (!binaryFileId.Equals(0))
            {
                binaryFile = binaryFileService.Get(binaryFileId);
            }

            if (binaryFile == null)
            {
                BinaryFileType binaryFileType = null;
                if (binaryFileTypeId.HasValue)
                {
                    binaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFileTypeId.Value);
                }

                if (binaryFileType != null)
                {
                    binaryFile = new BinaryFile {
                        Id = 0, IsSystem = false, BinaryFileTypeId = binaryFileTypeId
                    };
                    lActionTitle.Text = ActionTitle.Add(binaryFileType.Name).FormatAsHtmlTitle();
                }
                else
                {
                    pnlDetails.Visible = false;
                    return;
                }
            }
            else
            {
                lActionTitle.Text = ActionTitle.Edit(binaryFile.BinaryFileType.Name).FormatAsHtmlTitle();
            }

            binaryFile.LoadAttributes(rockContext);

            // initialize the fileUploader BinaryFileId to whatever file we are editing/viewing
            fsFile.BinaryFileId = binaryFile.Id;

            ShowBinaryFileDetail(binaryFile);
        }
Beispiel #18
0
        /// <summary>
        /// Handles the Delete event of the gBinaryFileType 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 gBinaryFileType_Delete(object sender, RowEventArgs e)
        {
            var rockContext = new RockContext();
            BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService(rockContext);
            BinaryFileType        binaryFileType        = binaryFileTypeService.Get(e.RowKeyId);

            if (binaryFileType != null)
            {
                string errorMessage;
                if (!binaryFileTypeService.CanDelete(binaryFileType, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                binaryFileTypeService.Delete(binaryFileType);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
        public AssetTabControl(BinaryFileType binaryFileType, AssetType assetType, string openDialogFilter, string assetTypeJsonFileName)
        {
            InitializeComponent();

            AssetType = assetType;

            List <AbstractAsset> assets = AssetHandler.Instance.GetAssets(binaryFileType, assetTypeJsonFileName).ToList();

            int i = 0;

            foreach (AbstractAsset asset in assets)
            {
                AssetRowControl rowHandler = new AssetRowControl(asset, assetType, i++ % 2 == 0, openDialogFilter);
                RowControls.Add(rowHandler);
            }

            AllFilters   = RowControls.Select(a => a.Asset).SelectMany(a => a.Tags ?? new List <string>()).Where(t => !string.IsNullOrEmpty(t)).Distinct().OrderBy(s => s);
            FiltersCount = AllFilters.Count();

            FilterHighlightColor = EditorUtils.FromRgbTuple(assetType.GetColor()) * 0.25f;

            Previewer = assetType switch
            {
                AssetType.Audio => new AudioPreviewerControl(),
                AssetType.Model => new ModelPreviewerControl(),
                AssetType.ModelBinding => new ModelBindingPreviewerControl(),
                AssetType.Particle => new ParticlePreviewerControl(),
                AssetType.Shader => new ShaderPreviewerControl(),
                AssetType.Texture => new TexturePreviewerControl(),
                _ => throw new NotSupportedException($"Previewer control for type {assetType} is not supported."),
            };

            MainGrid.Children.Add(Previewer);

            if (assetType == AssetType.Audio)
            {
                StackPanelLoudness.Visibility  = Visibility.Visible;
                ColumnDefinitionLoudness.Width = new GridLength(96);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Handles the Delete event of the gBinaryFileType 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 gBinaryFileType_Delete(object sender, RowEventArgs e)
        {
            RockTransactionScope.WrapTransaction(() =>
            {
                BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService();
                BinaryFileType binaryFileType = binaryFileTypeService.Get(e.RowKeyId);

                if (binaryFileType != null)
                {
                    string errorMessage;
                    if (!binaryFileTypeService.CanDelete(binaryFileType, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    binaryFileTypeService.Delete(binaryFileType, CurrentPersonId);
                    binaryFileTypeService.Save(binaryFileType, CurrentPersonId);
                }
            });

            BindGrid();
        }
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        /// <param name="lookupContext">The lookup context.</param>
        private static void LoadRockData(RockContext lookupContext = null)
        {
            lookupContext = lookupContext ?? new RockContext();

            // initialize file providers
            DatabaseProvider   = new Database();
            FileSystemProvider = new FileSystem();

            // core-specified attribute guid for setting file root path
            RootPathAttribute = AttributeCache.Get(new Guid("3CAFA34D-9208-439B-A046-CB727FB729DE"));

            // core-specified blacklist files
            FileTypeBlackList = (GlobalAttributesCache.Get().GetValue("ContentFiletypeBlacklist")
                                 ?? string.Empty).Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

            // clean up blacklist
            FileTypeBlackList = FileTypeBlackList.Select(a => a.ToLower().TrimStart(new char[] { '.', ' ' }));
            FileTypes         = new BinaryFileTypeService(lookupContext).Queryable().AsNoTracking().ToList();

            // get all the types we'll be importing
            var binaryTypeSettings = ConfigurationManager.GetSection("binaryFileTypes") as NameValueCollection;

            // create any custom types defined in settings that don't exist yet
            foreach (var typeKey in binaryTypeSettings.AllKeys)
            {
                if (!FileTypes.Any(f => f.Name == typeKey))
                {
                    var newFileType = new BinaryFileType();
                    lookupContext.BinaryFileTypes.Add(newFileType);
                    newFileType.Name         = typeKey;
                    newFileType.Description  = typeKey;
                    newFileType.AllowCaching = true;

                    var typeValue = binaryTypeSettings[typeKey];
                    if (typeValue != null)
                    {
                        // #TODO: support additional storage types (like AWS?)
                        newFileType.StorageEntityTypeId = typeValue.Equals("Database") ? DatabaseStorageTypeId : FileSystemStorageTypeId;
                        newFileType.Attributes          = new Dictionary <string, AttributeCache>();
                        newFileType.AttributeValues     = new Dictionary <string, AttributeValueCache>();

                        // save changes to binary type to get an ID
                        lookupContext.SaveChanges();

                        var newRootPath = new AttributeValue()
                        {
                            AttributeId = RootPathAttribute.Id,
                            EntityId    = newFileType.Id,
                            Value       = typeValue
                        };

                        newFileType.Attributes.Add(RootPathAttribute.Key, RootPathAttribute);
                        newFileType.AttributeValues.Add(RootPathAttribute.Key, new AttributeValueCache(newRootPath));

                        // save attribute values with the current type ID
                        lookupContext.AttributeValues.Add(newRootPath);
                    }

                    lookupContext.SaveChanges();
                    FileTypes.Add(newFileType);
                }
            }

            // load attributes on file system types to get the default storage location
            foreach (var type in FileTypes)
            {
                type.LoadAttributes(lookupContext);

                if (type.StorageEntityTypeId == FileSystemStorageTypeId && binaryTypeSettings.AllKeys.Any(k => type.Name.Equals(k)))
                {
                    // override the configured storage location since we can't handle relative paths
                    type.AttributeValues["RootPath"].Value = binaryTypeSettings[type.Name];
                }
            }

            // get a list of all the imported people keys
            var personAliasList = new PersonAliasService(lookupContext).Queryable().AsNoTracking().ToList();

            ImportedPeople = personAliasList
                             .Where(pa => pa.ForeignKey != null)
                             .Select(pa =>
                                     new PersonKeys()
            {
                PersonAliasId    = pa.Id,
                PersonId         = pa.PersonId,
                PersonForeignId  = pa.ForeignId,
                PersonForeignKey = pa.ForeignKey
            }).ToList();
        }
        /// <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 )
        {
            using ( new UnitOfWorkScope() )
            {
                BinaryFileType binaryFileType;

                BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService();
                AttributeService attributeService = new AttributeService();
                AttributeQualifierService attributeQualifierService = new AttributeQualifierService();
                CategoryService categoryService = new CategoryService();

                int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value );

                if ( binaryFileTypeId == 0 )
                {
                    binaryFileType = new BinaryFileType();
                    binaryFileTypeService.Add( binaryFileType, CurrentPersonId );
                }
                else
                {
                    binaryFileType = binaryFileTypeService.Get( binaryFileTypeId );
                }

                binaryFileType.Name = tbName.Text;
                binaryFileType.Description = tbDescription.Text;
                binaryFileType.IconCssClass = tbIconCssClass.Text;
                binaryFileType.AllowCaching = cbAllowCaching.Checked;

                if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) )
                {
                    var entityTypeService = new EntityTypeService();
                    var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) );

                    if ( storageEntityType != null )
                    {
                        binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                    }
                }

                binaryFileType.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFileType );

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

                RockTransactionScope.WrapTransaction( () =>
                    {
                        binaryFileTypeService.Save( binaryFileType, CurrentPersonId );

                        // get it back to make sure we have a good Id for it for the Attributes
                        binaryFileType = binaryFileTypeService.Get( binaryFileType.Guid );

                        /* Take care of Binary File Attributes */
                        var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id;

                        // delete BinaryFileAttributes that are no longer configured in the UI
                        var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() );
                        var selectedAttributeGuids = BinaryFileAttributesState.Select( a => a.Guid );
                        foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                        {
                            Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                            attributeService.Delete( attr, CurrentPersonId );
                            attributeService.Save( attr, CurrentPersonId );
                        }

                        // add/update the BinaryFileAttributes that are assigned in the UI
                        foreach ( var attributeState in BinaryFileAttributesState )
                        {
                            Rock.Attribute.Helper.SaveAttributeEdits( attributeState, attributeService, attributeQualifierService, categoryService,
                                entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), CurrentPersonId );
                        }

                        // SaveAttributeValues for the BinaryFileType
                        Rock.Attribute.Helper.SaveAttributeValues( binaryFileType, CurrentPersonId );

                    } );
            }

            NavigateToParentPage();
        }
Beispiel #23
0
        /// <summary>
        /// Handles the DoWork event of the bwUploadScannedChecks control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DoWorkEventArgs"/> instance containing the event data.</param>
        private void bwUploadScannedChecks_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;

            RockConfig     rockConfig = RockConfig.Load();
            RockRestClient client     = new RockRestClient(rockConfig.RockBaseUrl);

            client.Login(rockConfig.Username, rockConfig.Password);

            AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
            string       appInfo      = string.Format("{0}, version: {1}", assemblyName.FullName, assemblyName.Version);

            BinaryFileType binaryFileTypeContribution       = client.GetDataByGuid <BinaryFileType>("api/BinaryFileTypes", new Guid(Rock.SystemGuid.BinaryFiletype.CONTRIBUTION_IMAGE));
            DefinedValue   currencyTypeValueCheck           = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.CURRENCY_TYPE_CHECK));
            DefinedValue   transactionTypeValueContribution = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION));
            DefinedValue   transactionImageTypeValueFront   = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_FRONT));
            DefinedValue   transactionImageTypeValueBack    = client.GetDataByGuid <DefinedValue>("api/DefinedValues", new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_IMAGE_TYPE_CHECK_BACK));

            int totalCount = ScannedCheckList.Where(a => !a.Uploaded).Count();
            int position   = 1;

            foreach (ScannedCheckInfo scannedCheckInfo in ScannedCheckList.Where(a => !a.Uploaded))
            {
                // upload image of front of check
                BinaryFile binaryFileFront = new BinaryFile();
                binaryFileFront.Guid             = Guid.NewGuid();
                binaryFileFront.FileName         = string.Format("{0}_{1}_{2}_front.png", scannedCheckInfo.RoutingNumber, scannedCheckInfo.MaskedAccountNumber, scannedCheckInfo.CheckNumber);
                binaryFileFront.BinaryFileTypeId = binaryFileTypeContribution.Id;
                binaryFileFront.IsSystem         = false;
                binaryFileFront.MimeType         = "image/png";
                client.PostData <BinaryFile>("api/BinaryFiles/", binaryFileFront);

                // upload image data content of front of check
                binaryFileFront.Data         = new BinaryFileData();
                binaryFileFront.Data.Content = scannedCheckInfo.FrontImagePngBytes;
                binaryFileFront.Data.Id      = client.GetDataByGuid <BinaryFile>("api/BinaryFiles/", binaryFileFront.Guid).Id;
                client.PostData <BinaryFileData>("api/BinaryFileDatas/", binaryFileFront.Data);

                // upload image of back of check (if it exists)
                BinaryFile binaryFileBack = null;

                if (scannedCheckInfo.BackImageData != null)
                {
                    binaryFileBack          = new BinaryFile();
                    binaryFileBack.Guid     = Guid.NewGuid();
                    binaryFileBack.FileName = string.Format("{0}_{1}_{2}_back.png", scannedCheckInfo.RoutingNumber, scannedCheckInfo.MaskedAccountNumber, scannedCheckInfo.CheckNumber);

                    // upload image of back of check
                    binaryFileBack.BinaryFileTypeId = binaryFileTypeContribution.Id;
                    binaryFileBack.IsSystem         = false;
                    binaryFileBack.MimeType         = "image/png";
                    client.PostData <BinaryFile>("api/BinaryFiles/", binaryFileBack);

                    // upload image data content of back of check
                    binaryFileBack.Data         = new BinaryFileData();
                    binaryFileBack.Data.Content = scannedCheckInfo.BackImagePngBytes;
                    binaryFileBack.Data.Id      = client.GetDataByGuid <BinaryFile>("api/BinaryFiles/", binaryFileBack.Guid).Id;
                    client.PostData <BinaryFileData>("api/BinaryFileDatas/", binaryFileBack.Data);
                }

                int percentComplete = position++ *100 / totalCount;
                bw.ReportProgress(percentComplete);

                FinancialTransactionScannedCheck financialTransactionScannedCheck = new FinancialTransactionScannedCheck();
                financialTransactionScannedCheck.BatchId                = SelectedFinancialBatchId;
                financialTransactionScannedCheck.Amount                 = 0.00M;
                financialTransactionScannedCheck.TransactionCode        = string.Empty;
                financialTransactionScannedCheck.Summary                = string.Format("Scanned Check from {0}", appInfo);
                financialTransactionScannedCheck.Guid                   = Guid.NewGuid();
                financialTransactionScannedCheck.TransactionDateTime    = DateTime.Now;
                financialTransactionScannedCheck.CurrencyTypeValueId    = currencyTypeValueCheck.Id;
                financialTransactionScannedCheck.CreditCardTypeValueId  = null;
                financialTransactionScannedCheck.SourceTypeValueId      = null;
                financialTransactionScannedCheck.AuthorizedPersonId     = this.LoggedInPerson.Id;
                financialTransactionScannedCheck.TransactionTypeValueId = transactionTypeValueContribution.Id;

                // Rock server will encrypt CheckMicrPlainText to this since we can't have the DataEncryptionKey in a RestClient
                financialTransactionScannedCheck.CheckMicrEncrypted = null;

                financialTransactionScannedCheck.ScannedCheckMicr = string.Format("{0}_{1}_{2}", scannedCheckInfo.RoutingNumber, scannedCheckInfo.AccountNumber, scannedCheckInfo.CheckNumber);

                client.PostData <FinancialTransactionScannedCheck>("api/FinancialTransactions/PostScanned", financialTransactionScannedCheck);

                // get the FinancialTransaction back from server so that we can get it's Id
                financialTransactionScannedCheck.Id = client.GetDataByGuid <FinancialTransaction>("api/FinancialTransactions", financialTransactionScannedCheck.Guid).Id;

                // get the BinaryFiles back so that we can get their Ids
                binaryFileFront.Id = client.GetDataByGuid <BinaryFile>("api/BinaryFiles", binaryFileFront.Guid).Id;

                // upload FinancialTransactionImage records for front/back
                FinancialTransactionImage financialTransactionImageFront = new FinancialTransactionImage();
                financialTransactionImageFront.BinaryFileId  = binaryFileFront.Id;
                financialTransactionImageFront.TransactionId = financialTransactionScannedCheck.Id;
                financialTransactionImageFront.TransactionImageTypeValueId = transactionImageTypeValueFront.Id;
                client.PostData <FinancialTransactionImage>("api/FinancialTransactionImages", financialTransactionImageFront);

                if (binaryFileBack != null)
                {
                    // get the BinaryFiles back so that we can get their Ids
                    binaryFileBack.Id = client.GetDataByGuid <BinaryFile>("api/BinaryFiles", binaryFileBack.Guid).Id;
                    FinancialTransactionImage financialTransactionImageBack = new FinancialTransactionImage();
                    financialTransactionImageBack.BinaryFileId  = binaryFileBack.Id;
                    financialTransactionImageBack.TransactionId = financialTransactionScannedCheck.Id;
                    financialTransactionImageBack.TransactionImageTypeValueId = transactionImageTypeValueBack.Id;
                    client.PostData <FinancialTransactionImage>("api/FinancialTransactionImages", financialTransactionImageBack);
                }

                scannedCheckInfo.Uploaded = true;
            }
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="binaryFileTypeId">The binary file type identifier.</param>
        public void ShowDetail( int binaryFileTypeId )
        {
            pnlDetails.Visible = true;
            BinaryFileType binaryFileType = null;

            var rockContext = new RockContext();

            if ( !binaryFileTypeId.Equals( 0 ) )
            {
                binaryFileType = new BinaryFileTypeService( rockContext ).Get( binaryFileTypeId );
                lActionTitle.Text = ActionTitle.Edit( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }

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

            BinaryFileAttributesState = new List<Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text = binaryFileType.Name;
            tbDescription.Text = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbAllowCaching.Checked = binaryFileType.AllowCaching;
            cbRequiresViewSecurity.Checked = binaryFileType.RequiresViewSecurity;

            nbMaxWidth.Text = binaryFileType.MaxWidth.ToString();
            nbMaxHeight.Text = binaryFileType.MaxHeight.ToString();

            ddlPreferredFormat.BindToEnum<Format>();
            ddlPreferredFormat.SetValue( (int)binaryFileType.PreferredFormat );

            ddlPreferredResolution.BindToEnum<Resolution>();
            ddlPreferredResolution.SetValue( (int)binaryFileType.PreferredResolution );

            ddlPreferredColorDepth.BindToEnum<ColorDepth>();
            ddlPreferredColorDepth.SetValue( (int)binaryFileType.PreferredColorDepth );

            cbPreferredRequired.Checked = binaryFileType.PreferredRequired;

            if ( binaryFileType.StorageEntityType != null )
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService( rockContext );

            string qualifierValue = binaryFileType.Id.ToString();
            var qryBinaryFileAttributes = attributeService.GetByEntityTypeId( new BinaryFile().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "BinaryFileTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            BinaryFileAttributesState = qryBinaryFileAttributes.ToList();

            BindBinaryFileAttributesGrid();

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

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

            if ( binaryFileType.IsSystem )
            {
                restrictedEdit = true;
                nbEditModeMessage.Text = EditModeMessage.System( BinaryFileType.FriendlyTypeName );
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

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

            if ( readOnly )
            {
                Rock.Attribute.Helper.AddDisplayControls( binaryFileType, phAttributes );
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, true, BlockValidationGroup );
            }

            // the only thing we'll restrict for restrictedEdit is the Name (plus they won't be able to remove Attributes that are marked as IsSystem
            tbName.ReadOnly = readOnly || restrictedEdit;

            gBinaryFileAttributes.Enabled = !readOnly;
            gBinaryFileAttributes.Columns.OfType<EditField>().First().Visible = !readOnly;
            gBinaryFileAttributes.Actions.ShowAdd = !readOnly;

            // allow these to be edited in restricted edit mode if not readonly
            tbDescription.ReadOnly = readOnly;
            tbIconCssClass.ReadOnly = readOnly;
            cbAllowCaching.Enabled = !readOnly;
            cbRequiresViewSecurity.Enabled = !readOnly;
            cpStorageType.Enabled = !readOnly;
            nbMaxWidth.ReadOnly = readOnly;
            nbMaxHeight.ReadOnly = readOnly;
            ddlPreferredFormat.Enabled = !readOnly;
            ddlPreferredResolution.Enabled = !readOnly;
            ddlPreferredColorDepth.Enabled = !readOnly;
            cbPreferredRequired.Enabled = !readOnly;
            btnSave.Visible = !readOnly;
        }
        /// <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 )
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );

            int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value );

            if ( binaryFileTypeId == 0 )
            {
                binaryFileType = new BinaryFileType();
                binaryFileTypeService.Add( binaryFileType );
            }
            else
            {
                binaryFileType = binaryFileTypeService.Get( binaryFileTypeId );
            }

            binaryFileType.Name = tbName.Text;
            binaryFileType.Description = tbDescription.Text;
            binaryFileType.IconCssClass = tbIconCssClass.Text;
            binaryFileType.AllowCaching = cbAllowCaching.Checked;
            binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum<Format>();
            binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum<Resolution>();
            binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum<ColorDepth>();
            binaryFileType.PreferredRequired = cbPreferredRequired.Checked;

            if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) )
            {
                var entityTypeService = new EntityTypeService( rockContext );
                var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) );

                if ( storageEntityType != null )
                {
                    binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                }
            }

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

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

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

                // get it back to make sure we have a good Id for it for the Attributes
                binaryFileType = binaryFileTypeService.Get( binaryFileType.Guid );

                /* Take care of Binary File Attributes */
                var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() );
                var selectedAttributeGuids = BinaryFileAttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                    attributeService.Delete( attr );
                }
                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach ( var attributeState in BinaryFileAttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext );
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues( rockContext );

            } );

            AttributeCache.FlushEntityAttributes();

            NavigateToParentPage();
        }
 protected AbstractBinaryFileHandler(BinaryFileType binaryFileType)
 {
     BinaryFileType = binaryFileType;
 }
        /// <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 )
            {
                string itemId = PageParameter( "binaryFileTypeId" );
                if ( !string.IsNullOrWhiteSpace( itemId ) )
                {
                    ShowDetail( "binaryFileTypeId", int.Parse( itemId ) );
                }
                else
                {
                    pnlDetails.Visible = false;
                }
            }
            else
            {
                if ( pnlDetails.Visible )
                {
                    var storageEntityType = EntityTypeCache.Read( cpStorageType.SelectedValue.AsGuid() );
                    if ( storageEntityType != null )
                    {
                        var binaryFileType = new BinaryFileType { StorageEntityTypeId = storageEntityType.Id };
                        binaryFileType.LoadAttributes();
                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, false );
                    }
                }
            }
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        public void ShowDetail( string itemKey, int itemKeyValue )
        {
            if ( !itemKey.Equals( "binaryFileTypeId" ) )
            {
                return;
            }

            pnlDetails.Visible = true;
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();

            if ( !itemKeyValue.Equals( 0 ) )
            {
                binaryFileType = new BinaryFileTypeService( rockContext ).Get( itemKeyValue );
                lActionTitle.Text = ActionTitle.Edit( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }
            else
            {
                binaryFileType = new BinaryFileType { Id = 0 };
                lActionTitle.Text = ActionTitle.Add( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
            }

            BinaryFileAttributesState = new ViewStateList<Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text = binaryFileType.Name;
            tbDescription.Text = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbAllowCaching.Checked = binaryFileType.AllowCaching;
            cbRequiresSecurity.Checked = binaryFileType.RequiresSecurity;

            if ( binaryFileType.StorageEntityType != null )
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService( rockContext );

            string qualifierValue = binaryFileType.Id.ToString();
            var qryBinaryFileAttributes = attributeService.GetByEntityTypeId( new BinaryFile().TypeId ).AsQueryable()
                .Where( a => a.EntityTypeQualifierColumn.Equals( "BinaryFileTypeId", StringComparison.OrdinalIgnoreCase )
                && a.EntityTypeQualifierValue.Equals( qualifierValue ) );

            BinaryFileAttributesState.AddAll( qryBinaryFileAttributes.ToList() );
            BindBinaryFileAttributesGrid();

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

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

            if ( binaryFileType.IsSystem )
            {
                nbEditModeMessage.Text = EditModeMessage.System( BinaryFileType.FriendlyTypeName );
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

            if ( readOnly || binaryFileType.IsSystem)
            {
                lActionTitle.Text = ActionTitle.View( BinaryFileType.FriendlyTypeName ).FormatAsHtmlTitle();
                btnCancel.Text = "Close";
                Rock.Attribute.Helper.AddDisplayControls( binaryFileType, phAttributes );
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, true );
            }

            tbName.ReadOnly = readOnly || binaryFileType.IsSystem;
            tbDescription.ReadOnly = readOnly || binaryFileType.IsSystem;
            tbIconCssClass.ReadOnly = readOnly || binaryFileType.IsSystem;
            cbAllowCaching.Enabled = !readOnly && !binaryFileType.IsSystem;
            cbRequiresSecurity.Enabled = !readOnly && !binaryFileType.IsSystem;
            gBinaryFileAttributes.Enabled = !readOnly && !binaryFileType.IsSystem;

            // allow storagetype to be edited if IsSystem
            cpStorageType.Enabled = !readOnly;

            // allow save to be clicked if IsSystem since some things can be edited
            btnSave.Visible = !readOnly ;
        }
Beispiel #29
0
        /// <summary>
        /// Fetches the given remote photoUrl and stores it locally in the binary file table
        /// then returns Id of the binary file.
        /// </summary>
        /// <param name="photoUrl">a URL to a photo (jpg, png, bmp, tiff).</param>
        /// <returns>Id of the binaryFile</returns>
        private BinaryFile SaveImage( string imageUrl, BinaryFileType binaryFileType, string binaryFileTypeSettings, RockContext context )
        {
            // always create a new BinaryFile record of IsTemporary when a file is uploaded
            BinaryFile binaryFile = new BinaryFile();
            binaryFile.IsTemporary = true;
            binaryFile.BinaryFileTypeId = binaryFileType.Id;
            binaryFile.FileName = Path.GetFileName( imageUrl );

            var webClient = new WebClient();
            try
            {
                binaryFile.ContentStream = new MemoryStream( webClient.DownloadData( imageUrl ) );

                if ( webClient.ResponseHeaders != null )
                {
                    binaryFile.MimeType = webClient.ResponseHeaders["content-type"];
                }
                else
                {
                    switch ( Path.GetExtension( imageUrl ) )
                    {
                        case ".jpg":
                        case ".jpeg":
                            binaryFile.MimeType = "image/jpg";
                            break;
                        case ".png":
                            binaryFile.MimeType = "image/png";
                            break;
                        case ".gif":
                            binaryFile.MimeType = "image/gif";
                            break;
                        case ".bmp":
                            binaryFile.MimeType = "image/bmp";
                            break;
                        case ".tiff":
                            binaryFile.MimeType = "image/tiff";
                            break;
                        case ".svg":
                        case ".svgz":
                            binaryFile.MimeType = "image/svg+xml";
                            break;
                        default:
                            throw new NotSupportedException( string.Format( "unknown MimeType for {0}", imageUrl ) );
                    }
                }

                // Because prepost processing is disabled for this rockcontext, need to
                // manually have the storage provider save the contents of the binary file
                binaryFile.SetStorageEntityTypeId( binaryFileType.StorageEntityTypeId );
                binaryFile.StorageEntitySettings = binaryFileTypeSettings;
                if ( binaryFile.StorageProvider != null )
                {
                    binaryFile.StorageProvider.SaveContent( binaryFile );
                    binaryFile.Path = binaryFile.StorageProvider.GetPath( binaryFile );
                }

                var binaryFileService = new BinaryFileService( context );
                binaryFileService.Add( binaryFile );
                return binaryFile;
            }
            catch ( WebException )
            {
                return null;
            }
        }
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadRockData( RockContext lookupContext = null )
        {
            lookupContext = lookupContext ?? new RockContext();

            // initialize storage providers and file types
            LoadStorageProviders();

            FileTypes = new BinaryFileTypeService( lookupContext ).Queryable().AsNoTracking().ToList();

            // core-specified blacklist files
            FileTypeBlackList = ( GlobalAttributesCache.Read().GetValue( "ContentFiletypeBlacklist" )
                ?? string.Empty ).Split( new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries );

            // clean up blacklist
            FileTypeBlackList = FileTypeBlackList.Select( a => a.ToLower().TrimStart( new char[] { '.', ' ' } ) );

            // get all the file types we'll be importing
            var binaryTypeSettings = ConfigurationManager.GetSection( "binaryFileTypes" ) as NameValueCollection;

            // create any custom types that don't exist yet
            foreach ( var typeKey in binaryTypeSettings.AllKeys )
            {
                var fileType = FileTypes.FirstOrDefault( f => f.Name == typeKey );

                // create new binary file type if it doesn't exist
                if ( fileType == null )
                {
                    fileType = new BinaryFileType();
                    fileType.Name = typeKey;
                    fileType.Description = typeKey;
                    fileType.AllowCaching = true;

                    var typeValue = binaryTypeSettings[typeKey];
                    if ( typeValue != null )
                    {
                        var storageProvider = StorageProviders.FirstOrDefault( p => p.TypeName.RemoveWhitespace().EndsWith( typeValue.RemoveWhitespace() ) );
                        if ( storageProvider != null )
                        {
                            // ensure the storage provider is active
                            fileType.StorageEntityTypeId = storageProvider.EntityType.Id;
                            lookupContext.BinaryFileTypes.Add( fileType );
                            lookupContext.SaveChanges();
                            FileTypes.Add( fileType );
                        }
                        else
                        {
                            LogException( "Binary File Import", string.Format( "{0} must use the name of a configured storage provider.", typeKey ) );
                        }
                    }
                    else
                    {
                        LogException( "Binary File Import", string.Format( "{0} must specify the storage provider type.", typeKey ) );
                    }
                }
            }

            // load attributes on file types
            foreach ( var type in FileTypes )
            {
                type.LoadAttributes( lookupContext );
            }

            // get a list of all the imported people keys
            var personAliasList = new PersonAliasService( lookupContext ).Queryable().AsNoTracking().ToList();
            ImportedPeople = personAliasList.Select( pa =>
                new PersonKeys()
                {
                    PersonAliasId = pa.Id,
                    PersonId = pa.PersonId,
                    IndividualId = pa.ForeignId,
                } ).ToList();
        }
Beispiel #31
0
        /// <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;
        }
 public AudioAssetTabControlHandler(BinaryFileType binaryFileType)
     : base(binaryFileType)
 {
 }
Beispiel #33
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="ministryFileType">Type of the ministry file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map( ZipArchive folder, BinaryFileType ministryFileType, ProviderComponent storageProvider )
        {
            var lookupContext = new RockContext();
            var personEntityTypeId = EntityTypeCache.GetId<Person>();
            var fileFieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext ).Id;

            var existingAttributes = new AttributeService( lookupContext ).GetByFieldTypeId( fileFieldTypeId )
                .Where( a => a.EntityTypeId == personEntityTypeId )
                .ToDictionary( a => a.Key, a => a.Id );

            var emptyJsonObject = "{}";
            var newFileList = new List<DocumentKeys>();

            int completed = 0;
            int totalRows = folder.Entries.Count;
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying files import ({0:N0} found.", totalRows ) );

            foreach ( var file in folder.Entries )
            {
                var fileExtension = Path.GetExtension( file.Name );
                var fileMimeType = Extensions.GetMIMEType( file.Name );
                if ( BinaryFileComponent.FileTypeBlackList.Contains( fileExtension ) )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not allowed ({1})", fileExtension, file.Name ) );
                    continue;
                }
                else if ( fileMimeType == null )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not recognized ({1})", fileExtension, file.Name ) );
                    continue;
                }

                string[] parsedFileName = file.Name.Split( '_' );
                // Ministry docs should follow this pattern:
                // 0. Firstname
                // 1. Lastname
                // 2. ForeignId
                // 3. Filename

                var personForeignId = parsedFileName[2].AsType<int?>();
                var personKeys = BinaryFileComponent.ImportedPeople.FirstOrDefault( p => p.IndividualId == personForeignId );
                if ( personKeys != null )
                {
                    var rockFile = new Rock.Model.BinaryFile();
                    rockFile.IsSystem = false;
                    rockFile.IsTemporary = false;
                    rockFile.FileName = file.Name;
                    rockFile.MimeType = fileMimeType;
                    rockFile.BinaryFileTypeId = ministryFileType.Id;
                    rockFile.CreatedDateTime = file.LastWriteTime.DateTime;
                    rockFile.ModifiedDateTime = ImportDateTime;
                    rockFile.Description = string.Format( "Imported as {0}", file.Name );
                    rockFile.SetStorageEntityTypeId( ministryFileType.StorageEntityTypeId );
                    rockFile.StorageEntitySettings = emptyJsonObject;

                    if ( ministryFileType.AttributeValues.Any() )
                    {
                        rockFile.StorageEntitySettings = ministryFileType.AttributeValues
                            .ToDictionary( a => a.Key, v => v.Value.Value ).ToJson();
                    }

                    // use base stream instead of file stream to keep the byte[]
                    // NOTE: if byte[] converts to a string it will corrupt the stream
                    using ( var fileContent = new StreamReader( file.Open() ) )
                    {
                        rockFile.ContentStream = new MemoryStream( fileContent.BaseStream.ReadBytesToEnd() );
                    }

                    var attributePattern = "[A-Za-z0-9-]+";
                    var attributeName = Regex.Match( parsedFileName[3].RemoveWhitespace(), attributePattern );
                    var attributeKey = attributeName.Value.RemoveWhitespace();

                    // change key to default key for Background Check Documents
                    if ( attributeKey == "BackgroundCheck" )
                    {
                        attributeKey = "BackgroundCheckDocument";
                    }

                    if ( !existingAttributes.ContainsKey( attributeKey ) )
                    {
                        var newAttribute = new Attribute();
                        newAttribute.FieldTypeId = fileFieldTypeId;
                        newAttribute.EntityTypeId = personEntityTypeId;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.EntityTypeQualifierValue = string.Empty;
                        newAttribute.Key = attributeKey;
                        newAttribute.Name = attributeName.Value;
                        newAttribute.Description = attributeName.Value + " created by binary file import";
                        newAttribute.CreatedDateTime = ImportDateTime;
                        newAttribute.ModifiedDateTime = ImportDateTime;
                        newAttribute.IsGridColumn = false;
                        newAttribute.IsMultiValue = false;
                        newAttribute.IsRequired = false;
                        newAttribute.AllowSearch = false;
                        newAttribute.IsSystem = false;
                        newAttribute.Order = 0;

                        newAttribute.AttributeQualifiers.Add( new AttributeQualifier()
                        {
                            Key = "binaryFileType",
                            Value = ministryFileType.Guid.ToString()
                        } );

                        lookupContext.Attributes.Add( newAttribute );
                        lookupContext.SaveChanges();

                        existingAttributes.Add( newAttribute.Key, newAttribute.Id );
                    }

                    newFileList.Add( new DocumentKeys()
                    {
                        PersonId = personKeys.PersonId,
                        AttributeId = existingAttributes[attributeKey],
                        File = rockFile
                    } );

                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} files imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFiles( newFileList, storageProvider );

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newFileList.Any() )
            {
                SaveFiles( newFileList, storageProvider );
            }

            ReportProgress( 100, string.Format( "Finished files import: {0:N0} addresses imported.", completed ) );
        }
Beispiel #34
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="ministryFileType">Type of the ministry file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map(ZipArchive folder, BinaryFileType ministryFileType, ProviderComponent storageProvider)
        {
            var lookupContext      = new RockContext();
            var personEntityTypeId = EntityTypeCache.GetId <Person>();
            var fileFieldTypeId    = FieldTypeCache.Read(Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext).Id;

            var existingAttributes = new AttributeService(lookupContext).GetByFieldTypeId(fileFieldTypeId)
                                     .Where(a => a.EntityTypeId == personEntityTypeId)
                                     .ToDictionary(a => a.Key, a => a.Id);

            var emptyJsonObject = "{}";
            var newFileList     = new List <DocumentKeys>();

            int completed  = 0;
            int totalRows  = folder.Entries.Count;
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying files import ({0:N0} found.", totalRows));

            foreach (var file in folder.Entries)
            {
                var fileExtension = Path.GetExtension(file.Name);
                var fileMimeType  = Extensions.GetMIMEType(file.Name);
                if (BinaryFileComponent.FileTypeBlackList.Contains(fileExtension))
                {
                    LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name));
                    continue;
                }
                else if (fileMimeType == null)
                {
                    LogException("Binary File Import", string.Format("{0} filetype not recognized ({1})", fileExtension, file.Name));
                    continue;
                }

                string[] parsedFileName = file.Name.Split('_');
                // Ministry docs should follow this pattern:
                // 0. Firstname
                // 1. Lastname
                // 2. ForeignId
                // 3. Filename

                var personForeignId = parsedFileName[2].AsType <int?>();
                var personKeys      = BinaryFileComponent.ImportedPeople.FirstOrDefault(p => p.IndividualId == personForeignId);
                if (personKeys != null)
                {
                    var rockFile = new Rock.Model.BinaryFile();
                    rockFile.IsSystem         = false;
                    rockFile.IsTemporary      = false;
                    rockFile.FileName         = file.Name;
                    rockFile.MimeType         = fileMimeType;
                    rockFile.BinaryFileTypeId = ministryFileType.Id;
                    rockFile.CreatedDateTime  = file.LastWriteTime.DateTime;
                    rockFile.ModifiedDateTime = ImportDateTime;
                    rockFile.Description      = string.Format("Imported as {0}", file.Name);
                    rockFile.SetStorageEntityTypeId(ministryFileType.StorageEntityTypeId);
                    rockFile.StorageEntitySettings = emptyJsonObject;

                    if (ministryFileType.AttributeValues.Any())
                    {
                        rockFile.StorageEntitySettings = ministryFileType.AttributeValues
                                                         .ToDictionary(a => a.Key, v => v.Value.Value).ToJson();
                    }

                    // use base stream instead of file stream to keep the byte[]
                    // NOTE: if byte[] converts to a string it will corrupt the stream
                    using (var fileContent = new StreamReader(file.Open()))
                    {
                        rockFile.ContentStream = new MemoryStream(fileContent.BaseStream.ReadBytesToEnd());
                    }

                    var attributePattern = "[A-Za-z0-9-]+";
                    var attributeName    = Regex.Match(parsedFileName[3].RemoveWhitespace(), attributePattern);
                    var attributeKey     = attributeName.Value.RemoveWhitespace();

                    // change key to default key for Background Check Documents
                    if (attributeKey == "BackgroundCheck")
                    {
                        attributeKey = "BackgroundCheckDocument";
                    }

                    if (!existingAttributes.ContainsKey(attributeKey))
                    {
                        var newAttribute = new Attribute();
                        newAttribute.FieldTypeId  = fileFieldTypeId;
                        newAttribute.EntityTypeId = personEntityTypeId;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.Key              = attributeKey;
                        newAttribute.Name             = attributeName.Value;
                        newAttribute.Description      = attributeName.Value + " created by binary file import";
                        newAttribute.CreatedDateTime  = ImportDateTime;
                        newAttribute.ModifiedDateTime = ImportDateTime;
                        newAttribute.IsGridColumn     = false;
                        newAttribute.IsMultiValue     = false;
                        newAttribute.IsRequired       = false;
                        newAttribute.AllowSearch      = false;
                        newAttribute.IsSystem         = false;
                        newAttribute.Order            = 0;

                        newAttribute.AttributeQualifiers.Add(new AttributeQualifier()
                        {
                            Key   = "binaryFileType",
                            Value = ministryFileType.Guid.ToString()
                        });

                        lookupContext.Attributes.Add(newAttribute);
                        lookupContext.SaveChanges();

                        existingAttributes.Add(newAttribute.Key, newAttribute.Id);
                    }

                    newFileList.Add(new DocumentKeys()
                    {
                        PersonId    = personKeys.PersonId,
                        AttributeId = existingAttributes[attributeKey],
                        File        = rockFile
                    });

                    completed++;
                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} files imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveFiles(newFileList, storageProvider);

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newFileList.Any())
            {
                SaveFiles(newFileList, storageProvider);
            }

            ReportProgress(100, string.Format("Finished files import: {0:N0} addresses imported.", completed));
        }
Beispiel #35
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="transactionImageType">Type of the transaction image file.</param>
        public void Map(ZipArchive folder, BinaryFileType transactionImageType)
        {
            var lookupContext = new RockContext();

            var emptyJsonObject   = "{}";
            var newFileList       = new Dictionary <int, Rock.Model.BinaryFile>();
            var transactionIdList = new FinancialTransactionService(lookupContext)
                                    .Queryable().AsNoTracking().Where(t => t.ForeignId != null)
                                    .ToDictionary(t => (int)t.ForeignId, t => t.Id);

            var storageProvider = transactionImageType.StorageEntityTypeId == DatabaseProvider.EntityType.Id
                ? (ProviderComponent)DatabaseProvider
                : (ProviderComponent)FileSystemProvider;

            int completed  = 0;
            int totalRows  = folder.Entries.Count;
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying files import ({0:N0} found.", totalRows));

            foreach (var file in folder.Entries)
            {
                var fileExtension = Path.GetExtension(file.Name);
                if (BinaryFileComponent.FileTypeBlackList.Contains(fileExtension))
                {
                    LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name));
                    continue;
                }

                int?transactionId = Path.GetFileNameWithoutExtension(file.Name).AsType <int?>();
                if (transactionId != null && transactionIdList.ContainsKey((int)transactionId))
                {
                    var rockFile = new Rock.Model.BinaryFile();
                    rockFile.IsSystem         = false;
                    rockFile.IsTemporary      = false;
                    rockFile.FileName         = file.Name;
                    rockFile.BinaryFileTypeId = transactionImageType.Id;
                    rockFile.CreatedDateTime  = file.LastWriteTime.DateTime;
                    rockFile.MimeType         = Extensions.GetMIMEType(file.Name);
                    rockFile.Description      = string.Format("Imported as {0}", file.Name);
                    rockFile.SetStorageEntityTypeId(transactionImageType.StorageEntityTypeId);
                    rockFile.StorageEntitySettings = emptyJsonObject;

                    if (transactionImageType.AttributeValues.Any())
                    {
                        rockFile.StorageEntitySettings = transactionImageType.AttributeValues
                                                         .ToDictionary(a => a.Key, v => v.Value.Value).ToJson();
                    }

                    // use base stream instead of file stream to keep the byte[]
                    // NOTE: if byte[] converts to a string it will corrupt the stream
                    using (var fileContent = new StreamReader(file.Open()))
                    {
                        rockFile.ContentStream = new MemoryStream(fileContent.BaseStream.ReadBytesToEnd());
                    }

                    newFileList.Add(transactionIdList[(int)transactionId], rockFile);

                    completed++;
                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} files imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveFiles(newFileList, storageProvider);

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newFileList.Any())
            {
                SaveFiles(newFileList, storageProvider);
            }

            ReportProgress(100, string.Format("Finished files import: {0:N0} addresses imported.", completed));
        }
        /// <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( "binaryFileTypeId" ).AsInteger() );
            }
            else
            {
                if ( pnlDetails.Visible )
                {
                    var storageEntityType = EntityTypeCache.Read( cpStorageType.SelectedValue.AsGuid() );
                    if ( storageEntityType != null )
                    {
                        var binaryFileType = new BinaryFileType { StorageEntityTypeId = storageEntityType.Id };
                        binaryFileType.LoadAttributes();
                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls( binaryFileType, phAttributes, false, BlockValidationGroup );
                    }
                }
            }
        }
Beispiel #37
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="personImageType">Type of the person image file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map( ZipArchive folder, BinaryFileType personImageType, ProviderComponent storageProvider )
        {
            // check for existing images
            var lookupContext = new RockContext();
            var existingImageList = new PersonService( lookupContext ).Queryable().AsNoTracking()
                .Where( p => p.Photo != null )
                .ToDictionary( p => p.Id, p => p.Photo.CreatedDateTime );

            var emptyJsonObject = "{}";
            var newFileList = new Dictionary<int, Rock.Model.BinaryFile>();

            int completed = 0;
            int totalRows = folder.Entries.Count;
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying files import ({0:N0} found.", totalRows ) );

            foreach ( var file in folder.Entries )
            {
                var fileExtension = Path.GetExtension( file.Name );
                if ( BinaryFileComponent.FileTypeBlackList.Contains( fileExtension ) )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not allowed ({1})", fileExtension, file.Name ) );
                    continue;
                }

                var personForeignId = Path.GetFileNameWithoutExtension( file.Name ).AsType<int?>();
                var personKeys = BinaryFileComponent.ImportedPeople.FirstOrDefault( p => p.IndividualId == personForeignId );
                if ( personKeys != null )
                {
                    // only import the most recent profile photo
                    if ( !existingImageList.ContainsKey( personKeys.PersonId ) || existingImageList[personKeys.PersonId].Value < file.LastWriteTime.DateTime )
                    {
                        var rockFile = new Rock.Model.BinaryFile();
                        rockFile.IsSystem = false;
                        rockFile.IsTemporary = false;
                        rockFile.FileName = file.Name;
                        rockFile.BinaryFileTypeId = personImageType.Id;
                        rockFile.MimeType = Extensions.GetMIMEType( file.Name );
                        rockFile.CreatedDateTime = file.LastWriteTime.DateTime;
                        rockFile.ModifiedDateTime = ImportDateTime;
                        rockFile.Description = string.Format( "Imported as {0}", file.Name );
                        rockFile.SetStorageEntityTypeId( personImageType.StorageEntityTypeId );
                        rockFile.StorageEntitySettings = emptyJsonObject;

                        if ( personImageType.AttributeValues.Any() )
                        {
                            rockFile.StorageEntitySettings = personImageType.AttributeValues
                                .ToDictionary( a => a.Key, v => v.Value.Value ).ToJson();
                        }

                        // use base stream instead of file stream to keep the byte[]
                        // NOTE: if byte[] converts to a string it will corrupt the stream
                        using ( var fileContent = new StreamReader( file.Open() ) )
                        {
                            rockFile.ContentStream = new MemoryStream( fileContent.BaseStream.ReadBytesToEnd() );
                        }

                        newFileList.Add( personKeys.PersonId, rockFile );
                    }

                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} files imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFiles( newFileList, storageProvider );

                        // add image keys to master list
                        foreach ( var newFile in newFileList )
                        {
                            existingImageList.AddOrReplace( newFile.Key, newFile.Value.CreatedDateTime );
                        }

                        // Reset batch list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newFileList.Any() )
            {
                SaveFiles( newFileList, storageProvider );
            }

            ReportProgress( 100, string.Format( "Finished files import: {0:N0} addresses imported.", completed ) );
        }
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="binaryFileTypeId">The binary file type identifier.</param>
        public void ShowDetail(int binaryFileTypeId)
        {
            pnlDetails.Visible = true;
            BinaryFileType binaryFileType = null;

            var rockContext = new RockContext();

            if (!binaryFileTypeId.Equals(0))
            {
                binaryFileType    = new BinaryFileTypeService(rockContext).Get(binaryFileTypeId);
                lActionTitle.Text = ActionTitle.Edit(BinaryFileType.FriendlyTypeName).FormatAsHtmlTitle();
                pdAuditDetails.SetEntity(binaryFileType, ResolveRockUrl("~"));
            }

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

                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            BinaryFileAttributesState = new List <Attribute>();

            hfBinaryFileTypeId.Value = binaryFileType.Id.ToString();
            tbName.Text         = binaryFileType.Name;
            tbDescription.Text  = binaryFileType.Description;
            tbIconCssClass.Text = binaryFileType.IconCssClass;
            cbCacheToServerFileSystem.Checked = binaryFileType.CacheToServerFileSystem;

            if (binaryFileType.CacheControlHeaderSettings != null)
            {
                cpCacheSettings.CurrentCacheablity = JsonConvert.DeserializeObject <RockCacheability>(binaryFileType.CacheControlHeaderSettings);
            }

            cbRequiresViewSecurity.Checked = binaryFileType.RequiresViewSecurity;

            nbMaxWidth.Text  = binaryFileType.MaxWidth.ToString();
            nbMaxHeight.Text = binaryFileType.MaxHeight.ToString();

            ddlPreferredFormat.BindToEnum <Format>();
            ddlPreferredFormat.SetValue(( int )binaryFileType.PreferredFormat);

            ddlPreferredResolution.BindToEnum <Resolution>();
            ddlPreferredResolution.SetValue(( int )binaryFileType.PreferredResolution);

            ddlPreferredColorDepth.BindToEnum <ColorDepth>();
            ddlPreferredColorDepth.SetValue(( int )binaryFileType.PreferredColorDepth);

            cbPreferredRequired.Checked = binaryFileType.PreferredRequired;

            if (binaryFileType.StorageEntityType != null)
            {
                cpStorageType.SelectedValue = binaryFileType.StorageEntityType.Guid.ToString().ToUpper();
            }

            AttributeService attributeService = new AttributeService(rockContext);

            string qualifierValue          = binaryFileType.Id.ToString();
            var    qryBinaryFileAttributes = attributeService.GetByEntityTypeId(new BinaryFile().TypeId, true).AsQueryable()
                                             .Where(a => a.EntityTypeQualifierColumn.Equals("BinaryFileTypeId", StringComparison.OrdinalIgnoreCase) &&
                                                    a.EntityTypeQualifierValue.Equals(qualifierValue));

            BinaryFileAttributesState = qryBinaryFileAttributes.ToList();

            BindBinaryFileAttributesGrid();

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

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

            if (binaryFileType.IsSystem)
            {
                restrictedEdit         = true;
                nbEditModeMessage.Text = EditModeMessage.System(BinaryFileType.FriendlyTypeName);
            }

            phAttributes.Controls.Clear();
            binaryFileType.LoadAttributes();

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

            if (readOnly)
            {
                Rock.Attribute.Helper.AddDisplayControls(binaryFileType, phAttributes);
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls(binaryFileType, phAttributes, true, BlockValidationGroup);
            }

            // the only thing we'll restrict for restrictedEdit is the Name (plus they won't be able to remove Attributes that are marked as IsSystem
            tbName.ReadOnly = readOnly || restrictedEdit;

            gBinaryFileAttributes.Enabled = !readOnly;
            gBinaryFileAttributes.Columns.OfType <EditField>().First().Visible = !readOnly;
            gBinaryFileAttributes.Actions.ShowAdd = !readOnly;

            // allow these to be edited in restricted edit mode if not readonly
            tbDescription.ReadOnly            = readOnly;
            tbIconCssClass.ReadOnly           = readOnly;
            cbCacheToServerFileSystem.Enabled = !readOnly;
            cpCacheSettings.Enabled           = !readOnly;
            cbRequiresViewSecurity.Enabled    = !readOnly;
            cpStorageType.Enabled             = !readOnly;
            nbMaxWidth.ReadOnly            = readOnly;
            nbMaxHeight.ReadOnly           = readOnly;
            ddlPreferredFormat.Enabled     = !readOnly;
            ddlPreferredResolution.Enabled = !readOnly;
            ddlPreferredColorDepth.Enabled = !readOnly;
            cbPreferredRequired.Enabled    = !readOnly;
            btnSave.Visible = !readOnly;
        }
        /// <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)
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService     binaryFileTypeService     = new BinaryFileTypeService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);
            CategoryService           categoryService           = new CategoryService(rockContext);

            int binaryFileTypeId = int.Parse(hfBinaryFileTypeId.Value);

            if (binaryFileTypeId == 0)
            {
                binaryFileType = new BinaryFileType();
                binaryFileTypeService.Add(binaryFileType);
            }
            else
            {
                binaryFileType = binaryFileTypeService.Get(binaryFileTypeId);
            }

            binaryFileType.Name                       = tbName.Text;
            binaryFileType.Description                = tbDescription.Text;
            binaryFileType.IconCssClass               = tbIconCssClass.Text;
            binaryFileType.CacheToServerFileSystem    = cbCacheToServerFileSystem.Checked;
            binaryFileType.CacheControlHeaderSettings = cpCacheSettings.CurrentCacheablity.ToJson();
            binaryFileType.RequiresViewSecurity       = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth                   = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight                  = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat            = ddlPreferredFormat.SelectedValueAsEnum <Format>();
            binaryFileType.PreferredResolution        = ddlPreferredResolution.SelectedValueAsEnum <Resolution>();
            binaryFileType.PreferredColorDepth        = ddlPreferredColorDepth.SelectedValueAsEnum <ColorDepth>();
            binaryFileType.PreferredRequired          = cbPreferredRequired.Checked;

            if (!string.IsNullOrWhiteSpace(cpStorageType.SelectedValue))
            {
                var entityTypeService = new EntityTypeService(rockContext);
                var storageEntityType = entityTypeService.Get(new Guid(cpStorageType.SelectedValue));

                if (storageEntityType != null)
                {
                    binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                }
            }

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

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

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

                // get it back to make sure we have a good Id for it for the Attributes
                binaryFileType = binaryFileTypeService.Get(binaryFileType.Guid);

                /* Take care of Binary File Attributes */
                var entityTypeId = EntityTypeCache.Get(typeof(BinaryFile)).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes             = attributeService.GetByEntityTypeQualifier(entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), true);
                var selectedAttributeGuids = BinaryFileAttributesState.Select(a => a.Guid);
                foreach (var attr in attributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
                {
                    attributeService.Delete(attr);
                }

                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach (var attributeState in BinaryFileAttributesState)
                {
                    Rock.Attribute.Helper.SaveAttributeEdits(attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext);
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues(rockContext);
            });

            NavigateToParentPage();
        }
        /// <summary>
        /// Saves the data.
        /// </summary>
        /// <param name="context">The current HTTP context.</param>
        /// <param name="uploadedFile">The file that was uploaded</param>
        /// <param name="file">The file.</param>
        /// <param name="fileType">The file type.</param>
        public virtual void SaveData(HttpContext context, HttpPostedFile uploadedFile, BinaryFile file, BinaryFileType fileType)
        {
            var provider = fileType != null
                ? ProviderContainer.GetComponent(fileType.StorageEntityType.Name)
                : ProviderContainer.DefaultComponent;

            file.MimeType = uploadedFile.ContentType;
            file.FileName = Path.GetFileName(uploadedFile.FileName);
            var bytes = new byte[uploadedFile.ContentLength];

            uploadedFile.InputStream.Read(bytes, 0, uploadedFile.ContentLength);
            file.Data = new BinaryFileData {
                Content = bytes
            };
            provider.SaveFile(file, null);
        }
Beispiel #41
0
 public static bool HasFlagBothWays(this BinaryFileType a, BinaryFileType b)
 {
     return(a.HasFlag(b) || b.HasFlag(a));
 }
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <exception cref="WebFaultException">Must be logged in</exception>
        public void ProcessRequest(HttpContext context)
        {
            // *********************************************
            // TODO: verify user is authorized to save file!
            // *********************************************

            if (!context.User.Identity.IsAuthenticated)
            {
                throw new WebFaultException <string>("Must be logged in", System.Net.HttpStatusCode.Forbidden);
            }

            try
            {
                HttpFileCollection hfc          = context.Request.Files;
                HttpPostedFile     uploadedFile = hfc.AllKeys.Select(fk => hfc[fk]).FirstOrDefault();

                // No file or no data?  No good.
                if (uploadedFile == null || uploadedFile.ContentLength == 0)
                {
                    // TODO: Is there a better response we could send than a 200?
                    context.Response.Write("0");
                    return;
                }

                BinaryFileService fileService = new BinaryFileService();
                var            id             = context.Request.QueryString["fileId"];
                BinaryFile     file           = null;
                BinaryFileType fileType       = null;

                // Attempt to find file by an Id or Guid passed in
                if (!string.IsNullOrEmpty(id))
                {
                    int fileId;
                    file = int.TryParse(id, out fileId) ? fileService.Get(fileId) : fileService.GetByEncryptedKey(id);
                }

                // ...otherwise create a new BinaryFile
                if (file == null)
                {
                    file = new BinaryFile();
                }

                // Check to see if BinaryFileType info was sent
                BinaryFileTypeService fileTypeService = new BinaryFileTypeService();
                var guid = context.Request.QueryString["fileTypeGuid"];

                if (!string.IsNullOrEmpty(guid))
                {
                    Guid fileTypeGuid;
                    fileType = Guid.TryParse(guid, out fileTypeGuid) ? fileTypeService.Get(fileTypeGuid) : fileTypeService.GetByEncryptedKey(guid);
                }
                else if (file.BinaryFileType != null)
                {
                    fileType = file.BinaryFileType;
                }

                // If we're dealing with a new BinaryFile and a BinaryFileType Guid was passed in,
                // set its Id before the BinaryFile gets saved to the DB.
                if (file.BinaryFileType == null && fileType != null)
                {
                    file.BinaryFileTypeId = fileType.Id;
                }

                SaveData(context, uploadedFile, file, fileType);
                context.Response.Write(new { Id = file.Id, FileName = file.FileName }.ToJson());
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, context);
                context.Response.Write("err:" + ex.Message + "<br>" + ex.StackTrace);
            }
        }
Beispiel #43
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="transactionImageType">Type of the transaction image file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map( ZipArchive folder, BinaryFileType transactionImageType, ProviderComponent storageProvider )
        {
            var lookupContext = new RockContext();

            var emptyJsonObject = "{}";
            var newFileList = new Dictionary<int, Rock.Model.BinaryFile>();
            var transactionIdList = new FinancialTransactionService( lookupContext )
                .Queryable().AsNoTracking().Where( t => t.ForeignId != null )
                .ToDictionary( t => (int)t.ForeignId, t => t.Id );

            int completed = 0;
            int totalRows = folder.Entries.Count;
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying files import ({0:N0} found.", totalRows ) );

            foreach ( var file in folder.Entries )
            {
                var fileExtension = Path.GetExtension( file.Name );
                var fileMimeType = Extensions.GetMIMEType( file.Name );
                if ( BinaryFileComponent.FileTypeBlackList.Contains( fileExtension ) )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not allowed ({1})", fileExtension, file.Name ) );
                    continue;
                }
                else if ( fileMimeType == null )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not recognized ({1})", fileExtension, file.Name ) );
                    continue;
                }

                int? transactionId = Path.GetFileNameWithoutExtension( file.Name ).AsType<int?>();
                if ( transactionId != null && transactionIdList.ContainsKey( (int)transactionId ) )
                {
                    var rockFile = new Rock.Model.BinaryFile();
                    rockFile.IsSystem = false;
                    rockFile.IsTemporary = false;
                    rockFile.FileName = file.Name;
                    rockFile.MimeType = fileMimeType;
                    rockFile.BinaryFileTypeId = transactionImageType.Id;
                    rockFile.CreatedDateTime = file.LastWriteTime.DateTime;
                    rockFile.ModifiedDateTime = ImportDateTime;
                    rockFile.Description = string.Format( "Imported as {0}", file.Name );
                    rockFile.SetStorageEntityTypeId( transactionImageType.StorageEntityTypeId );
                    rockFile.StorageEntitySettings = emptyJsonObject;

                    if ( transactionImageType.AttributeValues.Any() )
                    {
                        rockFile.StorageEntitySettings = transactionImageType.AttributeValues
                            .ToDictionary( a => a.Key, v => v.Value.Value ).ToJson();
                    }

                    // use base stream instead of file stream to keep the byte[]
                    // NOTE: if byte[] converts to a string it will corrupt the stream
                    using ( var fileContent = new StreamReader( file.Open() ) )
                    {
                        rockFile.ContentStream = new MemoryStream( fileContent.BaseStream.ReadBytesToEnd() );
                    }

                    newFileList.Add( transactionIdList[(int)transactionId], rockFile );

                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} files imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFiles( newFileList, storageProvider );

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newFileList.Any() )
            {
                SaveFiles( newFileList, storageProvider );
            }

            ReportProgress( 100, string.Format( "Finished files import: {0:N0} addresses imported.", completed ) );
        }