Пример #1
0
        /// <summary>
        /// Adds the file from stream. This method will save the current context.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="mimeType">Type of the MIME.</param>
        /// <param name="contentLength">Length of the content.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="binaryFileTypeGuid">The binary file type unique identifier.</param>
        /// <param name="imageGuid">The image unique identifier.</param>
        /// <returns></returns>
        public BinaryFile AddFileFromStream(Stream stream, string mimeType, long contentLength, string fileName, string binaryFileTypeGuid, Guid?imageGuid)
        {
            int?binaryFileTypeId = Rock.Web.Cache.BinaryFileTypeCache.GetId(binaryFileTypeGuid.AsGuid());

            imageGuid = imageGuid == null || imageGuid == Guid.Empty ? Guid.NewGuid() : imageGuid;
            var rockContext = ( RockContext )this.Context;

            using (var memoryStream = new System.IO.MemoryStream())
            {
                stream.CopyTo(memoryStream);
                var binaryFile = new BinaryFile
                {
                    IsTemporary      = false,
                    BinaryFileTypeId = binaryFileTypeId,
                    MimeType         = mimeType,
                    FileName         = fileName,
                    FileSize         = contentLength,
                    ContentStream    = memoryStream,
                    Guid             = imageGuid.Value
                };

                var binaryFileService = new BinaryFileService(rockContext);
                binaryFileService.Add(binaryFile);
                rockContext.SaveChanges();
                return(binaryFile);
            }
        }
Пример #2
0
        /// <summary>
        /// Updates the document status.
        /// </summary>
        /// <param name="signatureDocument">The signature document.</param>
        /// <param name="tempFolderPath">The temporary folder path.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool UpdateDocumentStatus(SignatureDocument signatureDocument, string tempFolderPath, out List <string> errorMessages)
        {
            errorMessages = new List <string>();
            if (signatureDocument == null)
            {
                errorMessages.Add("Invalid Document.");
            }

            if (signatureDocument.SignatureDocumentTemplate == null)
            {
                errorMessages.Add("Document has an invalid document type.");
            }

            if (!errorMessages.Any())
            {
                var provider = DigitalSignatureContainer.GetComponent(signatureDocument.SignatureDocumentTemplate.ProviderEntityType.Name);
                if (provider == null || !provider.IsActive)
                {
                    errorMessages.Add("Digital Signature provider was not found or is not active.");
                }
                else
                {
                    var originalStatus = signatureDocument.Status;
                    if (provider.UpdateDocumentStatus(signatureDocument, out errorMessages))
                    {
                        if (signatureDocument.Status == SignatureDocumentStatus.Signed && !signatureDocument.BinaryFileId.HasValue)
                        {
                            using (var rockContext = new RockContext())
                            {
                                string documentPath = provider.GetDocument(signatureDocument, tempFolderPath, out errorMessages);
                                if (!string.IsNullOrWhiteSpace(documentPath))
                                {
                                    var        binaryFileService = new BinaryFileService(rockContext);
                                    BinaryFile binaryFile        = new BinaryFile();
                                    binaryFile.Guid             = Guid.NewGuid();
                                    binaryFile.IsTemporary      = false;
                                    binaryFile.BinaryFileTypeId = signatureDocument.SignatureDocumentTemplate.BinaryFileTypeId;
                                    binaryFile.MimeType         = "application/pdf";
                                    binaryFile.FileName         = new FileInfo(documentPath).Name;
                                    binaryFile.ContentStream    = new FileStream(documentPath, FileMode.Open);
                                    binaryFileService.Add(binaryFile);
                                    rockContext.SaveChanges();

                                    signatureDocument.BinaryFileId = binaryFile.Id;

                                    File.Delete(documentPath);
                                }
                            }
                        }

                        if (signatureDocument.Status != originalStatus)
                        {
                            signatureDocument.LastStatusDate = RockDateTime.Now;
                        }
                    }
                }
            }

            return(!errorMessages.Any());
        }
