Example #1
0
        /// <summary>
        /// Generate a URL for the file based on the rules of the StorageProvider
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        public override string GenerateUrl( BinaryFile file )
        {
            if ( string.IsNullOrWhiteSpace( file.FileName ) )
            {
                return null;
            }

            var urlBuilder = new StringBuilder();

            string rootPath = GetRootPath( file.BinaryFileTypeId ?? 0 );

            urlBuilder.Append( rootPath );

            if ( !rootPath.EndsWith( "/" ) )
            {
                urlBuilder.Append( "/" );
            }

            // if the file doesn't have a folderPath, prefix the FileName on disk with the Guid so that we can have multiple files with the same name (for example, setup.exe and setup.exe)
            if ( Path.GetDirectoryName( file.FileName ) == string.Empty )
            {
                urlBuilder.Append( file.Guid + "_" );
            }

            string urlFileName = file.FileName.Replace( "\\", "/" ).TrimStart( new char[] { '/' } );

            urlBuilder.Append( urlFileName );
            return urlBuilder.ToString();
        }
Example #2
0
        public int? SavePersonPhoto( string fileName, string mimeType, string description, byte[] content, bool isSystem = false, bool isTemporary = false, string foreignId = null )
        {
            BinaryFile binaryFile = new BinaryFile();
            binaryFile.FileName = fileName;
            binaryFile.BinaryFileTypeId = new BinaryFileTypeMap(Service).GetPhotoBinaryFileType().Id;
            binaryFile.Url = string.Format( "~/GetImage.ashx?guid={0}", binaryFile.Guid );
            binaryFile.IsSystem = false;
            binaryFile.MimeType = mimeType;
            binaryFile.Description = description;
            binaryFile.IsTemporary = isTemporary;
            binaryFile.ForeignId = foreignId;

            BinaryFileController fileController = new BinaryFileController( Service );
            fileController.Add( binaryFile );

            binaryFile = fileController.GetByGuid(binaryFile.Guid);

            binaryFile.Data = new BinaryFileData();
            binaryFile.Data.Content = content;
            binaryFile.Data.Id = binaryFile.Id;

            BinaryFileDataController fileDataController = new BinaryFileDataController( Service );
            fileDataController.Add( binaryFile.Data );

            return binaryFile.Id;
        }
Example #3
0
 /// <summary>
 /// Deletes the content from the external storage medium associated with the provider.
 /// </summary>
 /// <param name="binaryFile">The binary file.</param>
 public override void DeleteContent( BinaryFile binaryFile )
 {
     var file = new FileInfo( GetFilePath( binaryFile ) );
     if ( file.Exists )
     {
         file.Delete();
     }
 }
Example #4
0
 /// <summary>
 /// Gets the contents from the external storage medium associated with the provider
 /// </summary>
 /// <param name="file">The file.</param>
 /// <returns></returns>
 public override Stream GetContentStream( BinaryFile file )
 {
     if ( file.DatabaseData != null && file.DatabaseData.Content != null )
     {
         return new MemoryStream( file.DatabaseData.Content );
     }
     return new MemoryStream();
 }
Example #5
0
        /// <summary>
        /// Removes the file from the external storage medium associated with the provider.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="context">The context.</param>
        public override void RemoveFile( BinaryFile file, HttpContext context )
        {
            var physicalPath = GetPhysicalPath( file.Url, context );

            if ( File.Exists( physicalPath ) )
            {
                File.Delete( physicalPath );
            }
        }
 /// <summary>
 /// Gets the file content from storage provider.
 /// </summary>
 /// <param name="binaryFile">The binary file.</param>
 private void GetFileContentFromStorageProvider( BinaryFile binaryFile )
 {
     Rock.Storage.ProviderComponent storageProvider = BinaryFileService.DetermineBinaryFileStorageProvider( (Rock.Data.RockContext)Context, binaryFile );
     if ( storageProvider != null )
     {
         binaryFile.Data = binaryFile.Data ?? new BinaryFileData();
         binaryFile.Data.Content = storageProvider.GetFileContent( binaryFile, HttpContext.Current );
     }
 }
Example #7
0
        /// <summary>
        /// Gets the contents from the external storage medium associated with the provider
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        /// <returns></returns>
        public override Stream GetContentStream( BinaryFile binaryFile )
        {
            var file = new FileInfo( GetFilePath( binaryFile ) );
            if ( file.Exists )
            {
                return file.OpenRead();
            }

            return new MemoryStream();
        }
Example #8
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        public void ShowBinaryFileDetail( BinaryFile binaryFile )
        {
            pnlDetails.Visible = true;
            hfBinaryFileId.SetValue( binaryFile.Id );

            if ( binaryFile.BinaryFileTypeId.HasValue )
            {
                fsFile.BinaryFileTypeGuid = new BinaryFileTypeService( new RockContext() ).Get( binaryFile.BinaryFileTypeId.Value ).Guid;
            }

            tbName.Text = binaryFile.FileName;
            tbDescription.Text = binaryFile.Description;
            tbMimeType.Text = binaryFile.MimeType;
            ddlBinaryFileType.SetValue( binaryFile.BinaryFileTypeId );

            btnEditLabelContents.Visible =
                fsFile.BinaryFileId.HasValue &&
                !string.IsNullOrWhiteSpace( GetAttributeValue( "EditLabelPage" ) ) &&
                fsFile.BinaryFileTypeGuid == Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid();

            Guid? workflowTypeGuid = GetAttributeValue( "Workflow" ).AsGuidOrNull();
            btnRerunWorkflow.Visible = workflowTypeGuid.HasValue;

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

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

            phAttributes.Controls.Clear();

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( BinaryFile.FriendlyTypeName );
                btnCancel.Text = "Close";
                Rock.Attribute.Helper.AddDisplayControls( binaryFile, phAttributes );
                fsFile.Enabled = false;
                fsFile.Label = "View File";
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFile, phAttributes, true, BlockValidationGroup );
            }

            tbName.ReadOnly = readOnly;
            tbDescription.ReadOnly = readOnly;
            tbMimeType.ReadOnly = readOnly;
            ddlBinaryFileType.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
Example #9
0
 /// <summary>
 /// Gets the file bytes from the external storage medium associated with the provider.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public override byte[] GetFileContent( BinaryFile file, HttpContext context )
 {
     if (file.Data != null)
     {
         return file.Data.Content;
     }
     else
     {
         return null;
     }
 }
Example #10
0
        /// <summary>
        /// Saves the binary file contents to the external storage medium associated with the provider.
        /// </summary>
        /// <param name="file">The file.</param>
        public override void SaveContent( BinaryFile file )
        {
            if ( file.DatabaseData == null )
            {
                file.DatabaseData = new BinaryFileData();
            }

            using ( var stream = file.ContentStream )
            {
                file.DatabaseData.Content = stream.ReadBytesToEnd();
            }
        }
Example #11
0
        /// <summary>
        /// Gets the file bytes from the external storage medium associated with the provider.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override byte[] GetFileContent( BinaryFile file, HttpContext context )
        {
            var physicalPath = GetPhysicalPath( file.Url, context );

            if ( File.Exists( physicalPath ) )
            {
                return File.ReadAllBytes( physicalPath );
            }
            else
            {
                return null;
            }
        }
