private IDictionary <string, List <dynamic> > RemoveEmptyProperties(IDictionary <string, List <dynamic> > properties, ISet <string> propertyKeysToIgnore) { properties = properties .Where(propertyValues => propertyValues.Value != null) // if the user inserts null values instead of lists .Select(propertyValues => { var newValues = propertyValues.Value .Where(v => v != null) // Filter empty properties .Where(v => !string.IsNullOrWhiteSpace(v.ToString().Trim())) .Select(value => { // Check if value is entity and remove nested empty values if (DynamicExtension.IsType <Entity>(value, out Entity entity)) { entity.Properties = RemoveEmptyProperties(entity.Properties, propertyKeysToIgnore); entity.InboundProperties = null; return(entity as dynamic); } return(value); }); return(new KeyValuePair <string, List <dynamic> >(propertyValues.Key, newValues.ToList())); }) .Where(propertyValues => !(propertyValues.Value.IsNullOrEmpty() || propertyKeysToIgnore.Contains(propertyValues.Key))) // Remove empty lists and property keys to be ignored .ToDictionary(x => x.Key, x => x.Value); return(properties); }
public async Task <ActionResult> FB_AdminPages() { var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); dynamic myPages = await fb.GetTaskAsync( "me/accounts?fields=id, name, link, is_published, likes, talking_about_count" .GraphAPICall(appsecret_proof)); var pageList = new List <FacebookPageViewModel>(); foreach (dynamic page in myPages.data) { pageList.Add(DynamicExtension.ToStatic <FacebookPageViewModel>(page)); } return(PartialView(pageList)); } else { throw new HttpException(404, "Missing Access Token"); } }
public async Task <ActionResult> Index() { #region Permission Check PermissionRequestViewModel permissionViewModel = base.GetMissingPermissions(); if (permissionViewModel != null && permissionViewModel.MissingPermissions.Count > 0) { return(View("FB_RequestPermission", permissionViewModel)); } #endregion var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); //Get current user's profile dynamic myInfo = await fb.GetTaskAsync("me?fields=first_name,last_name,link,locale,email,name,birthday,gender,location,bio,age_range".GraphAPICall(appsecret_proof)); //get current picture dynamic profileImgResult = await fb.GetTaskAsync("{0}/picture?width=100&height=100&redirect=false".GraphAPICall((string)myInfo.id, appsecret_proof)); //Hydrate FacebookProfileViewModel with Graph API results var facebookProfile = DynamicExtension.ToStatic <FacebookProfileViewModel>(myInfo); facebookProfile.ImageURL = profileImgResult.data.url; return(View(facebookProfile)); } else { throw new HttpException(404, "Missing Access Token"); } }
public async Task <ActionResult> ReloadAlbum(string ReloadAlbumId) { #region Facebook Graph API Retrieve Albums var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); #region Get Photo Albums dynamic myInfo = await fb.GetTaskAsync( string.Format( "me/albums/{0}?fields=id,name,count,link,can_upload, picture, privacy", ReloadAlbumId) .GraphAPICall(appsecret_proof), null); #endregion #region Hydrate results //Hydrate FacebookProfileViewModel with Graph API results FacebookAlbumViewModel album = DynamicExtension.ToStatic <FacebookAlbumViewModel> (myInfo.data[0]); #endregion return(PartialView("FB_Album_Response", album)); } else { throw new HttpException(404, "Missing Access Token"); } #endregion }
public async Task <ActionResult> Get() { #region Facebook Graph API Retrieve Subscriptions var app_token = base.GetAppToken; if (!string.IsNullOrEmpty(app_token)) { var fb = new FacebookClient(app_token); #region Get Subscriptions dynamic result = await fb.GetTaskAsync( string.Format("subscriptions"), null); #endregion #region Hydrate results //Hydrate FacebookSubscriptionViewModel with Graph API results var subscriptionList = new List <FacebookSubscriptionViewModel>(); foreach (dynamic subscription in result.data) { subscriptionList.Add( DynamicExtension.ToStatic <FacebookSubscriptionViewModel>(subscription)); } #endregion return(PartialView("FB_GetSubscriptions_Response", subscriptionList)); } else { throw new HttpException(404, "Missing App Token"); } #endregion }
private IList <UrlCheckingCTO> GetIdentifierAndTargetUrls(Entity resource) { var identifiers = new List <UrlCheckingCTO>(); foreach (var property in resource.Properties) { foreach (var prop in property.Value) { if (property.Key == Graph.Metadata.Constants.Resource.DistributionEndpoints.HasNetworkAddress) { identifiers.Add(new UrlCheckingCTO(property.Key, resource.Id, prop)); } else if (DynamicExtension.IsType <Entity>(prop, out Entity parsedProp)) { if (property.Key == Graph.Metadata.Constants.EnterpriseCore.PidUri || property.Key == Graph.Metadata.Constants.Resource.BaseUri) { if (!string.IsNullOrWhiteSpace(parsedProp.Id)) { identifiers.Add(new UrlCheckingCTO(property.Key, resource.Id, parsedProp.Id)); } } else { identifiers.AddRange(GetIdentifierAndTargetUrls(parsedProp)); } } } } return(identifiers); }
/// <summary> /// Searches the properties for linked published entries including all nested objects /// </summary> /// <param name="properties">Properties of the entry to be searched</param> /// <param name="metadataProperties">Metadata of the entity type</param> /// <returns></returns> private static IList <string> GetAllLinkedResourceUris(IDictionary <string, List <dynamic> > properties, IList <MetadataProperty> metadataProperties) { var linkedUris = new List <string>(); foreach (var propertyItem in properties) { foreach (var propertyValue in propertyItem.Value) { var metadata = metadataProperties.FirstOrDefault(prop => prop.Properties[Graph.Metadata.Constants.EnterpriseCore.PidUri] == propertyItem.Key); if (metadata?.GetMetadataPropertyGroup()?.Key == Graph.Metadata.Constants.Resource.Groups.LinkTypes) { if (DynamicExtension.IsType <Entity>(propertyValue, out Entity linkedEntity)) { var pidUri = linkedEntity.Properties.GetValueOrNull(Graph.Metadata.Constants.EnterpriseCore.PidUri, true); linkedUris.Add(pidUri is Entity ? pidUri.Id : pidUri); } else { linkedUris.Add(propertyValue); } } } } return(linkedUris); }
public SkyDrivePhoto(ICloudFolder parent, IDictionary <string, object> objectDictionary) : base(parent, objectDictionary) { this.TagsCount = Dictionary.tags_count; this.TagsEnabled = Dictionary.tags_enabled; this.IsEmbeddable = Dictionary.is_embeddable; this.PictureLocation = Dictionary.picture; this.WhenTaken = DynamicExtension.ToDateTime(Dictionary.when_taken); this.Height = Dictionary.height; this.Width = Dictionary.width; this.CameraMake = Dictionary.camera_make; this.CameraModel = Dictionary.camera_model; this.FocalRatio = Dictionary.focal_ration; this.FocalLength = Dictionary.focal_length; this.ExposureNumerator = Dictionary.exposure_numerator; this.ExposureDenominator = Dictionary.exposure_denominator; this.PhotographyLocation = Dictionary.location ?? "Location Unavailable."; this.Photos = new Dictionary <PhotoType, PhotoCard>(Dictionary.images.Count); foreach (dynamic photo in Dictionary.images) { var card = new PhotoCard(); card.Height = photo.height; card.Width = photo.width; card.PhotoType = (PhotoType)Enum.Parse(typeof(PhotoType), photo.type, true); card.DownloadSourceLocation = photo.source; if (this.Photos.ContainsKey(card.PhotoType)) { this.Photos.Remove(card.PhotoType); } this.Photos.Add(card.PhotoType, card); } }
public async Task <ActionResult> GetAlbums() { #region Facebook Graph API Retrieve Albums var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); #region Get Photo Albums dynamic myInfo = await fb.GetTaskAsync( string.Format("me/albums?fields=id,name, count, link," + "picture, privacy") .GraphAPICall(appsecret_proof), null); #endregion #region Hydrate results //Hydrate FacebookProfileViewModel with Graph API results var albumList = new List <FacebookAlbumViewModel>(); foreach (dynamic album in myInfo.data) { albumList.Add(DynamicExtension.ToStatic <FacebookAlbumViewModel>(album)); } #endregion return(PartialView("FB_GetAlbums_Response", albumList)); } else { throw new HttpException(404, "Missing Access Token"); } #endregion }
private IDictionary <string, List <dynamic> > SortValuesByKeyAndValue(IDictionary <string, List <dynamic> > properties) { var sortedProperties = properties .Select(propertyValues => { var newValues = propertyValues.Value .Select(value => { // Check if value is entity and remove nested empty values if (DynamicExtension.IsType <Entity>(value, out Entity entity)) { entity.Properties = SortValuesByKeyAndValue(entity.Properties); return(entity as dynamic); } return(value); }) .OrderBy(t => GetKeyToOrderBy(t)); return(new KeyValuePair <string, List <dynamic> >(propertyValues.Key, newValues.ToList())); }) .OrderBy(x => x.Key, StringComparer.Ordinal) // sort by key .ToDictionary(x => x.Key, x => x.Value); return(sortedProperties); }
private IList <string> GetAllIdentifiersOfResource(Entity entity) { IList <string> pidUris = new List <string>(); if (entity != null) { foreach (var property in entity.Properties) { if (property.Key == Graph.Metadata.Constants.EnterpriseCore.PidUri || property.Key == Graph.Metadata.Constants.Resource.BaseUri) { pidUris.Add(property.Value?.FirstOrDefault()?.Id); } else if (property.Key == Graph.Metadata.Constants.Resource.Distribution || property.Key == Graph.Metadata.Constants.Resource.MainDistribution) { foreach (var prop in property.Value) { if (DynamicExtension.IsType <Entity>(prop, out Entity parsedProp)) { IList <string> nestedUris = GetAllIdentifiersOfResource(parsedProp); pidUris.AddRange(nestedUris); } } } } } return(pidUris.Where(uri => !string.IsNullOrWhiteSpace(uri)).ToList()); }
public async Task <ActionResult> FB_GetFeed() { var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); dynamic myFeed = await fb.GetTaskAsync( ("me/feed?fields=id,from {{id, name, picture{{url}} }},story,picture,link,name,description," + "message,type,created_time,likes,comments") .GraphAPICall(appsecret_proof)); var postList = new List <FacebookPostViewModel>(); foreach (dynamic post in myFeed.data) { postList.Add(DynamicExtension.ToStatic <FacebookPostViewModel>(post)); } return(PartialView(postList)); } else { throw new HttpException(404, "Missing Access Token"); } }
/// <summary> /// Registers all packet handlers defined in the given type. /// </summary> /// <param name = "type">the type to search through for packet handlers</param> public void Register(Type type) { if (type.IsAbstract || !(type.GetInterfaces().Contains(typeof(TContainer)) || type.IsSubclassOf(typeof(TContainer)))) { return; } var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); TContainer handlerContainer; try { handlerContainer = (TContainer)Activator.CreateInstance(type, true); } catch (Exception e) { throw new Exception("Unable to create HandlerContainer " + type.Name + ".\n " + e.Message); } foreach (var method in methods) { var attributes = method.GetCustomAttributes(typeof(TAttribute), false) as TAttribute[]; if (attributes == null || attributes.Length == 0) { continue; } try { if ( method.GetParameters().Count( entry => (entry.ParameterType.IsSubclassOf(typeof(Message)) || (entry.ParameterType == typeof(TClient) || entry.ParameterType.IsSubclassOf(typeof(TClient))))) != 2) { throw new ArgumentException("Incorrect delegate parameters"); } var handlerDelegate = DynamicExtension.CreateDelegate(method, typeof(TClient), typeof(Message)) as Action <object, TClient, Message>; foreach (var attribute in attributes) { RegisterHandler(attribute.MessageId, handlerContainer, attribute, handlerDelegate); } } catch (Exception e) { var handlerStr = type.FullName + "." + method.Name; throw new Exception("Unable to register PacketHandler " + handlerStr + ".\n Make sure its arguments are: " + typeof(TClient).FullName + ", " + typeof(Message).FullName + ".\n" + e.Message); } } }
static void Main(string[] args) { var extended = new DynamicExtension <Person>().ExtendWith <IPerson>(); extended.Age = 25; extended.Name = "Billy"; Console.WriteLine(extended.Name + " is " + extended.Age); Console.Read(); }
public async Task <ActionResult> GetMoreData(string NextPageUri) { if (!string.IsNullOrEmpty(NextPageUri)) { #region Permission Check PermissionRequestViewModel permissionViewModel = base.GetMissingPermissions(); if (permissionViewModel != null && permissionViewModel.MissingPermissions.Count > 0) { return(View("FB_RequestPermission", permissionViewModel)); } #endregion #region Get More Paged Data var access_token = HttpContext.Items["access_token"].ToString(); if (!string.IsNullOrEmpty(access_token)) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); dynamic nextPageResult = await fb.GetTaskAsync(NextPageUri.GraphAPICall(appsecret_proof)); #region Hydrate results //Hydrate FacebookProfileViewModel with Graph API results var userList = new List <FacebookFriendViewModel>(); foreach (dynamic friend in nextPageResult.data) { userList.Add(DynamicExtension.ToStatic <FacebookFriendViewModel>(friend)); } #endregion #region Paging Results string NextPageURI = string.Empty; if (nextPageResult.paging != null && nextPageResult.paging.next != null) { NextPageURI = nextPageResult.paging.next; } ViewBag.ShowGetMoreData = GetNextPageQuery(NextPageURI, access_token); #endregion return(PartialView("FindResults", userList)); } else { throw new HttpException(404, "Missing Access Token"); } #endregion } else { return(null); } }
private List <FacebookPhotoViewModel> HydratePhotoList(dynamic Result) { var photoList = new List <FacebookPhotoViewModel>(); foreach (dynamic photo in Result.data) { photoList.Add(DynamicExtension.ToStatic <FacebookPhotoViewModel>(photo)); } return(photoList); }
private IList <ValidationResultProperty> CheckDuplicatesInRepository(Entity resource, string resourceId, string previousVersion) { var duplicateErrors = new List <ValidationResultProperty>(); var pidUriResults = GetDuplicateResultsByIdentifierType(Graph.Metadata.Constants.EnterpriseCore.PidUri, resource, out var pidUri); var baseUriResults = GetDuplicateResultsByIdentifierType(Graph.Metadata.Constants.Resource.BaseUri, resource, out var baseUri); var targetUriResults = GetDuplicateResultsByTargetUri(resource, out var targetUri); // allow the pidURI to be duplicate when changing resource type if (pidUri != null && pidUri != string.Empty) { if (pidUriResults.Count == 2 && pidUriResults[0].Type != pidUriResults[1].Type && resource.Id != null) { pidUriResults.Clear(); } } // TODO: Piduri has no entry then duplicate, or if entry/entryDraft is not actual resource if (CheckIdentifierIsDuplicate(pidUriResults, resource, resourceId, out bool orphanedPid)) { var message = orphanedPid ? Common.Constants.Validation.DuplicateFieldOrphaned : Common.Constants.Validation.DuplicateField; var pidUriValidationResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.EnterpriseCore.PidUri, pidUri, message, ValidationResultSeverity.Violation, ValidationResultPropertyType.DUPLICATE); duplicateErrors.Add(pidUriValidationResult); } if (CheckBaseUriIsDuplicate(baseUriResults, resource, resourceId, pidUri, previousVersion, out bool orphanedBaseUri)) { var message = orphanedBaseUri ? Common.Constants.Validation.DuplicateFieldOrphaned : Common.Constants.Validation.DuplicateField; var baseUriValidatioResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.Resource.BaseUri, baseUri, message, ValidationResultSeverity.Violation, ValidationResultPropertyType.DUPLICATE, null); duplicateErrors.Add(baseUriValidatioResult); } if (CheckIdentifierIsDuplicate(targetUriResults, resource, resourceId, out _)) { var targetUriValidationResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.Resource.DistributionEndpoints.HasNetworkAddress, targetUri, Common.Constants.Validation.DuplicateField, ValidationResultSeverity.Info, ValidationResultPropertyType.DUPLICATE); duplicateErrors.Add(targetUriValidationResult); } foreach (var property in resource.Properties) { // TODO: Check metadata property type is permanent identifier if (property.Key != Graph.Metadata.Constants.EnterpriseCore.PidUri && property.Key != Graph.Metadata.Constants.Resource.BaseUri) { foreach (var prop in property.Value) { if (DynamicExtension.IsType <Entity>(prop, out Entity entity)) { duplicateErrors.AddRange(CheckDuplicatesInRepository(entity, resourceId, string.Empty)); } } } } return(duplicateErrors); }
public static void Initialize(Assembly asm) { var methods = asm.GetTypes() .SelectMany(t => t.GetMethods()) .Where(m => m.GetCustomAttributes(typeof(HeaderPacketAttribute), false).Length > 0) .ToArray(); foreach (var method in methods) { var action = DynamicExtension.CreateDelegate(method, typeof(SimpleClient), typeof(NetworkMessage)) as Action <object, SimpleClient, NetworkMessage>; MethodHandlers.Add((HeaderEnum)method.CustomAttributes.ToArray()[0].ConstructorArguments[0].Value, action); } }
public async Task <ActionResult> FB_TaggableFriends() { var access_token = HttpContext.Items["access_token"].ToString(); if (access_token != null) { var appsecret_proof = access_token.GenerateAppSecretProof(); var fb = new FacebookClient(access_token); dynamic myInfo = await fb.GetTaskAsync("me/taggable_friends?limit=5000".GraphAPICall(appsecret_proof)); var friendsList = new List <FacebookFriendViewModel>(); foreach (dynamic friend in myInfo.data) { FacebookFriendViewModel facebookFriendViewModel = DynamicExtension.ToStatic <FacebookFriendViewModel>(friend); /* * dynamic friendInfo = await fb.GetTaskAsync((facebookFriendViewModel.TaggingId).GraphAPICall(appsecret_proof)); * FacebookProfileViewModel facebookProfile = DynamicExtension.ToStatic<FacebookProfileViewModel>(friendInfo); * facebookFriendViewModel.facebookProfileViewModel = facebookProfile; */ friendsList.Add(facebookFriendViewModel); } friendsList.Sort(delegate(FacebookFriendViewModel x, FacebookFriendViewModel y) { if (x.Name == null && y.Name == null) { return(0); } else if (x.Name == null) { return(-1); } else if (y.Name == null) { return(1); } else { return(x.Name.CompareTo(y.Name)); } }); return(PartialView(friendsList)); } else { throw new HttpException(404, "Missing Access Token"); } }
/// <summary> /// /// </summary> /// <param name="resource"></param> /// <param name="key"></param> private void CleanupPermanentIdentifierForKey(Entity resource, string key) { if (resource.Properties.TryGetValue(key, out var distributionEndpoints)) { resource.Properties[key] = distributionEndpoints.Select(dynamicEndpoint => { if (DynamicExtension.IsType <Entity>(dynamicEndpoint, out Entity distributionEndpoint)) { distributionEndpoint.Properties = CleanupPermanentIdentifier(distributionEndpoint.Properties); return(distributionEndpoint); } return(dynamicEndpoint); }).ToList(); } }
protected override void InternalHasValidationResult(EntityValidationFacade validationFacade, KeyValuePair <string, List <dynamic> > properties) { // If there are already critical errors that apply to the property, no further validation is performed. if (validationFacade.ValidationResults.Any(v => v.Node == validationFacade.RequestResource.Id && v.Path == properties.Key && v.ResultSeverity == ValidationResultSeverity.Violation)) { return; } var firstIdentifier = properties.Value.FirstOrDefault(); // Identifiers must always be specified as entity. If the format does not match, stop validation here. if (!DynamicExtension.IsType <Entity>(firstIdentifier, out Entity uriEntity)) { return; } // In some cases wrong identifier types are given. Therefore the type is removed and added correctly. uriEntity.Properties.AddOrUpdate(Graph.Metadata.Constants.RDF.Type, new List <dynamic>() { Graph.Metadata.Constants.Identifier.Type }); // Trimming the PID URI for whitespaces uriEntity.Id = uriEntity.Id?.Trim(); Uri uriResult = new Uri(uriEntity.Id, UriKind.Absolute); // Check if uri start with pid host -> it is different for every environment if (!uriResult.Host.StartsWith(_colidDomain)) { validationFacade.ValidationResults.Add(new ValidationResultProperty(validationFacade.RequestResource.Id, properties.Key, uriEntity.Id, string.Format(Graph.Metadata.Constants.Messages.Identifier.InvalidPrefix, _colidDomain), ValidationResultSeverity.Violation)); } // Check if the uri is not only the host, but has also been extended else if (string.IsNullOrEmpty(uriResult.AbsolutePath) || uriResult.AbsolutePath == "/") { validationFacade.ValidationResults.Add(new ValidationResultProperty(validationFacade.RequestResource.Id, properties.Key, uriEntity.Id, string.Format(Graph.Metadata.Constants.Messages.Identifier.IdenticalToPrefix, _colidDomain), ValidationResultSeverity.Violation)); } // Identifiers must not contain the defined pid host more than once. else if (Regex.Matches(uriResult.OriginalString, _colidDomain).Count > 1) { validationFacade.ValidationResults.Add(new ValidationResultProperty(validationFacade.RequestResource.Id, properties.Key, uriEntity.Id, string.Format(Graph.Metadata.Constants.Messages.Identifier.SeveralPrefixUsage, _colidDomain), ValidationResultSeverity.Violation)); } validationFacade.RequestResource.Properties[properties.Key] = new List <dynamic>() { uriEntity }; }
public int CompareTo(object obj) { if (obj == null) { return(1); } if (DynamicExtension.IsType(obj, out Entity otherEntity)) { string type = Properties.GetValueOrNull(Graph.Metadata.Constants.RDF.Type, true); string otherType = otherEntity.Properties.GetValueOrNull(Graph.Metadata.Constants.RDF.Type, true); return(type.CompareTo(otherType)); } throw new ArgumentException($"Object is not type of class {typeof(Entity)}"); }
/// <summary> /// Checks if the given resource contains a permanent identifier for a given property value and removed related properties. /// </summary> /// <param name="properties">the properties to clean</param> /// <returns>true if exists, otehrwise false</returns> private IDictionary <string, List <dynamic> > CleanupPermanentIdentifier(IDictionary <string, List <dynamic> > properties) { if (properties.TryGetValue(Graph.Metadata.Constants.EnterpriseCore.PidUri, out var pidUriEntities)) { properties[Graph.Metadata.Constants.EnterpriseCore.PidUri] = pidUriEntities.Select(pidUriEntity => { if (DynamicExtension.IsType <Entity>(pidUriEntity, out Entity newEntity)) { newEntity.Properties.Clear(); return(newEntity); } return(pidUriEntity); }).Cast <dynamic>().ToList(); } return(properties); }
//private Uri RedirectUri //{ // get // { // var uriBuilder = new UriBuilder(Request.Url); // uriBuilder.Query = null; // uriBuilder.Fragment = null; // uriBuilder.Path = Url.Action("ExternalCallBack", "Facebook"); // return uriBuilder.Uri; // } //} //private RedirectResult GetFacebookLoginURL() //{ // if (Session["AccessTokenRetryCount"] == null || // (Session["AccessTokenRetryCount"] != null && // Session["AccessTokenRetryCount"].ToString() == "0")) // { // Session.Add("AccessTokenRetryCount", "1"); // FacebookClient fb = new FacebookClient(); // fb.AppId = ConfigurationManager.AppSettings["Facebook_AppId"]; // return Redirect(fb.GetLoginUrl(new // { // scope = ConfigurationManager.AppSettings["Facebook_Scope"], // redirect_uri = RedirectUri.AbsoluteUri, // response_type = "code" // }).ToString()); // } // else // { // ViewBag.ErrorMessage = "Unable to obtain a valid Facebook Token, contact support"; // return Redirect(Url.Action("Index", "Error")); // } //} //protected override void OnException(ExceptionContext filterContext) //{ // if (filterContext.Exception is FacebookApiLimitException) // { // //Status message banner notifying user to try again later // filterContext.ExceptionHandled = true; // ViewBag.GlobalStatusMessage = "Facebook Graph API limit reached, Please try again later..."; // } // else if (filterContext.Exception is FacebookOAuthException) // { // FacebookOAuthException OAuth_ex = (FacebookOAuthException)filterContext.Exception; // if (OAuth_ex.ErrorCode == 190 || OAuth_ex.ErrorSubcode > 0) // { // filterContext.ExceptionHandled = true; // filterContext.Result = GetFacebookLoginURL(); // } // else // { // //redirect to Facebook Custom Error Page // ViewBag.ErrorMessage = filterContext.Exception.Message; // filterContext.ExceptionHandled = true; // filterContext.Result = RedirectToAction("Index", "Error"); // } // } // else if (filterContext.Exception is FacebookApiException) // { // //redirect to Facebook Custom Error Page // ViewBag.ErrorMessage = filterContext.Exception.Message; // filterContext.ExceptionHandled = true; // filterContext.Result = RedirectToAction("Index", "Error"); // } // else // base.OnException(filterContext); //} //public async Task<ActionResult> ExternalCallBack(string code) //{ // //Callback return from Facebook will include a unique login encrypted code // //for this user's login with our application id // //that we can use to obtain a new access token // FacebookClient fb = new FacebookClient(); // //Exchange encrypted login code for an access_token // dynamic newTokenResult = await fb.GetTaskAsync( // string.Format("oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", // ConfigurationManager.AppSettings["Facebook_AppId"], // Url.Encode(RedirectUri.AbsoluteUri), // ConfigurationManager.AppSettings["Facebook_AppSecret"], // code)); // ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); // if (UserManager != null) // { // // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim // var userId = HttpContext.User.Identity.GetUserId(); // IList<Claim> currentClaims = await UserManager.GetClaimsAsync(userId); // //check to see if a claim already exists for FacebookAccessToken // Claim OldFacebookAccessTokenClaim = currentClaims.First(x => x.Type == "FacebookAccessToken"); // //Create new FacebookAccessToken claim // Claim newFacebookAccessTokenClaim = new Claim("FacebookAccessToken", newTokenResult.access_token); // if (OldFacebookAccessTokenClaim == null) // { // //Add new FacebookAccessToken Claim // await UserManager.AddClaimAsync(userId, newFacebookAccessTokenClaim); // } // else // { // //Remove the existing FacebookAccessToken Claim // await UserManager.RemoveClaimAsync(userId, OldFacebookAccessTokenClaim); // //Add new FacebookAccessToken Claim // await UserManager.AddClaimAsync(userId, newFacebookAccessTokenClaim); // } // Session.Add("AccessTokenRetryCount", "0"); // } // return RedirectToAction("Index"); //} // GET: Facebook public async Task <ActionResult> Index() { var access_token = HttpContext.Items["access_token"].ToString(); //try //{ var appsecret_proof = access_token.GenerateAppSecretProof(); //string _tempAccessToken = string.Empty; //if (Session["NewAccessToken"] == null) //{ // _tempAccessToken = access_token + "abc"; //} //else //{ // _tempAccessToken = access_token; //} var fb = new FacebookClient(access_token); //Get current user's profile dynamic myInfo = await fb.GetTaskAsync("me?fields=first_name,last_name,link,locale,email,name,birthday,gender,location,bio,age_range".GraphAPICall(appsecret_proof)); //get current picture dynamic profileImgResult = await fb.GetTaskAsync("{0}/picture?width=100&height=100&redirect=false".GraphAPICall((string)myInfo.id, appsecret_proof)); //Hydrate FacebookProfileViewModel with Graph API results var facebookProfile = DynamicExtension.ToStatic <FacebookProfileViewModel>(myInfo); facebookProfile.ImageURL = profileImgResult.data.url; return(View(facebookProfile)); //} //catch (FacebookApiLimitException ex) //{ // throw new HttpException(500, ex.Message); //} //catch (FacebookOAuthException ex) //{ // throw new HttpException(500, ex.Message); //} //catch (FacebookApiException ex) //{ // throw new HttpException(500, ex.Message); //} //catch (Exception ex) //{ // throw new HttpException(500, ex.Message); //} }
public static void RegisterAll() { Assembly asm = Assembly.GetAssembly(typeof(MessageInitializer)); foreach (Type type in asm.GetTypes().Where(w => w.IsSubclassOf(typeof(DiscordHandlerContener)))) { var methods = type.GetMethods().Where(x => x.CustomAttributes.Any(w => w.AttributeType == typeof(DiscordHandlerAttribute))); foreach (var method in methods) { var messageId = method.GetCustomAttribute <DiscordHandlerAttribute>().MessageId; var handlerDelegate = DynamicExtension.CreateDelegate(method, typeof(BaseMessage)) as Action <object, BaseMessage>; m_handlers.Add(messageId, handlerDelegate); } } }
private string GetKeyToOrderBy(dynamic value) { if (DynamicExtension.IsType <Entity>(value, out Entity entity)) { if (entity.Properties.TryGetValue(COLID.Graph.Metadata.Constants.EnterpriseCore.PidUri, out var pidUriList)) { foreach (var pidUriEntity in pidUriList) { if (DynamicExtension.IsType <Entity>(pidUriEntity, out Entity pidUri)) { return(pidUri.Id); } } } return(entity.Id); } return(value.ToString()); }
private IList <string> GetMatchingPidUris(Entity resource, string regexForExistingPidUris) { var matchingPidUris = new List <string>(); var activePidUris = _pidUriTemplateRepository.GetMatchingPidUris(regexForExistingPidUris, _metadataService.GetInstanceGraph(COLID.Graph.Metadata.Constants.PIDO.PidConcept), _metadataService.GetInstanceGraph("draft")); matchingPidUris.AddRange(activePidUris); Entity resourcePidUri = resource.Properties.GetValueOrNull(Graph.Metadata.Constants.EnterpriseCore.PidUri, true); Entity resourceBaseUri = resource.Properties.GetValueOrNull(Graph.Metadata.Constants.Resource.BaseUri, true); if (!string.IsNullOrWhiteSpace(resourcePidUri?.Id)) { matchingPidUris.Add(resourcePidUri.Id); } if (!string.IsNullOrWhiteSpace(resourceBaseUri?.Id)) { matchingPidUris.Add(resourceBaseUri.Id); } foreach (var property in resource.Properties) { foreach (var prop in property.Value) { if (DynamicExtension.IsType <Entity>(prop, out Entity entity)) { Entity nestedPidUri = entity.Properties.GetValueOrNull(Graph.Metadata.Constants.EnterpriseCore.PidUri, true); if (nestedPidUri != null && !string.IsNullOrWhiteSpace(nestedPidUri.Id) && Regex.IsMatch(nestedPidUri.Id, regexForExistingPidUris)) { matchingPidUris.Add(nestedPidUri.Id); } Entity nestedBaseUri = entity.Properties.GetValueOrNull(Graph.Metadata.Constants.Resource.BaseUri, true); if (nestedBaseUri != null && !string.IsNullOrWhiteSpace(nestedBaseUri.Id) && Regex.IsMatch(nestedBaseUri.Id, regexForExistingPidUris)) { matchingPidUris.Add(nestedBaseUri.Id); } } } } return(matchingPidUris); }
private void RemoveEndpointFromProperties(Entity resource, Uri distributionEndpointPidUri) { // Remove distribution endpoint from pid entry if (resource.Properties.TryGetValue(Graph.Metadata.Constants.Resource.Distribution, out List <dynamic> endpoints)) { int indexToRemove = 0; bool indexSet = false; var index = 0; foreach (var endpoint in endpoints) { if (DynamicExtension.IsType <Entity>(endpoint, out Entity distributionEndpoint)) { if (distributionEndpoint.Properties.TryGetValue(EnterpriseCore.PidUri, out List <dynamic> pidUriValue)) { Entity pidUriEntity = pidUriValue.FirstOrDefault(); if (pidUriEntity.Id == distributionEndpointPidUri.ToString()) { indexToRemove = index; indexSet = true; break; } } } index++; } if (indexSet) { endpoints.RemoveAt(indexToRemove); if (!endpoints.Any()) { resource.Properties.Remove(Graph.Metadata.Constants.Resource.Distribution); } else { resource.Properties[Graph.Metadata.Constants.Resource.Distribution] = endpoints; } } } }
/// <summary> /// Recursive function to sort the properties of an entity first by key, afterwards by value. /// </summary> /// <param name="entity">the entity to sort</param> /// <returns>a sorted entity</returns> private Entity SortEntity(Entity entity) { entity.Properties = entity.Properties .OrderBy(x => x.Key, StringComparer.Ordinal) .ThenBy(x => x.Value) .ToDictionary(x => x.Key, x => x.Value); foreach (var(_, value) in entity.Properties) { foreach (var listItem in value.Where(listItem => listItem != null)) { if (DynamicExtension.IsType <Entity>(listItem, out Entity mappedEntity)) { SortEntity(mappedEntity); } } } return(entity); }
private IList <ValidationResultProperty> CheckDuplicatesInRepository(Entity resource, string resourceId, string previousVersion) { var duplicateErrors = new List <ValidationResultProperty>(); var pidUriResults = GetDuplicateResultsByIdentifierType(Graph.Metadata.Constants.EnterpriseCore.PidUri, resource, out var pidUri); var baseUriResults = GetDuplicateResultsByIdentifierType(Graph.Metadata.Constants.Resource.BaseUri, resource, out var baseUri); var targetUriResults = GetDuplicateResultsByTargetUri(resource, out var targetUri); // TODO: Piduri has no entry then duiplicate, or if entry/entryDraft is not actual resource if (CheckIdentifierIsDuplicate(pidUriResults, resource, resourceId)) { var pidUriValidationResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.EnterpriseCore.PidUri, pidUri, Common.Constants.Validation.DuplicateField, ValidationResultSeverity.Violation, ValidationResultPropertyType.DUPLICATE); duplicateErrors.Add(pidUriValidationResult); } if (CheckBaseUriIsDuplicate(baseUriResults, resource, resourceId, pidUri, previousVersion)) { var baseUriValidatioResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.Resource.BaseUri, baseUri, Common.Constants.Validation.DuplicateField, ValidationResultSeverity.Violation, ValidationResultPropertyType.DUPLICATE, null); duplicateErrors.Add(baseUriValidatioResult); } if (CheckIdentifierIsDuplicate(targetUriResults, resource, resourceId)) { var targetUriValidationResult = new ValidationResultProperty(resource.Id, Graph.Metadata.Constants.Resource.DistributionEndpoints.HasNetworkAddress, targetUri, Common.Constants.Validation.DuplicateField, ValidationResultSeverity.Info, ValidationResultPropertyType.DUPLICATE); duplicateErrors.Add(targetUriValidationResult); } foreach (var property in resource.Properties) { foreach (var prop in property.Value) { if (DynamicExtension.IsType <Entity>(prop, out Entity parsedProp) && property.Key != Graph.Metadata.Constants.EnterpriseCore.PidUri && property.Key != Graph.Metadata.Constants.Resource.BaseUri) { duplicateErrors.AddRange(CheckDuplicatesInRepository(parsedProp, resourceId, string.Empty)); } } } return(duplicateErrors); }