Пример #3
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            BinaryFile binaryFile;
            var rockContext = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );

            int? prevBinaryFileTypeId = null;

            int binaryFileId = int.Parse( hfBinaryFileId.Value );

            if ( binaryFileId == 0 )
            {
                binaryFile = new BinaryFile();
                binaryFileService.Add( binaryFile );
            }
            else
            {
                binaryFile = binaryFileService.Get( binaryFileId );
                prevBinaryFileTypeId = binaryFile != null ? binaryFile.BinaryFileTypeId : (int?)null;
            }

            // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles)
            if ( fsFile.BinaryFileId != binaryFile.Id)
            {
                var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0);
                if (uploadedBinaryFile != null)
                {
                    binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId;
                    binaryFile.ContentStream = uploadedBinaryFile.ContentStream;
                }
            }

            binaryFile.IsTemporary = false;
            binaryFile.FileName = tbName.Text;
            binaryFile.Description = tbDescription.Text;
            binaryFile.MimeType = tbMimeType.Text;
            binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();

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

            if ( !Page.IsValid )
            {
                return;
            }

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

            rockContext.WrapTransaction( () =>
            {
                foreach ( var id in OrphanedBinaryFileIdList )
                {
                    var tempBinaryFile = binaryFileService.Get( id );
                    if ( tempBinaryFile != null && tempBinaryFile.IsTemporary )
                    {
                        binaryFileService.Delete( tempBinaryFile );
                    }
                }

                rockContext.SaveChanges();
                binaryFile.SaveAttributeValues( rockContext );

            } );

            Rock.CheckIn.KioskLabel.Flush( binaryFile.Guid );

            if ( !prevBinaryFileTypeId.Equals( binaryFile.BinaryFileTypeId ) )
            {
                var checkInBinaryFileType = new BinaryFileTypeService( rockContext )
                    .Get( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid() );
                if ( checkInBinaryFileType != null && (
                    ( prevBinaryFileTypeId.HasValue && prevBinaryFileTypeId.Value == checkInBinaryFileType.Id )  ||
                    ( binaryFile.BinaryFileTypeId.HasValue && binaryFile.BinaryFileTypeId.Value == checkInBinaryFileType.Id ) ) )
                {
                    Rock.CheckIn.KioskDevice.FlushAll();
                }
            }

            NavigateToParentPage();
        }
        /// <summary>
        /// Processes the binary file.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uploadedFile">The uploaded file.</param>
        private void ProcessBinaryFile( HttpContext context, HttpPostedFile uploadedFile )
        {
            // get BinaryFileType info
            Guid fileTypeGuid = context.Request.QueryString["fileTypeGuid"].AsGuid();

            RockContext rockContext = new RockContext();
            BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid );

            // 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.MimeType = uploadedFile.ContentType;
            binaryFile.FileName = Path.GetFileName( uploadedFile.FileName );
            binaryFile.Data = new BinaryFileData();
            binaryFile.Data.Content = GetFileBytes( context, uploadedFile );

            var binaryFileService = new BinaryFileService( rockContext );
            binaryFileService.Add( binaryFile );

            rockContext.SaveChanges();

            var response = new
            {
                Id = binaryFile.Id,
                FileName = binaryFile.FileName
            };

            context.Response.Write( response.ToJson() );
        }
        /// <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 )
        {
            BinaryFile binaryFile;
            var rockContext = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );

            int binaryFileId = int.Parse( hfBinaryFileId.Value );

            if ( binaryFileId == 0 )
            {
                binaryFile = new BinaryFile();
                binaryFileService.Add( binaryFile );
            }
            else
            {
                binaryFile = binaryFileService.Get( binaryFileId );
            }

            // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles)
            if ( fsFile.BinaryFileId != binaryFile.Id)
            {
                var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0);
                if (uploadedBinaryFile != null)
                {
                    binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId;
                    binaryFile.ContentStream = uploadedBinaryFile.ContentStream;
                }
            }

            binaryFile.IsTemporary = false;
            binaryFile.FileName = tbName.Text;
            binaryFile.Description = tbDescription.Text;
            binaryFile.MimeType = tbMimeType.Text;
            binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();

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

            if ( !Page.IsValid )
            {
                return;
            }

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

            rockContext.WrapTransaction( () =>
            {
                foreach ( var id in OrphanedBinaryFileIdList )
                {
                    var tempBinaryFile = binaryFileService.Get( id );
                    if ( tempBinaryFile != null && tempBinaryFile.IsTemporary )
                    {
                        binaryFileService.Delete( tempBinaryFile );
                    }
                }

                rockContext.SaveChanges();
                binaryFile.SaveAttributeValues( rockContext );
            } );

            NavigateToParentPage();
        }
Пример #6
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;
            }
        }
Пример #7
0
        /// <summary>
        /// Handles the SaveClick event of the _mdImageDialog 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 _mdImageDialog_SaveClick( object sender, EventArgs e )
        {
            try
            {
                var rockContext = new RockContext();
                BinaryFileService binaryFileService = new BinaryFileService(rockContext);

                // load image from database
                var binaryFile = binaryFileService.Get( CropBinaryFileId ?? 0 );
                if ( binaryFile != null )
                {
                    byte[] croppedImage = CropImage( binaryFile.Data.Content, binaryFile.MimeType );

                    BinaryFile croppedBinaryFile = new BinaryFile();
                    croppedBinaryFile.IsTemporary = true;
                    croppedBinaryFile.BinaryFileTypeId = binaryFile.BinaryFileTypeId;
                    croppedBinaryFile.MimeType = binaryFile.MimeType;
                    croppedBinaryFile.FileName = binaryFile.FileName;
                    croppedBinaryFile.Description = binaryFile.Description;
                    croppedBinaryFile.Data = new BinaryFileData();
                    croppedBinaryFile.Data.Content = croppedImage;

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

                    this.BinaryFileId = croppedBinaryFile.Id;
                }

                // Raise the FileSaved event if one is defined by another control.
                if ( FileSaved != null )
                {
                    FileSaved( this, e );
                }

                _mdImageDialog.Hide();
            }
            catch ( ImageResizer.Plugins.Basic.SizeLimits.SizeLimitException )
            {
                // shouldn't happen because we resize it below the limit in CropImage(), but just in case
                var sizeLimits = new ImageResizer.Plugins.Basic.SizeLimits();
                _nbImageWarning.Visible = true;
                _nbImageWarning.Text = string.Format( "The image size exceeds the maximum resolution of {0}x{1}. Press cancel and try selecting a smaller image.", sizeLimits.TotalSize.Width, sizeLimits.TotalSize.Height );
                _mdImageDialog.Show();
            }
        }
        public HttpResponseMessage Upload( int binaryFileTypeId )
        {
            try
            {
                var rockContext = new RockContext();
                var context = HttpContext.Current;
                var files = context.Request.Files;
                var uploadedFile = files.AllKeys.Select( fk => files[fk] ).FirstOrDefault();
                var binaryFileType = new BinaryFileTypeService( rockContext ).Get( binaryFileTypeId );

                if ( uploadedFile == null )
                {
                    GenerateResponse( HttpStatusCode.BadRequest, "No file was sent" );
                }

                if ( binaryFileType == null )
                {
                    GenerateResponse( HttpStatusCode.InternalServerError, "Invalid binary file type" );
                }

                if ( !binaryFileType.IsAuthorized( Rock.Security.Authorization.EDIT, GetPerson() ) )
                {
                    GenerateResponse( HttpStatusCode.Unauthorized, "Not authorized to upload this type of file" );
                }

                var binaryFileService = new BinaryFileService( rockContext );
                var binaryFile = new BinaryFile();
                binaryFileService.Add( binaryFile );

                binaryFile.IsTemporary = false;
                binaryFile.BinaryFileTypeId = binaryFileType.Id;
                binaryFile.MimeType = uploadedFile.ContentType;
                binaryFile.FileName = Path.GetFileName( uploadedFile.FileName );
                binaryFile.ContentStream = FileUtilities.GetFileContentStream( uploadedFile );

                rockContext.SaveChanges();

                return new HttpResponseMessage( HttpStatusCode.Created )
                {
                    Content = new StringContent( binaryFile.Id.ToString() )
                };
            }
            catch ( HttpResponseException exception )
            {
                return exception.Response;
            }
            catch
            {
                return new HttpResponseMessage( HttpStatusCode.InternalServerError )
                {
                    Content = new StringContent( "Unhandled exception" )
                };
            }
        }
