本文整理汇总了C#中Rock.Model.BinaryFileService.Add方法的典型用法代码示例。如果您正苦于以下问题:C# BinaryFileService.Add方法的具体用法?C# BinaryFileService.Add怎么用?C# BinaryFileService.Add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Rock.Model.BinaryFileService
的用法示例。
在下文中一共展示了BinaryFileService.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFacebookUserName
//.........这里部分代码省略.........
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();
示例2: btnSave_Click
/// <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();
}
示例3: SaveFile
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;
}
示例4: btnSave_Click
/// <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();
}
示例5: ProcessBinaryFile
/// <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() );
}
示例6: Upload
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" )
};
}
}
示例7: SaveImage
/// <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;
}
}
示例8: Execute
/// <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;
}
示例9: SavePhoto
/// <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;
}
}
示例10: GetTwitterUser
//.........这里部分代码省略.........
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;
}
}
示例11: Execute
/// <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 )
{
//.........这里部分代码省略.........
示例12: CreateDocument
/// <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() )
//.........这里部分代码省略.........
示例13: btnSave_Click
/// <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();
}
示例14: UpdateDocumentStatus
/// <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: Save
/// <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;
}