Example #12
0
        public static void OpenBinaryFile(string binaryFile, string grammarFile, string comparisonFile)
        {
            BinaryFile file = new BinaryFile(binaryFile);

            List<byte[]> interestingBytes = FilterController.Filter(binaryFile, comparisonFile);

            string outputFile = @"Y:\092010\output_binary.bin";

            using (var stream = File.Create(outputFile))
            {
                for (int i = 0; i < interestingBytes.Count; i++)
                {
                    stream.Write(interestingBytes[i], 0, interestingBytes[i].Length);
                }
            }

            List<byte[]> interestingBytes2 = FilterController.Filter(comparisonFile, binaryFile);

            string outputFile2 = @"Y:\092010\output_comparision.bin";

            using (var stream = File.Create(outputFile2))
            {
                for (int i = 0; i < interestingBytes2.Count; i++)
                {
                    stream.Write(interestingBytes2[i], 0, interestingBytes2[i].Length);
                }
            }

            return;

            int windowSize = 300;
            int shiftAmount = 50;

            Grammar grammar = new Grammar(grammarFile);

            ProcessWindow(interestingBytes, grammar);

            //string startOffsetS = "01d70300";

            //Int64 startOffsetI = Convert.ToInt64(startOffsetS, 16);

            //List<long> startIndexes = new List<long>();

            //for (long i = startOffsetI; i < file.Info.Length-windowSize; i+=shiftAmount)
            //{
            //    startIndexes.Add(i);
            //}

            //Parallel.For(0, startIndexes.Count, i => ProcessWindow(file, grammar, startIndexes[i],i));
        }
Example #13
0
        /// <summary>
        /// Gets the contents from the external storage medium associated with the provider
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        /// <returns></returns>
        public override Stream GetContentStream( BinaryFile binaryFile )
        {
            string filePath = GetFilePath( binaryFile );
            if ( !string.IsNullOrWhiteSpace( filePath ) )
            {
                var file = new FileInfo( GetFilePath( binaryFile ) );
                if ( file.Exists )
                {
                    return file.OpenRead();
                }
            }

            return new MemoryStream();
        }
Example #14
0
        /// <summary>
        /// Determines the storage provider that was used the last time the file was saved
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public static Storage.ProviderComponent DetermineBinaryFileStorageProvider( Rock.Data.RockContext dbContext, BinaryFile item )
        {
            Rock.Storage.ProviderComponent storageProvider = null;

            if ( item != null )
            {
                item.StorageEntityType = item.StorageEntityType ?? new EntityTypeService( dbContext ).Get( item.StorageEntityTypeId ?? 0 );
                if ( item.StorageEntityType != null )
                {
                    storageProvider = Rock.Storage.ProviderContainer.GetComponent( item.StorageEntityType.Name );
                }
            }

            return storageProvider;
        }
 internal static RenderedNode getNodeFromBinaryFile(BinaryFile binaryFile)
 {
     RenderedNode node = RenderedNode.CreateDefault();
     node.TechnicalSource = NodeSourceTypeBinaryFile;
     node.Title = binaryFile.Title;
     node.Excerpt = binaryFile.Description;
     node.ActualContentUrl = binaryFile.Data != null ? binaryFile.Data.ContentUrl : null;
     if (binaryFile.Categories != null)
     {
         node.Categories.CollectionContent.AddRange(getCategoryCollectionTexts(binaryFile.Categories, getTitleOrNameFromCategory));
         node.CategoryNames.CollectionContent.AddRange(getCategoryCollectionTexts(binaryFile.Categories, cat => cat.CategoryName));
         node.CategoryIDList = binaryFile.Categories.SelectedIDCommaSeparated;
     }
     return node;
 }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        public void ShowBinaryFileDetail( BinaryFile binaryFile )
        {
            pnlDetails.Visible = true;
            hfBinaryFileId.SetValue( binaryFile.Id );

            if ( binaryFile.BinaryFileTypeId.HasValue )
            {
                fsFile.BinaryFileTypeGuid = new BinaryFileTypeService( new RockContext() ).Get( binaryFile.BinaryFileTypeId.Value ).Guid;
            }

            tbName.Text = binaryFile.FileName;
            tbDescription.Text = binaryFile.Description;
            tbMimeType.Text = binaryFile.MimeType;
            ddlBinaryFileType.SetValue( binaryFile.BinaryFileTypeId );

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

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

            phAttributes.Controls.Clear();

            if ( readOnly )
            {
                lActionTitle.Text = ActionTitle.View( BinaryFile.FriendlyTypeName );
                btnCancel.Text = "Close";
                Rock.Attribute.Helper.AddDisplayControls( binaryFile, phAttributes );
                fsFile.Enabled = false;
                fsFile.Label = "View File";
            }
            else
            {
                Rock.Attribute.Helper.AddEditControls( binaryFile, phAttributes, true );
            }

            tbName.ReadOnly = readOnly;
            tbDescription.ReadOnly = readOnly;
            tbMimeType.ReadOnly = readOnly;
            ddlBinaryFileType.Enabled = !readOnly;

            btnSave.Visible = !readOnly;
        }
Example #17
0
    public static void Read16Bit(BinaryFile wavfile, double[][] sound, int samplecount, int channels)
    {
        int i = 0;
        int ic = 0;

        #if DEBUG
        Console.Write("Read16Bit...\n");
        #endif

        for (i = 0; i<samplecount; i++) {
            for (ic = 0; ic<channels; ic++) {
                double d = (double) wavfile.ReadInt16();
                d = d / 32768.0;
                sound[ic][i] = d;
            }
        }
    }
        /// <summary>
        /// Gets the path.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        public virtual string GetPath( BinaryFile file )
        {
            string url = string.Empty;

            if ( file != null )
            {
                url = "~/GetFile.ashx";
                if ( file.MimeType != null && file.MimeType.StartsWith( "image/", StringComparison.OrdinalIgnoreCase ) )
                {
                    url = "~/GetImage.ashx";
                }

                url += "?guid=" + file.Guid.ToString();
            }

            return url;
        }
Example #19
0
    public static void Read32BitFloat(BinaryFile wavfile, double[][] sound, int samplecount, int channels)
    {
        int i = 0;
        int ic = 0;

        #if DEBUG
        Console.Write("Read32BitFloat...\n");
        #endif

        for (i = 0;i<samplecount;i++) {
            for (ic = 0;ic<channels;ic++)
            {
                double d = (double) wavfile.ReadSingle();
                sound[ic][i] = d;
            }
        }
    }
Example #20
0
        /// <summary>
        /// Generate a URL for the file based on the rules of the StorageProvider
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        public override string GenerateUrl( BinaryFile file)
        {
            string urlPath;

            switch ( file.MimeType.ToLower() )
            {
                case "image/jpeg":
                case "image/gif":
                case "image/png":
                case "image/bmp":
                    urlPath = "~/GetImage.ashx";
                    break;
                default:
                    urlPath = "~/GetFile.ashx";
                    break;
            }

            return string.Format( "{0}?guid={1}", urlPath, file.Guid );
        }
Example #21
0
        public Stream Load(BinaryFile file)
        {
            var content = binaryFileContentRepository.GetByBinaryFile(file);

            if (content == null || content.Content == null)
            {
                return(null);
            }

            var path      = Path.GetTempFileName();
            var fileName  = Path.GetFileNameWithoutExtension(path);
            var extension = Path.GetExtension(file.Name);
            var fullPath  = Path.Combine(Path.GetDirectoryName(path), $"{fileName}{extension}");

            using (var stream = new FileStream(fullPath, FileMode.CreateNew))
            {
                stream.Write(content.Content, 0, content.Content.Length);
            }

            return(new FileStream(fullPath, FileMode.Open));
        }