Пример #9
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;
        }
Пример #10
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute( IJobExecutionContext context )
        {
            // Get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            int maxQueries = Int32.Parse( dataMap.GetString( "MaxQueriesperRun" ) );
            int size = Int32.Parse( dataMap.GetString( "ImageSize" ) );

            // Find people with no photo
            var rockContext = new RockContext();
            PersonService personService = new PersonService( rockContext );
            var people = personService.Queryable()
                .Where( p => p.PhotoId == null )
                .Take( maxQueries )
                .ToList();
            foreach ( var person in people )
            {
                if ( !string.IsNullOrEmpty( person.Email ) )
                {
                    // Build MD5 hash for email
                    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                    byte[] encodedEmail = new UTF8Encoding().GetBytes( person.Email.ToLower().Trim() );
                    byte[] hashedBytes = md5.ComputeHash( encodedEmail );
                    StringBuilder sb = new StringBuilder( hashedBytes.Length * 2 );
                    for ( int i = 0; i < hashedBytes.Length; i++ )
                    {
                        sb.Append( hashedBytes[i].ToString( "X2" ) );
                    }
                    string hash = sb.ToString().ToLower();
                    // Query Gravatar's https endpoint asking for a 404 on no match
                    var restClient = new RestClient( string.Format( "https://secure.gravatar.com/avatar/{0}.jpg?default=404&size={1}", hash, size ) );
                    var request = new RestRequest( Method.GET );
                    var response = restClient.Execute( request );
                    if ( response.StatusCode == HttpStatusCode.OK )
                    {
                        var bytes = response.RawBytes;
                        // Create and save the image
                        BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                        if ( fileType != null )
                        {

                            var binaryFileService = new BinaryFileService( rockContext );
                            var binaryFile = new BinaryFile();
                            binaryFileService.Add( binaryFile );
                            binaryFile.IsTemporary = false;
                            binaryFile.BinaryFileType = fileType;
                            binaryFile.MimeType = "image/jpeg";
                            binaryFile.FileName = person.NickName + person.LastName + ".jpg";
                            binaryFile.ContentStream = new MemoryStream( bytes );

                            person.PhotoId = binaryFile.Id;
                            rockContext.SaveChanges();
                        }
                    }
                    RestClient profileClient = new RestClient( "http://www.gravatar.com/" );
                    var profileRequest = new RestRequest( Method.GET );
                    profileRequest.RequestFormat = DataFormat.Json;
                    profileRequest.Resource = hash + ".json";
                    var profileResponse = profileClient.Execute( profileRequest );
                    if ( profileResponse.StatusCode == HttpStatusCode.OK )
                    {
                        JObject gravatarProfile = JObject.Parse( profileResponse.Content );

                        string gravatarFirstName = gravatarProfile["entry"][0]["name"]["givenName"].ToStringSafe();
                        if ( string.IsNullOrEmpty( person.FirstName ) && !string.IsNullOrEmpty( gravatarFirstName ) )
                        {
                            person.FirstName = gravatarFirstName;
                        }
                        string gravatarLastName = gravatarProfile["entry"][0]["name"]["familyName"].ToStringSafe();
                        if ( string.IsNullOrEmpty( person.LastName ) && !string.IsNullOrEmpty( gravatarLastName ) )
                        {
                            person.LastName = gravatarLastName;
                        }

                        var twitterAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_TWITTER.AsGuid() );
                        if ( twitterAttribute != null )
                        {
                            person.LoadAttributes( rockContext );
                            if ( string.IsNullOrEmpty( person.GetAttributeValue( twitterAttribute.Key ) ) )
                            {
                                var gravatarTwitterAccount = gravatarProfile["entry"][0]["accounts"].Children()
                            .Where( a => a["shortname"].ToStringSafe() == "twitter" )
                            .FirstOrDefault();
                                if ( gravatarTwitterAccount["verified"].ToString().AsBoolean() )
                                {
                                    string twitterLink = gravatarTwitterAccount["url"].ToStringSafe();
                                    if ( twitterLink != null )
                                    {
                                        person.SetAttributeValue( twitterAttribute.Key, twitterLink );
                                    }
                                }
                            }
                        }

                        var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() );
                        if ( facebookAttribute != null )
                        {
                            person.LoadAttributes( rockContext );
                            if ( string.IsNullOrEmpty( person.GetAttributeValue( facebookAttribute.Key ) ) )
                            {
                                var gravatarFacebookAccount = gravatarProfile["entry"][0]["accounts"].Children()
                            .Where( a => a["shortname"].ToStringSafe() == "facebook" )
                            .FirstOrDefault();
                                if ( gravatarFacebookAccount["verified"].ToString().AsBoolean() )
                                {
                                    string facebookLink = gravatarFacebookAccount["url"].ToStringSafe();
                                    if ( facebookLink != null )
                                    {
                                        person.SetAttributeValue( facebookAttribute.Key, facebookLink );
                                    }
                                }
                            }
                        }

                        person.SaveAttributeValues( rockContext );
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Gets the name of the Twitter user.
        /// </summary>
        /// <param name="twitterUser">The Twitter user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetTwitterUser( dynamic twitterUser, string accessToken = "" )
        {
            string username = string.Empty;
            string twitterId = twitterUser.id_str;
            string twitterLink = "https://twitter.com/" + twitterUser.screen_name;

            string userName = "******" + twitterId;
            UserLogin user = null;

            using ( var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService( rockContext );
                user = userLoginService.GetByUserName( userName );

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                {
                    // Get name and email from twitterUser object and then split the name
                    string fullName = twitterUser.name;
                    string firstName = null;
                    string lastName = null;
                    var personService = new PersonService( rockContext );
                    personService.SplitName( fullName, out firstName, out lastName );
                    string email = string.Empty;
                    try { email = twitterUser.email; }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace( email ) )
                    {
                        var people = personService.GetByMatch( firstName, lastName, email );
                        if ( people.Count() == 1 )
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;

                    rockContext.WrapTransaction( () =>
                    {
                        // If not an existing person, create a new one
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            person.Gender = Gender.Unknown;
                            if ( person != null )
                            {
                                PersonService.SaveNewPerson( person, rockContext, null, false );
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id;
                            user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "Twitter", true );
                        }

                    } );
                }

                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService( rockContext );
                        var person = personService.Get( user.PersonId.Value );
                        if ( person != null )
                        {
                            string twitterImageUrl = twitterUser.profile_image_url;
                            bool twitterImageDefault = twitterUser.default_profile_image;
                            twitterImageUrl = twitterImageUrl.Replace( "_normal", "" );
                            // If person does not have a photo, use their Twitter photo if it exists
                            if ( !person.PhotoId.HasValue && !twitterImageDefault && !string.IsNullOrWhiteSpace( twitterImageUrl ) )
                            {
                                // Download the photo from the url provided
                                var restClient = new RestClient( twitterImageUrl );
                                var restRequest = new RestRequest( Method.GET );
                                var restResponse = restClient.Execute( restRequest );
                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    var bytes = restResponse.RawBytes;

                                    // Create and save the image
                                    BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                    if ( fileType != null )
                                    {
                                        var binaryFileService = new BinaryFileService( rockContext );
                                        var binaryFile = new BinaryFile();
                                        binaryFileService.Add( binaryFile );
                                        binaryFile.IsTemporary = false;
                                        binaryFile.BinaryFileType = fileType;
                                        binaryFile.MimeType = "image/jpeg";
                                        binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg";
                                        binaryFile.ContentStream = new MemoryStream( bytes );

                                        rockContext.SaveChanges();

                                        person.PhotoId = binaryFile.Id;
                                        rockContext.SaveChanges();
                                    }
                                }
                            }

                            // Save the Twitter social media link
                            var twitterAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_TWITTER.AsGuid() );
                            if ( twitterAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( twitterAttribute.Key, twitterLink );
                                person.SaveAttributeValues( rockContext );
                            }
                        }

                    }
                }

                return username;
            }
        }
Пример #12
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;
            }

            var sourceTemplateStream = templateBinaryFile.ContentStream;

            // Start by creating a new document with the contents of the Template (so that Styles, etc get included)
            using ( MemoryStream outputDocStream = new MemoryStream() )
            {
                sourceTemplateStream.CopyTo( outputDocStream );
                outputDocStream.Seek( 0, SeekOrigin.Begin );

                // now that we have the outputdoc started, simplify the sourceTemplate
                var simplifiedDoc = WordprocessingDocument.Open( sourceTemplateStream, true );
                MarkupSimplifier.SimplifyMarkup( simplifiedDoc, this.simplifyMarkupSettingsAll );

                //// simplify any nodes that have Lava in it that might not have been caught by the MarkupSimplifier
                //// MarkupSimplifier only merges superfluous runs that are children of a paragraph
                var simplifiedDocX = simplifiedDoc.MainDocumentPart.GetXDocument();
                OpenXmlRegex.Match(
                                simplifiedDocX.Elements(),
                                this.lavaRegEx,
                                ( x, m ) =>
                                {
                                    foreach ( var nonParagraphRunsParent in x.DescendantNodes().OfType<XElement>().Where( a => a.Parent != null && a.Name != null )
                                .Where( a => ( a.Name.LocalName == "r" ) ).Select( a => a.Parent ).Distinct().ToList() )
                                    {
                                        if ( lavaRegEx.IsMatch( nonParagraphRunsParent.Value ) )
                                        {
                                            var tempParent = XElement.Parse( new Paragraph().OuterXml );
                                            tempParent.Add( nonParagraphRunsParent.Nodes() );
                                            tempParent = MarkupSimplifier.MergeAdjacentSuperfluousRuns( tempParent );
                                            nonParagraphRunsParent.ReplaceNodes( tempParent.Nodes() );
                                        }
                                    }
                                } );

                XElement lastLavaNode = simplifiedDocX.DescendantNodes().OfType<XElement>().LastOrDefault( a => lavaRegEx.IsMatch( a.Value ) );

                // ensure there is a { Next } indicator after the last lava node in the template
                if (lastLavaNode != null)
                {
                    var nextRecordMatch = nextRecordRegEx.Match( lastLavaNode.Value );
                    if ( nextRecordMatch == null || !nextRecordMatch.Success )
                    {
                        // if the last lava node doesn't have a { next }, append to the end
                        lastLavaNode.Value += " {% next %} ";
                    }
                    else
                    {
                        if ( !lastLavaNode.Value.EndsWith( nextRecordMatch.Value ) )
                        {
                            // if the last lava node does have a { next }, but there is stuff after it, add it (just in case)
                            lastLavaNode.Value += " {% next %} ";
                        }
                    }
                }

                simplifiedDoc.MainDocumentPart.PutXDocument();

                sourceTemplateStream.Seek( 0, SeekOrigin.Begin );

                bool? allSameParent = null;

                using ( WordprocessingDocument outputDoc = WordprocessingDocument.Open( outputDocStream, true ) )
                {
                    var xdoc = outputDoc.MainDocumentPart.GetXDocument();
                    var outputBodyNode = xdoc.DescendantNodes().OfType<XElement>().FirstOrDefault( a => a.Name.LocalName.Equals( "body" ) );
                    outputBodyNode.RemoveNodes();

                    int recordIndex = 0;
                    int? lastRecordIndex = null;
                    int recordCount = mergeObjectList.Count();
                    while ( recordIndex < recordCount )
                    {
                        if ( lastRecordIndex.HasValue && lastRecordIndex == recordIndex )
                        {
                            // something went wrong, so throw to avoid spinning infinately
                            throw new Exception( "Unexpected unchanged recordIndex" );
                        }

                        lastRecordIndex = recordIndex;
                        using ( var tempMergeTemplateStream = new MemoryStream() )
                        {
                            sourceTemplateStream.Position = 0;
                            sourceTemplateStream.CopyTo( tempMergeTemplateStream );
                            tempMergeTemplateStream.Position = 0;
                            var tempMergeWordDoc = WordprocessingDocument.Open( tempMergeTemplateStream, true );
                            var tempMergeTemplateX = tempMergeWordDoc.MainDocumentPart.GetXDocument();
                            var tempMergeTemplateBodyNode = tempMergeTemplateX.DescendantNodes().OfType<XElement>().FirstOrDefault( a => a.Name.LocalName.Equals( "body" ) );

                            // find all the Nodes that have a {% next %}.
                            List<XElement> nextIndicatorNodes = new List<XElement>();

                            OpenXmlRegex.Match(
                                tempMergeTemplateX.Elements(),
                                this.nextRecordRegEx,
                                ( x, m ) =>
                                {
                                    nextIndicatorNodes.Add( x );
                                } );

                            allSameParent = allSameParent ?? nextIndicatorNodes.Count > 1 && nextIndicatorNodes.Select( a => a.Parent ).Distinct().Count() == 1;

                            List<XContainer> recordContainerNodes = new List<XContainer>();

                            foreach ( var nextIndicatorNodeParent in nextIndicatorNodes.Select( a => a.Parent ).Where( a => a != null ) )
                            {
                                XContainer recordContainerNode = nextIndicatorNodeParent;
                                if ( !allSameParent.Value )
                                {
                                    // go up the parent nodes until we have more than one "Next" descendent so that we know what to consider our record container
                                    while ( recordContainerNode.Parent != null )
                                    {
                                        if ( this.nextRecordRegEx.Matches( recordContainerNode.Parent.Value ).Count == 1 )
                                        {
                                            // still just the one "next" indicator, so go out another parent
                                            recordContainerNode = recordContainerNode.Parent;
                                        }
                                        else
                                        {
                                            // we went too far up the parents and found multiple "next" children, so use this node as the recordContainerNode
                                            break;
                                        }
                                    }
                                }

                                if ( !recordContainerNodes.Contains( recordContainerNode ) )
                                {
                                    recordContainerNodes.Add( recordContainerNode );
                                }
                            }

                            foreach ( var recordContainerNode in recordContainerNodes )
                            {
                                //// loop thru each of the recordContainerNodes
                                //// If we have more records than nodes, we'll jump out to the outer "while" and append another template and keep going

                                XContainer mergedXRecord;

                                var recordContainerNodeXml = recordContainerNode.ToString( SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces ).ReplaceWordChars();

                                if ( recordIndex >= recordCount )
                                {
                                    // out of records, so clear out any remaining template nodes that haven't been merged
                                    string xml = recordContainerNodeXml;
                                    mergedXRecord = XElement.Parse( xml ) as XContainer;
                                    OpenXmlRegex.Replace( mergedXRecord.Nodes().OfType<XElement>(), this.regExDot, string.Empty, ( a, b ) => { return true; } );

                                    recordIndex++;
                                }
                                else
                                {
                                    //// just in case they have shared parent node, or if there is trailing {{ next }} after the last lava
                                    //// on the page, split the XML for each record and reassemble it when done
                                    List<string> xmlChunks = this.nextRecordRegEx.Split( recordContainerNodeXml ).ToList();

                                    string mergedXml = string.Empty;

                                    foreach ( var xml in xmlChunks )
                                    {
                                        if ( xml.HasMergeFields() )
                                        {
                                            if ( recordIndex < recordCount )
                                            {
                                                try
                                                {
                                                    DotLiquid.Hash wordMergeObjects = new DotLiquid.Hash();
                                                    wordMergeObjects.Add( "Row", mergeObjectList[recordIndex] );

                                                    foreach ( var field in globalMergeFields )
                                                    {
                                                        wordMergeObjects.Add( field.Key, field.Value );
                                                    }

                                                    mergedXml += xml.ResolveMergeFields( wordMergeObjects, true, true );
                                                }
                                                catch ( Exception ex )
                                                {
                                                    // if ResolveMergeFields failed, log the exception, then just return the orig xml
                                                    this.Exceptions.Add( ex );
                                                    mergedXml += xml;
                                                }

                                                recordIndex++;
                                            }
                                            else
                                            {
                                                // out of records, so just keep it as the templated xml
                                                mergedXml += xml;
                                            }
                                        }
                                        else
                                        {
                                            mergedXml += xml;
                                        }
                                    }

                                    mergedXRecord = XElement.Parse( mergedXml ) as XContainer;
                                }

                                // remove the orig nodes and replace with merged nodes
                                recordContainerNode.RemoveNodes();
                                recordContainerNode.Add( mergedXRecord.Nodes().OfType<XElement>() );

                                var mergedRecordContainer = XElement.Parse( recordContainerNode.ToString( SaveOptions.DisableFormatting ) );
                                if ( recordContainerNode.Parent != null )
                                {
                                    // the recordContainerNode is some child/descendent of <body>
                                    recordContainerNode.ReplaceWith( mergedRecordContainer );
                                }
                                else
                                {
                                    // the recordContainerNode is the <body>
                                    recordContainerNode.RemoveNodes();
                                    recordContainerNode.Add( mergedRecordContainer.Nodes() );

                                    if ( recordIndex < recordCount )
                                    {
                                        // add page break
                                        var pageBreakXml = new Paragraph( new Run( new Break() { Type = BreakValues.Page } ) ).OuterXml;
                                        var pageBreak = XElement.Parse( pageBreakXml, LoadOptions.None );
                                        var lastParagraph = recordContainerNode.Nodes().OfType<XElement>().Where( a => a.Name.LocalName == "p" ).LastOrDefault();
                                        if ( lastParagraph != null )
                                        {
                                            lastParagraph.AddAfterSelf( pageBreak );
                                        }
                                    }
                                }
                            }

                            outputBodyNode.Add( tempMergeTemplateBodyNode.Nodes() );
                        }
                    }

                    // remove all the 'next' delimiters
                    OpenXmlRegex.Replace( outputBodyNode.Nodes().OfType<XElement>(), this.nextRecordRegEx, string.Empty, ( xx, mm ) => { return true; } );

                    // remove all but the last SectionProperties element (there should only be one per section (body))
                    var sectPrItems = outputBodyNode.Nodes().OfType<XElement>().Where( a => a.Name.LocalName == "sectPr" );
                    foreach ( var extra in sectPrItems.Where( a => a != sectPrItems.Last() ).ToList() )
                    {
                        extra.Remove();
                    }

                    // renumber all the ids to make sure they are unique
                    var idAttrs = xdoc.DescendantNodes().OfType<XElement>().Where( a => a.HasAttributes ).Select( a => a.Attribute( "id" ) ).Where( s => s != null );
                    int lastId = 1;
                    foreach ( var attr in idAttrs )
                    {
                        attr.Value = lastId.ToString();
                        lastId++;
                    }

                    // remove the last pagebreak
                    MarkupSimplifier.SimplifyMarkup( outputDoc, new SimplifyMarkupSettings { RemoveLastRenderedPageBreak = true } );

                    // If you want to see validation errors
                    /*
                    var validator = new OpenXmlValidator();
                    var errors = validator.Validate( outputDoc ).ToList();
                    */
                }

                outputBinaryFile = new BinaryFile();
                outputBinaryFile.IsTemporary = true;
                outputBinaryFile.ContentStream = outputDocStream;
                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;
        }