Example #22
0
        public static void SaveProjectile(int ProjectileNum)
        {
            string filename;

            filename = Path.Combine(Application.StartupPath, "data", "projectiles", string.Format("projectile{0}.dat", ProjectileNum));

            ByteStream writer = new ByteStream(100);

            writer.WriteString(Projectiles[ProjectileNum].Name);
            writer.WriteInt32(Projectiles[ProjectileNum].Sprite);
            writer.WriteByte(Projectiles[ProjectileNum].Range);
            writer.WriteInt32(Projectiles[ProjectileNum].Speed);
            writer.WriteInt32(Projectiles[ProjectileNum].Damage);
            //Logic
            writer.WriteString(Projectiles[ProjectileNum].OnInstantiate);
            writer.WriteString(Projectiles[ProjectileNum].OnUpdate);
            writer.WriteString(Projectiles[ProjectileNum].OnHitWall);
            writer.WriteString(Projectiles[ProjectileNum].OnHitEntity);

            BinaryFile.Save(filename, ref writer);
        }
Example #23
0
        /// <summary>
        /// Gets from binary file service.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="fileId">The file identifier.</param>
        /// <param name="fileGuid">The file unique identifier.</param>
        /// <returns></returns>
        private BinaryFile GetFromBinaryFileService(HttpContext context, int fileId, RockContext rockContext)
        {
            BinaryFile binaryFile = null;

            System.Threading.ManualResetEvent completedEvent = new ManualResetEvent(false);

            // use the binaryFileService.BeginGet/EndGet which is a little faster than the regular get
            AsyncCallback cb = ( IAsyncResult asyncResult ) =>
            {
                // restore the context from the asyncResult.AsyncState
                HttpContext asyncContext = ( HttpContext )asyncResult.AsyncState;
                binaryFile = new BinaryFileService(rockContext).EndGet(asyncResult, context);
                completedEvent.Set();
            };

            IAsyncResult beginGetResult = new BinaryFileService(rockContext).BeginGet(cb, context, fileId);

            // wait up to 5 minutes for the response
            completedEvent.WaitOne(300000);
            return(binaryFile);
        }
Example #24
0
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues"></param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            var picker = control as BinaryFilePicker;

            if (picker != null)
            {
                BinaryFile binaryFile = null;
                Guid?      guid       = value.AsGuidOrNull();

                // get the item (or null) and set it
                if (guid.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        binaryFile = new BinaryFileService(rockContext).Get(guid.Value);
                    }
                }

                picker.SetValue(binaryFile);
            }
        }
Example #25
0
        public static void Main(string[] args)
        {
            string inLeft  = @"F:\SAMPLES\IMPULSE RESPONSES\PER IVAR IR SAMPLES\ALTIVERB-QUAD-IMPULSE-RESPONSES\Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90_L.wav";
            string inRight = @"F:\SAMPLES\IMPULSE RESPONSES\PER IVAR IR SAMPLES\ALTIVERB-QUAD-IMPULSE-RESPONSES\Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90_R.wav";

            float[] channel1;
            float[] channel2;
            float[] channel3;
            float[] channel4;
            AudioUtilsNAudio.SplitStereoWaveFileToMono(inLeft, out channel1, out channel2);
            AudioUtilsNAudio.SplitStereoWaveFileToMono(inRight, out channel3, out channel4);

            // find out what channel is longest
            int maxLength = Math.Max(channel1.Length, channel3.Length);

            string outputFile = @"Scoring Stages (Orchestral Studios)_Todd-AO - California US_st to st wide mics at 18m90V2.sir";

            //string cfh_data = @"abe6f4214362.34U4T9yaBCCDEuyH0uCm7T6Pf.z+PqR.kBAoHEfz3DlPB4lX.K4XirMP+3WCzJZ6RYE0ka38ty94e5j858dEG1RUZlT3iZV2EATQgrjIV5ixyF5zA0qasZdXlJpZ8FtlNjwomlnU8lHn+JhPP48khE9n1HPSpVyoJhg5itqiqqKp600.vKJEevIQJ4fXS0aTksgilV6fMkL4wNFPLDn33w5irgZ7lpiNZaJe791OXu1ATcghs1bHHwzElL49JBlnXKYBBeeT8QCedFNXTRbHdVznj7XbHjFhSlLFaURBSgnoA1RJ7UWAwYQSCSew407fANeNiyoYvERkkO.1PVR0vMSTEqnZihvsR6eC5ammIKKcBl.NPeBmsPpDLBjimqMfQB15NVIEpXEZfXflcpdxcd77xh56HaQM9Shz7rIRJa4p+EHo0YfjCv3BeKI87QR6yGIW1qI+hIdM99OMVIuF+7+KqzUe.bo2V9C";
            string cfh_data = @"abe6f42143                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      ";

            BinaryFile binaryFile = new BinaryFile(outputFile, BinaryFile.ByteOrder.LittleEndian, true);

            binaryFile.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            binaryFile.Write("\n\n");
            binaryFile.Write("<SirImpulseFile version=\"2.1\" cfh_data=\"");
            binaryFile.Write(cfh_data);
            binaryFile.Write("\"/>");
            binaryFile.Write("\r\n");
            binaryFile.Write((byte)0);

            WriteAudioBlock(binaryFile, channel1, maxLength, "0");
            WriteAudioBlock(binaryFile, channel2, maxLength, "1");
            WriteAudioBlock(binaryFile, channel3, maxLength, "2");
            WriteAudioBlock(binaryFile, channel4, maxLength, "3");

            binaryFile.Close();

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
Example #26
0
        public void UploadFile(BinaryFile file)
        {
            DataFileModel model = new DataFileModel();

            model.Date    = file.Date;
            model.User.Id = file.User.Id;
            model.Path    = FileManager.GetFileManager().SaveSessionsFile(file);
            GlobalConfig.Connection.File_Insert(model);
            var sessions = BinaryConnector.StaticLoad <List <AppSession> >(model.Path);

            foreach (var session in sessions)
            {
                if (session.MouseData != null && session.EndTime != DateTime.MinValue)
                {
                    AppModel appModel = new AppModel();
                    appModel.ProcessName = session.App.ProcessName;
                    GlobalConfig.Connection.App_Insert(appModel);
                    SessionModel sessionModel = new SessionModel();
                    sessionModel.AppId = appModel.Id;
                    sessionModel.BackspaceStrokesCount = session.KeyboardData.BackspaceStrokesCount;
                    sessionModel.StrokesCount          = session.KeyboardData.StrokesCount;
                    sessionModel.StrokeHoldTimes       = session.KeyboardData.StrokeHoldTimes;
                    sessionModel.UniqueKeysCount       = session.KeyboardData.UniqueKeysCount;
                    sessionModel.MouseClickCount       = (int)session.MouseData.MouseClickCount;
                    sessionModel.MouseClickTotalTime   = (int)session.MouseData.MouseClickTotalTime;
                    sessionModel.StartTime             = session.StartTime;
                    sessionModel.EndTime = session.EndTime;
                    sessionModel.UserId  = model.User.Id;
                    sessionModel.AppId   = appModel.Id;
                    GlobalConfig.Connection.Session_Insert(sessionModel);
                    if (session.App.Type == HRPMSharedLibrary.Enums.AppType.Browser)
                    {
                        DomainModel domainModel = new DomainModel();
                        domainModel.Domain = session.App.Content;
                        GlobalConfig.Connection.Domain_Insert(domainModel);
                        GlobalConfig.Connection.SessionDomain_Insert(sessionModel.Id, domainModel.Id);
                    }
                }
            }
        }
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            SignatureDocumentService signatureDocumentService = new SignatureDocumentService(rockContext);
            BinaryFileService        binaryfileService        = new BinaryFileService(rockContext);
            PersonAliasService       personAliasService       = new PersonAliasService(rockContext);

            errorMessages = new List <string>();

            // Get all the attribute values
            var        mergeFields        = GetMergeFields(action);
            int        documentTemplateId = GetAttributeValue(action, "DocumentTemplateId", true).AsInteger();
            Guid       documentGuid       = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Document").AsGuid()).AsGuid();
            BinaryFile binaryFile         = binaryfileService.Get(documentGuid);
            string     documentKey        = GetAttributeValue(action, "DocumentKey", true).ResolveMergeFields(mergeFields);
            string     documentName       = GetAttributeValue(action, "DocumentName", true).ResolveMergeFields(mergeFields);
            Guid       assignedTo         = GetAttributeValue(action, "AssignedTo", true).AsGuid();
            Guid       appliesTo          = GetAttributeValue(action, "AppliesTo", true).AsGuid();
            Guid       signedBy           = GetAttributeValue(action, "SignedBy", true).AsGuid();

            if (binaryFile != null)
            {
                // Create the signature document
                Rock.Model.SignatureDocument document = new Rock.Model.SignatureDocument();
                document.AssignedToPersonAliasId = personAliasService.Get(assignedTo).Id;
                document.AppliesToPersonAliasId  = personAliasService.Get(appliesTo).Id;
                document.SignedByPersonAliasId   = personAliasService.Get(signedBy).Id;
                document.Name         = documentName;
                document.DocumentKey  = documentKey;
                document.BinaryFileId = binaryFile.Id;
                document.SignatureDocumentTemplateId = documentTemplateId;
                document.LastInviteDate = RockDateTime.Now;
                document.LastStatusDate = RockDateTime.Now;
                document.Status         = SignatureDocumentStatus.Signed;

                // Add the signature document to the service
                signatureDocumentService.Add(document);
            }

            return(true);
        }
            public static List <SkillData> Load()
            {
                try
                {
                    List <SkillData> CustomDefinitions = new List <SkillData>();

                    if (Directory.Exists(Dir_Definitions))
                    {
                        var files = Directory.GetFiles(Dir_Definitions);

                        foreach (var file in files)
                        {
                            bool failed;

                            _SkillData _skilldata = BinaryFile.ReadFromFile <_SkillData>(file, out failed);

                            if (!failed)
                            {
                                SkillData newSkillData = Convert_ToClass(_skilldata);

                                CustomDefinitions.Add(newSkillData);
                            }
                            else
                            {
                                _SkillData_int _skilldata_int = BinaryFile.ReadFromFile <_SkillData_int>(file, out failed);

                                SkillData newSkillData = Convert_ToClass(_skilldata_int);

                                CustomDefinitions.Add(newSkillData);
                            }
                        }
                    }

                    return(CustomDefinitions);
                }
                catch
                {
                    return(new List <SkillData>());
                }
            }