Пример #13
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            BinaryFile binaryFile;
            BinaryFileService binaryFileService = new BinaryFileService();
            AttributeService attributeService = new AttributeService();

            int binaryFileId = int.Parse( hfBinaryFileId.Value );

            if ( binaryFileId == 0 )
            {
                binaryFile = new BinaryFile();
                binaryFileService.Add( binaryFile, CurrentPersonId );
            }
            else
            {
                binaryFile = binaryFileService.Get( binaryFileId );
            }

            // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles)
            if ( fsFile.BinaryFileId != binaryFile.Id)
            {
                var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0);
                if (uploadedBinaryFile != null)
                {
                    binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId;
                    if ( uploadedBinaryFile.Data != null )
                    {
                        binaryFile.Data = binaryFile.Data ?? new BinaryFileData();
                        binaryFile.Data.Content = uploadedBinaryFile.Data.Content;
                    }
                }
            }

            binaryFile.IsTemporary = false;
            binaryFile.FileName = tbName.Text;
            binaryFile.Description = tbDescription.Text;
            binaryFile.MimeType = tbMimeType.Text;
            binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();

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

            if ( !Page.IsValid )
            {
                return;
            }

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

            RockTransactionScope.WrapTransaction( () =>
            {
                binaryFileService.Save( binaryFile, CurrentPersonId );
                Rock.Attribute.Helper.SaveAttributeValues( binaryFile, CurrentPersonId );
            } );

            NavigateToParentPage();
        }
        /// <summary>
        /// Updates the document status.
        /// </summary>
        /// <param name="signatureDocument">The signature document.</param>
        /// <param name="tempFolderPath">The temporary folder path.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool UpdateDocumentStatus( SignatureDocument signatureDocument, string tempFolderPath, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            if ( signatureDocument == null )
            {
                errorMessages.Add( "Invalid Document." );
            }

            if ( signatureDocument.SignatureDocumentTemplate == null )
            {
                errorMessages.Add( "Document has an invalid document type." );
            }

            if ( !errorMessages.Any() )
            {
                var provider = DigitalSignatureContainer.GetComponent( signatureDocument.SignatureDocumentTemplate.ProviderEntityType.Name );
                if ( provider == null || !provider.IsActive )
                {
                    errorMessages.Add( "Digital Signature provider was not found or is not active." );
                }
                else
                {
                    var originalStatus = signatureDocument.Status;
                    if ( provider.UpdateDocumentStatus( signatureDocument, out errorMessages ) )
                    {
                        if ( signatureDocument.Status == SignatureDocumentStatus.Signed && !signatureDocument.BinaryFileId.HasValue )
                        {
                            using ( var rockContext = new RockContext() )
                            {
                                string documentPath = provider.GetDocument( signatureDocument, tempFolderPath, out errorMessages );
                                if ( !string.IsNullOrWhiteSpace( documentPath ) )
                                {
                                    var binaryFileService = new BinaryFileService( rockContext );
                                    BinaryFile binaryFile = new BinaryFile();
                                    binaryFile.Guid = Guid.NewGuid();
                                    binaryFile.IsTemporary = false;
                                    binaryFile.BinaryFileTypeId = signatureDocument.SignatureDocumentTemplate.BinaryFileTypeId;
                                    binaryFile.MimeType = "application/pdf";
                                    binaryFile.FileName = new FileInfo( documentPath ).Name;
                                    binaryFile.ContentStream = new FileStream( documentPath, FileMode.Open );
                                    binaryFileService.Add( binaryFile );
                                    rockContext.SaveChanges();

                                    signatureDocument.BinaryFileId = binaryFile.Id;

                                    File.Delete( documentPath );
                                }
                            }
                        }

                        if ( signatureDocument.Status != originalStatus )
                        {
                            signatureDocument.LastStatusDate = RockDateTime.Now;
                        }

                    }

                }
            }

            return !errorMessages.Any();
        }
Пример #15
0
        private static Guid? SaveFile( AttributeCache binaryFileAttribute, string url, string fileName )
        {
            // get BinaryFileType info
            if ( binaryFileAttribute != null &&
                binaryFileAttribute.QualifierValues != null &&
                binaryFileAttribute.QualifierValues.ContainsKey( "binaryFileType" ) )
            {
                Guid? fileTypeGuid = binaryFileAttribute.QualifierValues["binaryFileType"].Value.AsGuidOrNull();
                if ( fileTypeGuid.HasValue )
                {
                    RockContext rockContext = new RockContext();
                    BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid.Value );

                    if ( binaryFileType != null )
                    {
                        byte[] data = null;

                        using ( WebClient wc = new WebClient() )
                        {
                            data = wc.DownloadData( url );
                        }

                        BinaryFile binaryFile = new BinaryFile();
                        binaryFile.Guid = Guid.NewGuid();
                        binaryFile.IsTemporary = true;
                        binaryFile.BinaryFileTypeId = binaryFileType.Id;
                        binaryFile.MimeType = "application/pdf";
                        binaryFile.FileName = fileName;
                        binaryFile.ContentStream = new MemoryStream( data );

                        var binaryFileService = new BinaryFileService( rockContext );
                        binaryFileService.Add( binaryFile );

                        rockContext.SaveChanges();

                        return binaryFile.Guid;
                    }
                }
            }

            return null;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            string size = GetAttributeValue( action, "size" ) ?? "200";
            string value = GetAttributeValue( action, "Person" );
            Guid personGuid = value.AsGuid();
            if ( !personGuid.IsEmpty() )
            {
                var attributePerson = AttributeCache.Read( personGuid, rockContext );
                if ( attributePerson != null )
                {
                    string attributePersonValue = action.GetWorklowAttributeValue( personGuid );
                    if ( !string.IsNullOrWhiteSpace( attributePersonValue ) )
                    {
                        if ( attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType" )
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if ( !personAliasGuid.IsEmpty() )
                            {
                                var person = new PersonAliasService( rockContext ).Queryable()
                                    .Where( a => a.Guid.Equals( personAliasGuid ) )
                                    .Select( a => a.Person )
                                    .FirstOrDefault();
                                if ( person != null )
                                {
                                    if ( !string.IsNullOrEmpty( person.Email ) )
                                    {
                                        // Build MD5 hash for email
                                        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                                        byte[] encodedEmail = new UTF8Encoding().GetBytes( person.Email.ToLower().Trim() );
                                        byte[] hashedBytes = md5.ComputeHash( encodedEmail );
                                        StringBuilder sb = new StringBuilder( hashedBytes.Length * 2 );
                                        for ( int i = 0; i < hashedBytes.Length; i++ )
                                        {
                                            sb.Append( hashedBytes[i].ToString( "X2" ) );
                                        }
                                        string hash = sb.ToString().ToLower();
                                        // Query Gravatar's https endpoint asking for a 404 on no match
                                        var restClient = new RestClient( string.Format( "https://secure.gravatar.com/avatar/{0}.jpg?default=404&size={1}", hash, size ) );
                                        var request = new RestRequest( Method.GET );
                                        var response = restClient.Execute( request );
                                        if ( response.StatusCode == HttpStatusCode.OK )
                                        {
                                            var bytes = response.RawBytes;
                                            // Create and save the image
                                            BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                            if ( fileType != null )
                                            {

                                                var binaryFileService = new BinaryFileService( rockContext );
                                                var binaryFile = new BinaryFile();
                                                binaryFileService.Add( binaryFile );
                                                binaryFile.IsTemporary = false;
                                                binaryFile.BinaryFileType = fileType;
                                                binaryFile.MimeType = "image/jpeg";
                                                binaryFile.FileName = person.NickName + person.LastName + ".jpg";
                                                binaryFile.ContentStream = new MemoryStream( bytes );

                                                person.PhotoId = binaryFile.Id;
                                                rockContext.SaveChanges();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        errorMessages.Add( string.Format( "Email address could not be found for {0} ({1})!", person.FullName.ToString(), personGuid.ToString() ) );
                                    }
                                }
                                else
                                {
                                    errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", personGuid.ToString() ) );
                                }
                            }
                        }
                        else
                        {
                            errorMessages.Add( "The attribute used to provide the person was not of type 'Person'." );
                        }
                    }
                }
            }

            return true;
        }
Пример #17
0
        /// <summary>
        /// Gets the name of the facebook user.
        /// </summary>
        /// <param name="facebookUser">The facebook user.</param>
        /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetFacebookUserName( FacebookUser facebookUser, bool syncFriends = false, string accessToken = "" )
        {
            string username = string.Empty;
            string facebookId = facebookUser.id;
            string facebookLink = facebookUser.link;

            string userName = "******" + facebookId;
            UserLogin user = null;

            using ( var rockContext = new RockContext() )
            {

                // Query for an existing user
                var userLoginService = new UserLoginService( rockContext );
                user = userLoginService.GetByUserName( userName );

                // If no user was found, see if we can find a match in the person table
                if ( user == null )
                {
                    // Get name/email from Facebook login
                    string lastName = facebookUser.last_name.ToStringSafe();
                    string firstName = facebookUser.first_name.ToStringSafe();
                    string email = string.Empty;
                    try { email = facebookUser.email.ToStringSafe(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if ( !string.IsNullOrWhiteSpace( email ) )
                    {
                        var personService = new PersonService( rockContext );
                        var people = personService.GetByMatch( firstName, lastName, email );
                        if ( people.Count() == 1)
                        {
                            person = people.First();
                        }
                    }

                    var personRecordTypeId = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    var personStatusPending = DefinedValueCache.Read( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid() ).Id;

                    rockContext.WrapTransaction( () =>
                    {
                        if ( person == null )
                        {
                            person = new Person();
                            person.IsSystem = false;
                            person.RecordTypeValueId = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName = firstName;
                            person.LastName = lastName;
                            person.Email = email;
                            person.IsEmailActive = true;
                            person.EmailPreference = EmailPreference.EmailAllowed;
                            try
                            {
                                if ( facebookUser.gender.ToString() == "male" )
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if ( facebookUser.gender.ToString() == "female" )
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if ( person != null )
                            {
                                PersonService.SaveNewPerson( person, rockContext, null, false );
                            }
                        }

                        if ( person != null )
                        {
                            int typeId = EntityTypeCache.Read( typeof( Facebook ) ).Id;
                            user = UserLoginService.Create( rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true );
                        }

                    } );
                }

                if ( user != null )
                {
                    username = user.UserName;

                    if ( user.PersonId.HasValue )
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService( rockContext );
                        var person = personService.Get( user.PersonId.Value );
                        if ( person != null )
                        {
                            // If person does not have a photo, try to get their Facebook photo
                            if ( !person.PhotoId.HasValue )
                            {
                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId ) );
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );
                                var restResponse = restClient.Execute( restRequest );
                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    dynamic picData = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    bool isSilhouette = picData.data.is_silhouette;
                                    string url = picData.data.url;

                                    // If Facebook returned a photo url
                                    if ( !isSilhouette && !string.IsNullOrWhiteSpace( url ) )
                                    {
                                        // Download the photo from the url provided
                                        restClient = new RestClient( url );
                                        restRequest = new RestRequest( Method.GET );
                                        restResponse = restClient.Execute( restRequest );
                                        if ( restResponse.StatusCode == HttpStatusCode.OK )
                                        {
                                            var bytes = restResponse.RawBytes;

                                            // Create and save the image
                                            BinaryFileType fileType = new BinaryFileTypeService( rockContext ).Get( Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid() );
                                            if ( fileType != null )
                                            {
                                                var binaryFileService = new BinaryFileService( rockContext );
                                                var binaryFile = new BinaryFile();
                                                binaryFileService.Add( binaryFile );
                                                binaryFile.IsTemporary = false;
                                                binaryFile.BinaryFileType = fileType;
                                                binaryFile.MimeType = "image/jpeg";
                                                binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg";
                                                binaryFile.ContentStream = new MemoryStream( bytes );

                                                rockContext.SaveChanges();

                                                person.PhotoId = binaryFile.Id;
                                                rockContext.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }

                            // Save the facebook social media link
                            var facebookAttribute = AttributeCache.Read( Rock.SystemGuid.Attribute.PERSON_FACEBOOK.AsGuid() );
                            if ( facebookAttribute != null )
                            {
                                person.LoadAttributes( rockContext );
                                person.SetAttributeValue( facebookAttribute.Key, facebookLink );
                                person.SaveAttributeValues( rockContext );
                            }

                            if ( syncFriends && !string.IsNullOrWhiteSpace( accessToken ) )
                            {
                                // Get the friend list (only includes friends who have also authorized this app)
                                var restRequest = new RestRequest( Method.GET );
                                restRequest.AddParameter( "access_token", accessToken );
                                restRequest.RequestFormat = DataFormat.Json;
                                restRequest.AddHeader( "Accept", "application/json" );

                                var restClient = new RestClient( string.Format( "https://graph.facebook.com/v2.2/{0}/friends", facebookId ) );
                                var restResponse = restClient.Execute( restRequest );

                                if ( restResponse.StatusCode == HttpStatusCode.OK )
                                {
                                    // Get a list of the facebook ids for each friend
                                    dynamic friends = JsonConvert.DeserializeObject<ExpandoObject>( restResponse.Content, converter );
                                    var facebookIds = new List<string>();
                                    foreach ( var friend in friends.data )
                                    {
                                        facebookIds.Add( friend.id );
                                    }

                                    // Queue a transaction to add/remove friend relationships in Rock
                                    var transaction = new Rock.Transactions.UpdateFacebookFriends( person.Id, facebookIds );
                                    Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
                                }
                            }
                        }

                    }
                }

                return username;
            }
        }
Пример #18
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 SavePhoto( string photoUrl, 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( photoUrl );
            binaryFile.Data = new BinaryFileData();
            binaryFile.SetStorageEntityTypeId( _storageEntityType.Id );

            var webClient = new WebClient();
            try
            {
                binaryFile.Data.Content = webClient.DownloadData( photoUrl );

                if ( webClient.ResponseHeaders != null )
                {
                    binaryFile.MimeType = webClient.ResponseHeaders["content-type"];
                }
                else
                {
                    switch ( Path.GetExtension( photoUrl ) )
                    {
                        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}", photoUrl ) );
                    }
                }

                var binaryFileService = new BinaryFileService( context );
                binaryFileService.Add( binaryFile );
                return binaryFile;
            }
            catch ( WebException )
            {
                return null;
            }
        }
Пример #19
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>
        /// Processes the binary file.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="uploadedFile">The uploaded file.</param>
        private void ProcessBinaryFile( HttpContext context, HttpPostedFile uploadedFile )
        {
            // get BinaryFileType info
            Guid fileTypeGuid = context.Request.QueryString["fileTypeGuid"].AsGuid();

            RockContext rockContext = new RockContext();
            BinaryFileType binaryFileType = new BinaryFileTypeService( rockContext ).Get( fileTypeGuid );

            if ( binaryFileType == null )
            {
                throw new Rock.Web.FileUploadException( "Binary file type must be specified", System.Net.HttpStatusCode.Forbidden );
            }
            else
            {
                var currentUser = UserLoginService.GetCurrentUser();
                Person currentPerson = currentUser != null ? currentUser.Person : null;

                if ( !binaryFileType.IsAuthorized( Authorization.EDIT, currentPerson ) )
                {
                    throw new Rock.Web.FileUploadException( "Not authorized to upload this type of file", System.Net.HttpStatusCode.Forbidden );
                }
            }

            // always create a new BinaryFile record of IsTemporary when a file is uploaded
            var binaryFileService = new BinaryFileService( rockContext );
            var binaryFile = new BinaryFile();
            binaryFileService.Add( binaryFile );

            // assume file is temporary unless specified otherwise so that files that don't end up getting used will get cleaned up
            binaryFile.IsTemporary = context.Request.QueryString["IsTemporary"].AsBooleanOrNull() ?? true;
            binaryFile.BinaryFileTypeId = binaryFileType.Id;
            binaryFile.MimeType = uploadedFile.ContentType;
            binaryFile.FileName = Path.GetFileName( uploadedFile.FileName );
            binaryFile.ContentStream = GetFileContentStream( context, uploadedFile );
            rockContext.SaveChanges();

            var response = new
            {
                Id = binaryFile.Id,
                FileName = binaryFile.FileName
            };

            context.Response.Write( response.ToJson() );
        }