Example #29
0
        /// <summary>
        /// Handles the FileUploaded event of the fsFile 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 fsFile_FileUploaded(object sender, EventArgs e)
        {
            var        rockContext       = new RockContext();
            var        binaryFileService = new BinaryFileService(rockContext);
            BinaryFile binaryFile        = null;

            if (fsFile.BinaryFileId.HasValue)
            {
                binaryFile = binaryFileService.Get(fsFile.BinaryFileId.Value);
            }

            if (binaryFile != null)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text))
                {
                    binaryFile.FileName = tbName.Text;
                }

                // set binaryFile.Id to original id since the UploadedFile is a temporary binaryFile with a different id
                binaryFile.Id               = hfBinaryFileId.ValueAsInt();
                binaryFile.Description      = tbDescription.Text;
                binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();
                if (binaryFile.BinaryFileTypeId.HasValue)
                {
                    binaryFile.BinaryFileType = new BinaryFileTypeService(rockContext).Get(binaryFile.BinaryFileTypeId.Value);
                }

                var tempList = OrphanedBinaryFileIdList;
                tempList.Add(fsFile.BinaryFileId.Value);
                OrphanedBinaryFileIdList = tempList;

                // load attributes, then get the attribute values from the UI
                binaryFile.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues(phAttributes, binaryFile);

                LaunchFileUploadWorkflow(binaryFile, binaryFileService);

                ShowBinaryFileDetail(binaryFile);
            }
        }
Example #30
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                string itemId = PageParameter( "BinaryFileId" );
                string typeId = PageParameter( "BinaryFileTypeId" );
                if ( !string.IsNullOrWhiteSpace( itemId ) )
                {
                    if ( string.IsNullOrWhiteSpace( typeId ) )
                    {
                        ShowDetail( "BinaryFileId", int.Parse( itemId ) );
                    }
                    else
                    {
                        ShowDetail( "BinaryFileId", int.Parse( itemId ), int.Parse( typeId ) );
                    }
                }
                else
                {
                    pnlDetails.Visible = false;
                }

                ddlBinaryFileType.Visible = GetAttributeValue( "ShowBinaryFileType" ).AsBoolean();
            }
            else
            {
                if ( pnlDetails.Visible )
                {
                    var binaryFile = new BinaryFile { BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt() ?? 0 };
                    if ( binaryFile.BinaryFileTypeId > 0 )
                    {
                        binaryFile.LoadAttributes();
                        phAttributes.Controls.Clear();
                        Rock.Attribute.Helper.AddEditControls( binaryFile, phAttributes, false );
                    }
                }
            }
        }
Example #31
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        /// <param name="binaryFileTypeId">The binary file type id.</param>
        public void ShowDetail(string itemKey, int itemKeyValue, int?binaryFileTypeId)
        {
            if (!itemKey.Equals("BinaryFileId"))
            {
                return;
            }

            var        binaryFileService = new BinaryFileService();
            BinaryFile BinaryFile        = null;

            if (!itemKeyValue.Equals(0))
            {
                BinaryFile = binaryFileService.Get(itemKeyValue);
            }

            if (BinaryFile != null)
            {
                lActionTitle.Text = ActionTitle.Edit(BinaryFile.BinaryFileType.Name);
            }
            else
            {
                BinaryFile = new BinaryFile {
                    Id = 0, IsSystem = false, BinaryFileTypeId = binaryFileTypeId
                };

                string friendlyName = BinaryFile.FriendlyTypeName;
                if (binaryFileTypeId.HasValue)
                {
                    var binaryFileType = new BinaryFileTypeService().Get(binaryFileTypeId.Value);
                    if (binaryFileType != null)
                    {
                        friendlyName = binaryFileType.Name;
                    }
                }

                lActionTitle.Text = ActionTitle.Add(friendlyName);
            }

            ShowDetail(BinaryFile);
        }
Example #32
0
        private void UpdatePersonPhoto(Rock.Model.Person person, MemoryStream photoData)
        {
            RockContext   rockContext   = new RockContext();
            PersonService personService = new PersonService(rockContext);

            person = personService.Get(person.Id);


            var binaryFileType = new BinaryFileTypeService(rockContext).GetNoTracking(Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid());

            var fileName = person.FullName.RemoveSpaces().MakeValidFileName();

            if (fileName.IsNullOrWhiteSpace())
            {
                fileName = "PersonPhoto";
            }

            var binaryFile = new BinaryFile()
            {
                FileName         = fileName,
                MimeType         = "image/jpeg",
                BinaryFileTypeId = binaryFileType.Id,
                IsTemporary      = false
            };

            binaryFile.SetStorageEntityTypeId(binaryFileType.StorageEntityTypeId);

            byte[] photoDataBytes = photoData.ToArray();
            binaryFile.FileSize      = photoDataBytes.Length;
            binaryFile.ContentStream = new MemoryStream(photoDataBytes);

            var binaryFileService = new BinaryFileService(rockContext);

            binaryFileService.Add(binaryFile);
            rockContext.SaveChanges();

            person.PhotoId = binaryFile.Id;

            rockContext.SaveChanges();
        }
Example #33
0
        public models Stripify(string filePath)
        {
            var stgpv    = new Model();
            var textures = new MikuMikuLibrary.Textures.TextureSet();
            var texdb    = new TextureDatabase();

            using (var farcArchive = BinaryFile.Load <FarcArchive>(filePath))
            {
                using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("txi")).First(), EntryStreamMode.MemoryStream))
                    texdb.Load(entryStream);
                using (var entryStream = farcArchive.Open(farcArchive.Entries.Where(c => c.Contains("txd")).First(), EntryStreamMode.MemoryStream))
                    textures.Load(entryStream);
                using (var entryStream = farcArchive.Open(farcArchive.Entries.First(), EntryStreamMode.MemoryStream))
                    stgpv.Load(entryStream, textures, texdb);
            }

            foreach (var meshes in stgpv.Meshes)
            {
                foreach (var submeshes in meshes.SubMeshes)
                {
                    foreach (var indexTable in submeshes.IndexTables)
                    {
                        ushort[] triangleStrip = Stripifier.Stripify(indexTable.Indices);
                        if (triangleStrip != null)
                        {
                            indexTable.PrimitiveType = PrimitiveType.TriangleStrip;
                            indexTable.Indices       = triangleStrip;
                        }
                    }
                }
            }

            var le_model = new models();

            le_model.model    = stgpv;
            le_model.fileName = filePath;
            Logs.WriteLine("Stripified " + Path.GetFileName(filePath));
            return(le_model);
        }
Example #34
0
        private void AddDocuments(ref Application application, out bool Valid, IEnumerable <HttpPostedFileBase> docs)
        {
            Valid = true;
            foreach (var f in docs)
            {
                if (f != null)
                {
                    string mimeType = f.ContentType;
                    if (mimeType == "application/pdf" || mimeType == "application/msword" || mimeType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || mimeType == "application/vnd.openxmlformats-officedocument.wordprocessingml.template")
                    {
                        Valid = true;

                        string fileName   = Path.GetFileName(f.FileName);
                        int    fileLength = f.ContentLength;
                        if (!(fileName == "" || fileLength == 0))
                        {
                            Stream fileStream = f.InputStream;
                            byte[] fileData   = new byte[fileLength];
                            fileStream.Read(fileData, 0, fileLength);

                            BinaryFile newFile = new BinaryFile
                            {
                                FileContent = new FileContent
                                {
                                    Content  = fileData,
                                    MimeType = mimeType
                                },
                                FileName = fileName
                            };
                            application.BinaryFiles.Add(newFile);
                        }
                    }
                    else
                    {
                        Valid = false;
                    }
                }
            }
        }
Example #35
0
        protected void mdEdit_SaveClick(object sender, EventArgs e)
        {
            // Save the image
            // SetAttributeValue("BackgroundImage", imgupTitleBackground.BinaryFileId);
            SetAttributeValue("TitleText", tbTopperTitle.Text);
            RockContext       rockContext       = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService(rockContext);
            BinaryFile        backgroundImage   = binaryFileService.Get(imgupTitleBackground.BinaryFileId ?? 0);

            if (backgroundImage != null)
            {
                backgroundImage.IsTemporary = false;
                rockContext.SaveChanges();
            }

            SetAttributeValue("BackgroundImageId", imgupTitleBackground.BinaryFileId.ToString());
            SetAttributeValue("InfoPanelContent", htmlInfoPanelContent.Text);
            SetAttributeValue("InfoPanelBackgroundRGBValue", cpBackground.Text);
            SetAttributeValue("InfoPanelVisible", cbInfoPanel.Checked.ToString());
            SaveAttributeValues();
            mdEdit.Hide();
        }
Example #36
0
        public static void LoadProjectiles()
        {
            string filename;
            int    i;

            CheckProjectile();

            for (i = 1; i <= MAX_PROJECTILES; i++)
            {
                filename = Path.Combine(Application.StartupPath, "data", "projectiles", string.Format("projectile{0}.dat", i));
                ByteStream reader = new ByteStream();
                BinaryFile.Load(filename, ref reader);

                Projectiles[i].Name   = reader.ReadString();
                Projectiles[i].Sprite = reader.ReadInt32();
                Projectiles[i].Range  = reader.ReadByte();
                Projectiles[i].Speed  = reader.ReadInt32();
                Projectiles[i].Damage = reader.ReadInt32();

                //Application.DoEvents();
            }
        }
        private static Entry parse_nimd_entry(BinaryFile bFile)
        {
            // read boolean (1 byte)
            bool isList = bFile.ReadBoolean();

            // ready 2 ints (8 bytes)
            int total_size = bFile.ReadInt32();
            int name_size  = bFile.ReadInt32();

            string name = bFile.ReadString(name_size);

            if (isList)
            {
                return(parse_nimd_entry_list(bFile, name));
            }

            // ready 2 ints (8 bytes)
            int data_offset = bFile.ReadInt32();
            int data_size   = bFile.ReadInt32();

            return(new Entry(name, data_offset, data_size));
        }
Example #38
0
        /// <summary>
        /// Saves the data.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="inputStream">The input stream.</param>
        /// <param name="file">The file.</param>
        public override void SaveData(HttpContext context, Stream inputStream, BinaryFile file)
        {
            // Check to see if we should flip the image.
            try
            {
                Bitmap bmp  = new Bitmap(inputStream);
                var    exif = new EXIFextractor(ref bmp, "\n");
                if (exif["Orientation"] != null)
                {
                    RotateFlipType flip = OrientationToFlipType(exif["Orientation"].ToString());
                    if (flip != RotateFlipType.RotateNoneFlipNone)   // don't flip if orientation is correct
                    {
                        bmp.RotateFlip(flip);
                        exif.setTag(0x112, "1");   // reset orientation tag
                    }
                }

                if (context.Request.QueryString["enableResize"] != null)
                {
                    Bitmap resizedBmp = RoughResize(bmp, 1024, 768);
                    bmp = resizedBmp;
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    bmp.Save(stream, ContentTypeToImageFormat(file.MimeType));
                    if (file.Data == null)
                    {
                        file.Data = new BinaryFileData();
                    }
                    file.Data.Content = stream.ToArray();
                    stream.Close();
                }
            }
            catch
            {
                // TODO: Log unable to rotate and/or resize.
            }
        }
        private void SetFileSize(BinaryFile file, DevComponents.DotNetBar.LabelX label, bool sizesSame)
        {
            if (file == null || !file.IsFileOnDisk)
            {
                label.Text = "-";
                return;
            }

            double numMegaBytes = file.GetFileSize() / (1024d * 1024d);

            if (numMegaBytes >= 1)
                label.Text = numMegaBytes + " MB";
            else
            {
                numMegaBytes = file.GetFileSize() / 1024d;
                label.Text = numMegaBytes + " kB";
            }
            if (sizesSame)
                pictureBoxFilesize.Image = System.Drawing.Image.FromStream(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Slyce.IntelliMerge.Resources.font_char61_green_16_h.png"));
            else
                pictureBoxFilesize.Image = System.Drawing.Image.FromStream(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Slyce.IntelliMerge.Resources.font_char33_red_16_h.png"));
        }
        /// <summary>
        /// Extract NI Massive's tables.dat file into a specified output directory
        /// </summary>
        /// <param name="tablesDatFilePath">path to tables.dat</param>
        /// <param name="outputDirPath">path to output directory</param>
        /// <returns></returns>
        public static bool Extract(string tablesDatFilePath, string outputDirPath)
        {
            if (File.Exists(tablesDatFilePath))
            {
                string fileName = Path.GetFileNameWithoutExtension(tablesDatFilePath);

                // read in the map to save as NI Massive's GUI filenames
                var map = MassiveMapping.ReadMassiveMapping("massive_map.csv");

                var   bFile = new BinaryFile(tablesDatFilePath, BinaryFile.ByteOrder.LittleEndian);
                Entry nimd  = parse_nimd_file(bFile);
                extract_nimd_entry(bFile, nimd, outputDirPath, outputDirPath, map);

                bFile.Close();

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #41
0
        /// <summary>
        /// 检查序列化文件是否存在,如果存在就读取再保存到access数据库,不存在就new一个新的list
        /// </summary>
        private void CheckFileBuff()
        {
            try
            {
                //检查目录下是否有序列化文件,若存在就反序列化读取,不存在就创new一个新的list
                if (File.Exists(fileName))
                {
                    DataBase.DBHelp.FileName = DataBase.DBHelp.fileName;                        //指定数据库路径
                    BinaryFile.FileName      = fileName;                                        //指定序列化文件路径
                    //读取出序列化文件的内容到List表
                    recLst = BinaryFile.ReadBinary().ConvertAll(s => (Models.DataBaseRecord)s); //读取序列化文件内容到list
                    Models.DataBaseRecord rec     = recLst[0];                                  //获取出列表第一个参数项
                    List <string>         listTem = new List <string>();                        //实例化一个类属性让下面SQL语读出查找的项用来做判断

                    listTem = DataBase.CQServices.GetRecordSql(@"SELECT DataSheet.serialNumber
                                                            FROM DataSheet
                                                            WHERE(((DataSheet.serialNumber) = '" + rec.serialNumber + @"'))");

                    //判断数据库里有无重复编号,有的话就删除,没有就插入
                    if (listTem.Count > 0)
                    {
                        DataBase.CQServices.DeleteRecord(rec.serialNumber); //删除重复项
                    }
                    DataBase.CQServices.BulckInsert(recLst);                //向ACCESS数据库添加数据列表
                    File.Delete(fileName);                                  //删除序列化文件
                    recLst.Clear();                                         //清空数据列表
                }
                else
                {
                    recLst.Clear();
                }
            }
            catch (Exception ex)
            {
                CMessageBox.Show(ex.Message, "提示");
                return;
            }
        }
        /// <summary>
        /// Saves the specified <see cref="Rock.Model.BinaryFile"/>.
        /// </summary>
        /// <param name="item">A <see cref="Rock.Model.BinaryFile"/> to save.</param>
        /// <param name="personId">A <see cref="System.Int32"/> representing the PersonId of the <see cref="Rock.Model.Person"/> who is saving the BinaryFile..</param>
        /// <returns></returns>
        public override bool Save( BinaryFile item, int? personId )
        {
            item.LastModifiedDateTime = DateTime.Now;
            Rock.Storage.ProviderComponent storageProvider = DetermineBinaryFileStorageProvider( item );

            if ( storageProvider != null )
            {
                //// if this file is getting replaced, and we can determine the StorageProvider, use the provider to get and remove the file from the provider's 
                //// external storage medium before we save it again. This especially important in cases where the provider for this filetype has changed 
                //// since it was last saved

                // first get the FileContent from the old/current fileprovider in case we need to save it somewhere else
                item.Data = item.Data ?? new BinaryFileData();
                item.Data.Content = storageProvider.GetFileContent( item, HttpContext.Current );

                // now, remove it from the old/current fileprovider
                storageProvider.RemoveFile( item, HttpContext.Current );
            }

            // when a file is saved (unless it is getting Deleted/Saved), it should use the StoredEntityType that is associated with the BinaryFileType
            if ( item.BinaryFileType != null )
            {
                // make sure that it updated to use the same storage as specified by the BinaryFileType
                if ( item.StorageEntityTypeId != item.BinaryFileType.StorageEntityTypeId )
                {
                    item.SetStorageEntityTypeId( item.BinaryFileType.StorageEntityTypeId );
                    storageProvider = DetermineBinaryFileStorageProvider( item );
                }
            }

            if ( storageProvider != null )
            {
                // save the file to the provider's new storage medium
                storageProvider.SaveFile( item, HttpContext.Current );
            }

            return base.Save( item, personId );
        }
        protected void lbExport_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var           batchId    = tbBatchId.Text.AsInteger();
                var           batches    = new FinancialBatchService(rockContext).Queryable().Where(b => b.Id == batchId).ToList();
                var           fileFormat = new ImageCashLetterFileFormatService(rockContext).Get(ddlFileFormat.SelectedValue.AsInteger());
                var           component  = FileFormatTypeContainer.GetComponent(fileFormat.EntityType.Name);
                List <string> errorMessages;

                fileFormat.LoadAttributes(rockContext);

                var mergeFields = new Dictionary <string, object>
                {
                    { "FileFormat", fileFormat }
                };
                var filename = fileFormat.FileNameTemplate.ResolveMergeFields(mergeFields);

                var stream = component.ExportBatches(fileFormat, batches, out errorMessages);

                var binaryFileService     = new BinaryFileService(rockContext);
                var binaryFileTypeService = new BinaryFileTypeService(rockContext);
                var binaryFile            = new BinaryFile
                {
                    BinaryFileTypeId = binaryFileTypeService.Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid()).Id,
                    IsTemporary      = true,
                    FileName         = filename,
                    MimeType         = "octet/stream",
                    ContentStream    = stream
                };

                binaryFileService.Add(binaryFile);
                rockContext.SaveChanges();

                pnlSuccess.Visible     = true;
                hlDownload.NavigateUrl = ResolveUrl(string.Format("~/GetFile.ashx?Id={0}&attachment=True", binaryFile.Id));
            }
        }
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="toPersonId">To person identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="newMessage">if set to <c>true</c> [new message].</param>
        private void SendMessageToPerson(int toPersonId, string message, bool newMessage)
        {
            using (var rockContext = new RockContext())
            {
                // The sender is the logged in user.
                int    fromPersonAliasId = CurrentUser.Person.PrimaryAliasId.Value;
                string fromPersonName    = CurrentUser.Person.FullName;

                // The sending phone is the selected one
                DefinedValueCache fromPhone = DefinedValueCache.Get(hfSmsNumber.ValueAsInt());

                string responseCode = Rock.Communication.Medium.Sms.GenerateResponseCode(rockContext);

                BinaryFile        binaryFile = null;
                List <BinaryFile> photos     = null;

                if (!newMessage && ImageUploaderConversation.BinaryFileId.IsNotNullOrZero())
                {
                    // If this is a response using the conversation window and a photo file has been uploaded then add it
                    binaryFile = new BinaryFileService(rockContext).Get(ImageUploaderConversation.BinaryFileId.Value);
                }
                else if (newMessage && ImageUploaderModal.BinaryFileId.IsNotNullOrZero())
                {
                    // If this is a new message using the modal and a photo file has been uploaded then add it
                    binaryFile = new BinaryFileService(rockContext).Get(ImageUploaderModal.BinaryFileId.Value);
                }

                photos = binaryFile != null ? new List <BinaryFile> {
                    binaryFile
                } : null;

                var toPrimaryAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(toPersonId);

                // Create and enqueue the communication
                Rock.Communication.Medium.Sms.CreateCommunicationMobile(CurrentUser.Person, toPrimaryAliasId, message, fromPhone, responseCode, rockContext, photos);
                ImageUploaderConversation.BinaryFileId = null;
            }
        }
        public static void SaveAnimation(int AnimationNum)
        {
            string filename;
            int    x;

            filename = Path.Combine(Application.StartupPath, "data", "animations", string.Format("animation{0}.dat", AnimationNum));

            ByteStream writer = new ByteStream(100);

            writer.WriteString(Types.Animation[AnimationNum].Name);
            writer.WriteString(Types.Animation[AnimationNum].Sound);
            var loopTo = Information.UBound(Types.Animation[AnimationNum].Sprite);

            for (x = 0; x <= loopTo; x++)
            {
                writer.WriteInt32(Types.Animation[AnimationNum].Sprite[x]);
            }
            var loopTo1 = Information.UBound(Types.Animation[AnimationNum].Frames);

            for (x = 0; x <= loopTo1; x++)
            {
                writer.WriteInt32(Types.Animation[AnimationNum].Frames[x]);
            }
            var loopTo2 = Information.UBound(Types.Animation[AnimationNum].LoopCount);

            for (x = 0; x <= loopTo2; x++)
            {
                writer.WriteInt32(Types.Animation[AnimationNum].LoopCount[x]);
            }
            var loopTo3 = Information.UBound(Types.Animation[AnimationNum].LoopTime);

            for (x = 0; x <= loopTo3; x++)
            {
                writer.WriteInt32(Types.Animation[AnimationNum].LoopTime[x]);
            }

            BinaryFile.Save(filename, ref writer);
        }
        /// <summary>
        /// Метод изменяет анкету текущего пользователя
        /// </summary>
        /// <returns></returns>
        public ActionResult EditProfile()
        {
            var profile = jobseekerRepository.FindProfile(Convert.ToInt64(User.Identity.GetUserId()));

            if (profile != null)
            {
                var exp = GetExperienceLists();
                foreach (SelectListItem e in exp)
                {
                    if (profile.Experience.Contains(experienceRepository.Load(Convert.ToInt64(e.Value))) == true)
                    {
                        e.Selected = true;
                    }
                }
                BinaryFile file = new BinaryFile();
                if (profile.Avatar != null && System.IO.File.Exists(profile.Avatar.Path))
                {
                    file.Content     = System.IO.File.ReadAllBytes(profile.Avatar.Path);
                    file.ContentType = profile.Avatar.ContentType;
                    file.Name        = profile.Avatar.Name;
                    file.Path        = profile.Avatar.Path;
                }
                var model = new ProfileModel
                {
                    Entity      = profile,
                    Id          = profile.Id,
                    Experience  = exp,
                    DateOfBirth = profile.DateofBirth,
                    Name        = profile.Name,
                    File        = file
                };
                return(View(model));
            }
            else
            {
                return(RedirectToAction("CreateProfile", "Jobseeker"));
            }
        }
Example #47
0
        /// <summary>
        /// Saves the binary file contents to the external storage medium associated with the provider.
        /// </summary>
        /// <param name="binaryFile">The binary file.</param>
        /// <exception cref="System.ArgumentException">File Data must not be null.</exception>
        public override void SaveContent( BinaryFile binaryFile )
        {
            var filePath = GetFilePath( binaryFile );

            // Create the directory if it doesn't exist
            var directoryName = Path.GetDirectoryName( filePath );
            if ( !Directory.Exists( directoryName ) )
            {
                Directory.CreateDirectory( directoryName );
            }

            // Write the contents to file
            using ( var inputStream = binaryFile.ContentStream )
            {
                if ( inputStream != null )
                {
                    using ( var outputStream = File.OpenWrite( filePath ) )
                    {
                        inputStream.CopyTo( outputStream );
                    }
                }
            }
        }
Example #48
0
        /// <summary>
        /// Saves the file to the external storage medium associated with the provider.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="System.ArgumentException">File Data must not be null.</exception>
        public override void SaveFile( BinaryFile file, HttpContext context )
        {
            if ( file.Data == null )
            {
                throw new ArgumentException( "File Data must not be null." );
            }

            var url = GenerateUrl( file );
            var physicalPath = GetPhysicalPath( url, context );
            var directoryName = Path.GetDirectoryName( physicalPath );

            if ( !Directory.Exists( directoryName ) )
            {
                Directory.CreateDirectory( directoryName );
            }

            File.WriteAllBytes( physicalPath, file.Data.Content );

            // Set Data to null after successful OS save so the the binary data is not 
            // written into the database.
            file.Data = null;
            file.Url = url;
        }
Example #49
0
        public static void Write8Bit(BinaryFile waveFile, float[][] sound, int sampleCount, int channels)
        {
            for (int i = 0; i < sampleCount; i++)
            {
                for (int ic = 0; ic < channels; ic++)
                {
                    int val = SoundIOUtils.RoundToClosestInt((sound[ic][i] + 1) * 128);

                    if (val > 255)
                    {
                        val = 255;
                    }
                    if (val < 0)
                    {
                        val = 0;
                    }

                    byte b = (byte)val;

                    waveFile.Write(b);
                }
            }
        }
Example #50
0
        /// <summary>
        /// Handles the Delete event of the gBinaryFile control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gBinaryFile_Delete(object sender, RowEventArgs e)
        {
            RockTransactionScope.WrapTransaction(() =>
            {
                BinaryFileService binaryFileService = new BinaryFileService();
                BinaryFile binaryFile = binaryFileService.Get((int)e.RowKeyValue);

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

                    binaryFileService.Delete(binaryFile, CurrentPersonId);
                    binaryFileService.Save(binaryFile, CurrentPersonId);
                }
            });

            BindGrid();
        }
Example #51
0
        /// <summary>
        /// Saves the file to the external storage medium associated with the provider.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="System.ArgumentException">File Data must not be null.</exception>
        public override void SaveFile(BinaryFile file, HttpContext context)
        {
            if (file.Data == null)
            {
                throw new ArgumentException("File Data must not be null.");
            }

            var url           = GenerateUrl(file);
            var physicalPath  = GetPhysicalPath(url, context);
            var directoryName = Path.GetDirectoryName(physicalPath);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }

            File.WriteAllBytes(physicalPath, file.Data.Content);

            // Set Data to null after successful OS save so the the binary data is not
            // written into the database.
            file.Data = null;
            file.Url  = url;
        }
Example #52
0
        /// <summary>
        /// Parse out the xml string from the passed chunk data byte array
        /// </summary>
        /// <param name="chunkDataByteArray"></param>
        /// <returns>xml string</returns>
        private static string ParseChunkData(byte[] chunkDataByteArray)
        {
            var bf = new BinaryFile(chunkDataByteArray, BinaryFile.ByteOrder.BigEndian, Encoding.ASCII);

            int    val1 = bf.ReadInt32();
            int    val2 = bf.ReadInt32();
            int    val3 = bf.ReadInt32();
            string val4 = bf.ReadString(4);
            string val5 = bf.ReadString(4);

            int chunkSize = bf.ReadInt32();

            string val7 = bf.ReadString(4);

            var xmlChunkBytes = new byte[chunkSize];

            xmlChunkBytes = bf.ReadBytes(0, chunkSize, BinaryFile.ByteOrder.LittleEndian);
            string xmlString = BinaryFile.ByteArrayToString(xmlChunkBytes);

            int val8 = bf.ReadInt32(BinaryFile.ByteOrder.LittleEndian);

            return(xmlString);
        }
Example #53
0
        static void Test3()
        {
            File.Delete(@"z:\te.ed");
            var       ef     = new BinaryFile(@"z:\te.ed");
            Stopwatch sw     = new Stopwatch();
            var       writer = ef.GetWriter();
            var       reader = ef.GetReader();
            int       w      = sizeof(int);
            int       count  = 200000;
            int       l      = w * count;

            sw.Start();
            writer.Write(1, count);
            sw.Stop();

            Console.WriteLine(sw.ElapsedMilliseconds);

            var x = new FileInfo(@"z:\te.ed");

            ef.Dispose();

            Console.WriteLine(x.Length == l);
        }
Example #54
0
        /// <summary>
        /// Handles the Click event of the lbPrepareCertificate 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 lbPrepareCertificate_Click(object sender, EventArgs e)
        {
            //
            // Decode the data in the hidden field into the raw certificate data.
            //
            var certData = Rock.Security.Encryption.DecryptString(hfCertificate.Value)
                           .Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(v => Convert.FromBase64String(v))
                           .ToList();

            var pkcs12 = AcmeHelper.GetPkcs12Certificate(tbCertificatePassword.Text,
                                                         certData.First(), certData.Skip(1).ToList());

            //
            // Store the password protected PKCS12 data as a binary file.
            //
            var rockContext      = new RockContext();
            var outputBinaryFile = new BinaryFile
            {
                IsTemporary      = true,
                ContentStream    = new System.IO.MemoryStream(pkcs12),
                FileName         = "Certfificate.p12",
                MimeType         = "application/x-pkcs12",
                BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid()).Id
            };

            new BinaryFileService(rockContext).Add(outputBinaryFile);

            rockContext.SaveChanges();

            //
            // Present a download link to the user.
            //
            pnlDownloadCertificate.Visible    = false;
            nbRenewStatus.Text                = string.Format("Your <a href='/GetFile.ashx?guid={0}'>certificate</a> is ready for download.", outputBinaryFile.Guid);
            nbRenewStatus.NotificationBoxType = NotificationBoxType.Success;
        }
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="mergeTemplate">The merge template.</param>
        /// <param name="mergeObjectList">The merge object list.</param>
        /// <param name="globalMergeFields">The global merge fields.</param>
        /// <returns></returns>
        public override BinaryFile CreateDocument(MergeTemplate mergeTemplate, List <object> mergeObjectList, Dictionary <string, object> globalMergeFields)
        {
            this.Exceptions = new List <Exception>();
            BinaryFile outputBinaryFile = null;

            var rockContext       = new RockContext();
            var binaryFileService = new BinaryFileService(rockContext);

            var templateBinaryFile = binaryFileService.Get(mergeTemplate.TemplateBinaryFileId);

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

            string       templateHtml     = templateBinaryFile.ContentsToString();
            var          htmlMergeObjects = GetHtmlMergeObjects(mergeObjectList, globalMergeFields);
            string       outputHtml       = templateHtml.ResolveMergeFields(htmlMergeObjects);
            HtmlDocument outputDoc        = new HtmlDocument();

            outputDoc.LoadHtml(outputHtml);
            var outputStream = new MemoryStream();

            outputDoc.Save(outputStream);

            outputBinaryFile                  = new BinaryFile();
            outputBinaryFile.IsTemporary      = true;
            outputBinaryFile.ContentStream    = outputStream;
            outputBinaryFile.FileName         = "MergeTemplateOutput" + Path.GetExtension(templateBinaryFile.FileName);
            outputBinaryFile.MimeType         = templateBinaryFile.MimeType;
            outputBinaryFile.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid()).Id;

            binaryFileService.Add(outputBinaryFile);
            rockContext.SaveChanges();

            return(outputBinaryFile);
        }
Example #56
0
        /// <summary>
        /// Creates the document.
        /// </summary>
        /// <param name="mergeTemplate">The merge template.</param>
        /// <param name="mergeObjectList">The merge object list.</param>
        /// <param name="globalMergeFields">The global merge fields.</param>
        /// <returns></returns>
        public override BinaryFile CreateDocument( MergeTemplate mergeTemplate, List<object> mergeObjectList, Dictionary<string, object> globalMergeFields )
        {
            this.Exceptions = new List<Exception>();
            BinaryFile outputBinaryFile = null;

            var rockContext = new RockContext();
            var binaryFileService = new BinaryFileService( rockContext );

            var templateBinaryFile = binaryFileService.Get( mergeTemplate.TemplateBinaryFileId );
            if ( templateBinaryFile == null )
            {
                return null;
            }

            string templateHtml = templateBinaryFile.ContentsToString();
            var htmlMergeObjects = GetHtmlMergeObjects( mergeObjectList, globalMergeFields );
            string outputHtml = templateHtml.ResolveMergeFields( htmlMergeObjects );
            HtmlDocument outputDoc = new HtmlDocument();
            outputDoc.LoadHtml( outputHtml );
            var outputStream = new MemoryStream();
            outputDoc.Save( outputStream );

            outputBinaryFile = new BinaryFile();
            outputBinaryFile.IsTemporary = true;
            outputBinaryFile.ContentStream = outputStream;
            outputBinaryFile.FileName = "MergeTemplateOutput" + Path.GetExtension( templateBinaryFile.FileName );
            outputBinaryFile.MimeType = templateBinaryFile.MimeType;
            outputBinaryFile.BinaryFileTypeId = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.DEFAULT.AsGuid() ).Id;

            binaryFileService.Add( outputBinaryFile );
            rockContext.SaveChanges();

            return outputBinaryFile;
        }
        /// <summary>
        /// Ends the get.
        /// </summary>
        /// <param name="asyncResult">The asynchronous result.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public BinaryFile EndGet( IAsyncResult asyncResult, HttpContext context )
        {
            // restore the command from the context
            SqlCommand cmd = (SqlCommand)context.Items["cmd"];

            using ( SqlDataReader reader = cmd.EndExecuteReader( asyncResult ) )
            {
                BinaryFile binaryFile = new BinaryFile();

                // Columns must be read in Sequential Order (see stored procedure spBinaryFileGet)
                reader.Read();
                binaryFile.Id = reader["Id"] as int? ?? 0;
                binaryFile.IsTemporary = ( reader["IsTemporary"] as int? ) == 1;
                binaryFile.IsSystem = ( reader["IsSystem"] as int? ) == 1;
                binaryFile.BinaryFileTypeId = reader["BinaryFileTypeId"] as int?;
                binaryFile.Url = reader["Url"] as string;
                binaryFile.FileName = reader["FileName"] as string;
                binaryFile.MimeType = reader["MimeType"] as string;
                binaryFile.LastModifiedDateTime = reader["LastModifiedDateTime"] as DateTime?;
                binaryFile.Description = reader["Description"] as string;
                int? storageEntityTypeId = reader["StorageEntityTypeId"] as int?;
                binaryFile.SetStorageEntityTypeId( storageEntityTypeId );
                var guid = reader["Guid"];
                if ( guid is Guid )
                {
                    binaryFile.Guid = (Guid)guid;
                }

                string entityTypeName = reader["StorageEntityTypeName"] as string;

                binaryFile.Data = new BinaryFileData();

                // read the fileContent from the database just in case it's stored in the database, otherwise, the Provider will get it
                var content = reader["Content"];
                if ( content != null )
                {
                    binaryFile.Data.Content = content as byte[];
                }

                Rock.Storage.ProviderComponent provider = Rock.Storage.ProviderContainer.GetComponent( entityTypeName );

                binaryFile.Data.Content = provider.GetFileContent( binaryFile, context );

                return binaryFile;
            }
        }
        /// <summary>
        /// Determines the storage provider that was used the last time the file was saved
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        private Storage.ProviderComponent DetermineBinaryFileStorageProvider( BinaryFile item )
        {
            Rock.Storage.ProviderComponent storageProvider = null;

            if ( item != null )
            {
                item.StorageEntityType = item.StorageEntityType ?? new EntityTypeService( this.RockContext ).Get( item.StorageEntityTypeId ?? 0 );
                if ( item.StorageEntityType != null )
                {
                    storageProvider = Rock.Storage.ProviderContainer.GetComponent( item.StorageEntityType.Name );
                }
            }

            return storageProvider;
        }
        /// <summary>
        /// Deletes the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="personId">The person identifier.</param>
        /// <returns></returns>
        public override bool Delete( BinaryFile item, int? personId )
        {
            // if we can determine the StorageProvider, use the provider to remove the file from the provider's external storage medium
            Rock.Storage.ProviderComponent storageProvider = DetermineBinaryFileStorageProvider( item );

            if ( storageProvider != null )
            {
                storageProvider.RemoveFile( item, HttpContext.Current );
            }

            // delete the record from the database
            return base.Delete( item, personId );
        }
Example #60
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;
        }