public override IObjectsDataSet CloneDirtyObjects(IObjectsDataSet rootDataSet)
        {
            var  clone = new GOUserObjectsDataSet(rootDataSet as ObjectsDataSet);
            bool completed;

            foreach (var keyValue in this.GOUserObjects.Where(o => o.Value.IsDirty || o.Value.IsMarkedForDeletion))
            {
                var cloneObject = (GOUserDataObject)keyValue.Value.Clone(false);
                cloneObject.InternalObjectId = keyValue.Value.InternalObjectId;

                completed = false;
                while (!completed)
                {
                    completed = clone.GOUserObjects.TryAdd(keyValue.Key, cloneObject);
                }
            }

            foreach (var keyValue in this.GOUserObjectInternalIds
                     .Where(o => this.GOUserObjects[o.Value].IsDirty || this.GOUserObjects[o.Value].IsMarkedForDeletion))
            {
                completed = false;

                var count = 0;
                while (!completed && count++ < 15)
                {
                    completed = clone.GOUserObjectInternalIds.TryAdd(keyValue.Key, keyValue.Value);
                }
            }

            // CloneDirtyObjects is used to pass only dirty objects to server to save changes. Since indexes are not serialized, no need to clone them
            return(clone);
        }
        public virtual void Construct(UserProfileDataObject userProfile, bool includeDirtyObjectsOnly)
        {
            if (userProfile == null)
            {
                return;
            }

            this.PrimaryKey = userProfile.PrimaryKey;

            if (userProfile.ObjectsDataSet == null)
            {
                var dataset = ApplicationSettings.Container.Resolve <IObjectsDataSet>();
                dataset.AddObject(userProfile);
            }

            if (userProfile.ObjectsDataSet == null)
            {
                _logEngine.LogError("Unable to set a dataset to the Entity UserProfile", "Unable to set a dataset to the entity. Container may not be initialized", "UserProfileDataObject", null);
                throw new PulpException("Unexpected Error : Unable to set a dataset to the entity : UserProfile");
            }

            if (userProfile.InternalObjectId == null)
            {
                _logEngine.LogError("Unable to construct an object without InternalObjectId in UserProfileDataObject", "The Object you are trying to construct doesn't have an InternalObjectId", "UserProfileDataObject", null);
                throw new PulpException("Unexpected Error : Unable to construct an object without InternalObjectId in UserProfileDataObject");
            }
            this.InternalObjectId = (int)userProfile.InternalObjectId;
            this.ObjectsDataSet   = includeDirtyObjectsOnly ? userProfile.ObjectsDataSet.CloneDirtyObjects() : userProfile.ObjectsDataSet;
        }
示例#3
0
        // securityFilterExpression is for security : check if the user is allowed to read the entity
        protected override UserProfileDataObject DoGetFromDatabase(
            UserProfileDataObject entity,
            LambdaExpression securityFilterExpression,
            List <string> includes,
            IObjectsDataSet context,
            Parameters parameters)
        {
            var securityFilter = securityFilterExpression as Expression <Func <ORMUserProfile, bool> >;

            var query = Query(
                e => e.Uri == entity.Uri,
                null,
                null,
                securityFilter,
                throwIfAccessDenied: true);

            // Normal (default generated) behaviour is:
            // includes not treated by orm but with dispatcher mechanism to allow for proper security and extension calls on all objects
            // But the following allows custom implementations to prefetch associations
            ApplicationSettings.TryResolve <IPrefetch <ORMUserProfile> >()?.Fetch(query, includes, parameters);

            var dataset = ApplicationSettings.Resolve <IObjectsDataSet>();
            var result  = query.FirstOrDefault()?.ToDataObject(dataset) as UserProfileDataObject;

            return(result);
        }
        // Check create, update or delete authorizations on all the entities of a dataset.
        // dataset : the dataset to check
        // claims : user claims to check upon
        // entitiesToIgnore : for these entities, the check should be skipped
        // mode : define if an entity not authorized should be removed from the dataset or an exception thrown
        public PermissionLevel CheckWriteAuthorizationsOnDataSet(IObjectsDataSet saveset, UserClaims claims, Parameters parameters, out string message)
        {
            // Work on a clone of the dataset so as not to mess with the original (causes save problems otherwise, e.g. if main entity !IsDirty)
            var dataset = saveset.CloneDirtyObjects();

            message = null;
            SecurityPredicate predicate = null;

            foreach (var entity in dataset.GetAllObjects())
            {
                // get the instance of the entity authorizations class
                var entityAuthorizations = GetEntityAuthorizations(entity);

                // case delete
                if (entity.IsMarkedForDeletion)
                {
                    var permissionLevel = CanDelete(entity, claims, out message, out predicate);

                    if (permissionLevel != PermissionLevel.Authorized)
                    {
                        string explanation = Explain(EntityAccessEnum.DELETE, entityAuthorizations.EntityDisplayName);
                        message = FormatAccessDeniedMessage(explanation, predicate);
                        return(PermissionLevel.Denied);
                    }
                }
                // case create / update
                else
                {
                    PermissionLevel permissionLevel;

                    if (entity.IsNew)
                    {
                        permissionLevel = CanCreate(entity, claims, out message, out predicate);
                    }
                    else if (entity.IsDirty)
                    {
                        permissionLevel = CanUpdate(entity, claims, out message, out predicate);

                        if (permissionLevel != PermissionLevel.Authorized && AppSettings.Get <bool>("DataSetAuthorizationCheckModeRemoveFromDataSet"))
                        {
                            saveset.RemoveObject(entity);
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }

                    if (permissionLevel != PermissionLevel.Authorized)
                    {
                        string explanation = Explain(entity.IsNew ? EntityAccessEnum.CREATE : EntityAccessEnum.UPDATE, entityAuthorizations.EntityDisplayName);
                        message = FormatAccessDeniedMessage(explanation, predicate);
                        return(PermissionLevel.Denied);
                    }
                }
            }

            return(PermissionLevel.Authorized);
        }
		public virtual void Construct(GOGroupDataObject gOGroup, bool includeDirtyObjectsOnly)
		{
            if (gOGroup == null)
                return;

			this.PrimaryKey = gOGroup.PrimaryKey;
			
            if (gOGroup.ObjectsDataSet == null)
            {
                var dataset = ApplicationSettings.Container.Resolve<IObjectsDataSet>();
                dataset.AddObject(gOGroup);
            }

			if(gOGroup.ObjectsDataSet == null)
			{
				_logEngine.LogError("Unable to set a dataset to the Entity GOGroup", "Unable to set a dataset to the entity. Container may not be initialized", "GOGroupDataObject", null);
				throw new PulpException("Unexpected Error : Unable to set a dataset to the entity : GOGroup");
			}

			if(gOGroup.InternalObjectId == null)
			{
				_logEngine.LogError("Unable to construct an object without InternalObjectId in GOGroupDataObject", "The Object you are trying to construct doesn't have an InternalObjectId", "GOGroupDataObject", null);
				throw new PulpException("Unexpected Error : Unable to construct an object without InternalObjectId in GOGroupDataObject");
			}
			this.InternalObjectId = (int) gOGroup.InternalObjectId;
			this.ObjectsDataSet = includeDirtyObjectsOnly ? gOGroup.ObjectsDataSet.CloneDirtyObjects() : gOGroup.ObjectsDataSet;
		}
        public virtual void Construct(PlaceToLocationDataObject placeToLocation, bool includeDirtyObjectsOnly)
        {
            if (placeToLocation == null)
            {
                return;
            }

            this.PrimaryKey = placeToLocation.PrimaryKeysCollection;

            if (placeToLocation.ObjectsDataSet == null)
            {
                var dataset = ApplicationSettings.Container.Resolve <IObjectsDataSet>();
                dataset.AddObject(placeToLocation);
            }

            if (placeToLocation.ObjectsDataSet == null)
            {
                _logEngine.LogError("Unable to set a dataset to the Entity PlaceToLocation", "Unable to set a dataset to the entity. Container may not be initialized", "PlaceToLocationDataObject", null);
                throw new PulpException("Unexpected Error : Unable to set a dataset to the entity : PlaceToLocation");
            }

            if (placeToLocation.InternalObjectId == null)
            {
                _logEngine.LogError("Unable to construct an object without InternalObjectId in PlaceToLocationDataObject", "The Object you are trying to construct doesn't have an InternalObjectId", "PlaceToLocationDataObject", null);
                throw new PulpException("Unexpected Error : Unable to construct an object without InternalObjectId in PlaceToLocationDataObject");
            }
            this.InternalObjectId = (int)placeToLocation.InternalObjectId;
            this.ObjectsDataSet   = includeDirtyObjectsOnly ? placeToLocation.ObjectsDataSet.CloneDirtyObjects() : placeToLocation.ObjectsDataSet;
        }
示例#7
0
        public override IObjectsDataSet Clone(IObjectsDataSet rootDataSet)
        {
            var  clone = new GORoleObjectsDataSet(rootDataSet as ObjectsDataSet);
            bool completed;

            foreach (var keyValue in this.GORoleObjects)
            {
                var cloneObject = (GORoleDataObject)keyValue.Value.Clone(false);
                cloneObject.InternalObjectId = keyValue.Value.InternalObjectId;

                completed = false;
                var count = 0;
                while (!completed && count++ < 15)
                {
                    completed = clone.GORoleObjects.TryAdd(keyValue.Key, cloneObject);
                }
            }

            foreach (var keyValue in this.GORoleObjectInternalIds)
            {
                completed = false;
                var count = 0;
                while (!completed && count++ < 15)
                {
                    completed = clone.GORoleObjectInternalIds.TryAdd(keyValue.Key, keyValue.Value);
                }
            }



            return(clone);
        }
示例#8
0
 protected override UserProfileDataObject DoSaveToDatabase(
     UserProfileDataObject entity,
     List <string> includes,
     IObjectsDataSet context,
     Parameters parameters)
 {
     return(base.DoSaveToDatabase(entity, includes, context, parameters));
 }
 protected override GOLoginHistoryDataObject DoSaveToDatabase(
     GOLoginHistoryDataObject entity,
     List <string> includes,
     IObjectsDataSet context,
     Parameters parameters)
 {
     return(base.DoSaveToDatabase(entity, includes, context, parameters));
 }
示例#10
0
 public virtual int Count(
     LambdaExpression securityFilterExpression = null,
     string filterPredicate   = null,
     object[] filterArguments = null,
     IObjectsDataSet context  = null,
     Parameters parameters    = null,
     bool skipSecurity        = false /* skipSecurity has no effect here */)
 {
     throw new NotImplementedException();
 }
示例#11
0
 public virtual GOUserDataObject Save(
     GOUserDataObject theDataObjectToSave,
     bool includeDirtyObjectsOnly,
     LambdaExpression securityFilterExpression = null,
     List <string> includes  = null,
     IObjectsDataSet context = null,
     Parameters parameters   = null,
     bool skipSecurity       = false /* skipSecurity has no effect here */)
 {
     return(Save(new GOUserContainer(theDataObjectToSave, includeDirtyObjectsOnly), securityFilterExpression, includes, parameters: parameters));
 }
示例#12
0
        protected override void DoDeleteFromDatabase(
            UserProfileDataObject entity,
            LambdaExpression filterExpression,                                  // no longer used here - handled higher up the stack by dataprovider extensions
            IObjectsDataSet context,
            Parameters parameters)
        {
            var session  = NHibernateSessionController.GetCurrentSession();
            var toDelete = entity.ToORMEntity();

            session.Delete(toDelete);
        }
        // Check read authorization on all the entities of a dataset. usefull when a get, getcollection or save action is configured with includes, to make sure related objects can be read for the given user claims.
        // dataset : the dataset to check
        // entitiesToIgnore : for these entities, the check should be skipped
        // mode : define if an entity not authorized should be removed from the dataset or an exception thrown
        public PermissionLevel CheckReadAuthorizationsOnDataSet(IObjectsDataSet dataset, UserClaims claims, IEnumerable <IDataObject> entitiesToIgnore, DataSetAuthorizationCheckMode mode, Parameters parameters, out string message)
        {
            message = null;
            SecurityPredicate predicate = null;

            // Work on a clone of the dataset so as not to mess with the original (causes save problems otherwise, e.g. if main entity !IsDirty)
            dataset = dataset.Clone();

            foreach (var entity in dataset.GetAllObjects())
            {
                var permissionLevel = CanRead(entity, claims, out message, out predicate);

                if (permissionLevel != PermissionLevel.Authorized)
                {
                    if (mode == DataSetAuthorizationCheckMode.RemoveFromDataSet)
                    {
                        dataset.RemoveObject(entity);
                        continue;
                    }
                    else
                    {
                        string explanation = Explain(EntityAccessEnum.READ, GetEntityAuthorizations(entity).EntityDisplayName);
                        message = FormatAccessDeniedMessage(explanation, predicate);
                        return(PermissionLevel.Denied);
                    }
                }

                if (predicate != null)
                {
                    // If the security filter needs related data, load it first:
                    if (!String.IsNullOrEmpty(predicate.Includes))
                    {
                        DataObjectHelper.RecurseLoadIncludes(entity, parameters, predicate.Includes, skipSecurity: true);
                    }

                    if (!DoesPredicateAccept(entity, predicate.Filter, predicate.Includes, EntityAccessEnum.READ))
                    {
                        if (mode == DataSetAuthorizationCheckMode.RemoveFromDataSet)
                        {
                            dataset.RemoveObject(entity);
                            continue;
                        }
                        else
                        {
                            string explanation = Explain(EntityAccessEnum.READ, GetEntityAuthorizations(entity).EntityDisplayName);
                            message = FormatAccessDeniedMessage(explanation, predicate);
                            return(PermissionLevel.Denied);
                        }
                    }
                }
            }

            return(PermissionLevel.Authorized);
        }
示例#14
0
        public virtual VisitedPlaceDataObject Save(
            VisitedPlaceDataObject theDataObjectToSave,
            LambdaExpression securityFilterExpression = null,
            List <string> includes  = null,
            IObjectsDataSet context = null,
            Parameters parameters   = null,
            bool skipSecurity       = false /* skipSecurity has no effect here */)
        {
            bool includeDirtyObjectsOnly = GetIncludeDirtyObjectsOnlyOption(parameters);

            return(Save(new VisitedPlaceContainer(theDataObjectToSave, includeDirtyObjectsOnly), securityFilterExpression, includes, parameters: parameters));
        }
		public void Construct(DataObjectCollection<GOGroupDataObject> gOGroupItems)
        {
            if (gOGroupItems == null)
                return;
				
			this.PrimaryKeys = gOGroupItems.Select(c => c.PrimaryKey).ToList();
            if (gOGroupItems.ObjectsDataSet == null)
            {
                gOGroupItems.ObjectsDataSet = ApplicationSettings.Container.Resolve<IObjectsDataSet>();
            }
	
			this.InternalObjectIds = gOGroupItems.Select(c => c.InternalObjectId).Cast<int>().ToList();
            this.ObjectsDataSet = gOGroupItems.ObjectsDataSet;
		}
        public override IObjectsDataSet Clone(IObjectsDataSet rootDataSet)
        {
            var  clone = new GOUserObjectsDataSet(rootDataSet as ObjectsDataSet);
            bool completed;

            foreach (var keyValue in this.GOUserObjects)
            {
                var cloneObject = (GOUserDataObject)keyValue.Value.Clone(false);
                cloneObject.InternalObjectId = keyValue.Value.InternalObjectId;

                completed = false;
                var count = 0;
                while (!completed && count++ < 15)
                {
                    completed = clone.GOUserObjects.TryAdd(keyValue.Key, cloneObject);
                }
            }

            foreach (var keyValue in this.GOUserObjectInternalIds)
            {
                completed = false;
                var count = 0;
                while (!completed && count++ < 15)
                {
                    completed = clone.GOUserObjectInternalIds.TryAdd(keyValue.Key, keyValue.Value);
                }
            }


            foreach (var fkKeyValue in this.UserProfile_FKIndex)
            {
                var iscompleted = false;
                var count2      = 0;
                while (!iscompleted && count2++ < 15)
                {
                    iscompleted = clone.UserProfile_FKIndex.TryAdd(fkKeyValue.Key, new List <int>());
                }

                foreach (var pk in fkKeyValue.Value)
                {
                    clone.UserProfile_FKIndex[fkKeyValue.Key].Add(pk);
                }
            }



            return(clone);
        }
        public void Construct(DataObjectCollection <UserProfileDataObject> userProfileItems)
        {
            if (userProfileItems == null)
            {
                return;
            }

            this.PrimaryKeys = userProfileItems.Select(c => c.PrimaryKey).ToList();
            if (userProfileItems.ObjectsDataSet == null)
            {
                userProfileItems.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>();
            }

            this.InternalObjectIds = userProfileItems.Select(c => c.InternalObjectId).Cast <int>().ToList();
            this.ObjectsDataSet    = userProfileItems.ObjectsDataSet;
        }
        public void Construct(DataObjectCollection <VisitedPlaceDataObject> visitedPlaceItems)
        {
            if (visitedPlaceItems == null)
            {
                return;
            }

            this.PrimaryKeys = visitedPlaceItems.Select(c => c.PrimaryKey).ToList();
            if (visitedPlaceItems.ObjectsDataSet == null)
            {
                visitedPlaceItems.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>();
            }

            this.InternalObjectIds = visitedPlaceItems.Select(c => c.InternalObjectId).Cast <int>().ToList();
            this.ObjectsDataSet    = visitedPlaceItems.ObjectsDataSet;
        }
        public void Construct(DataObjectCollection <PlaceToLocationDataObject> placeToLocationItems)
        {
            if (placeToLocationItems == null)
            {
                return;
            }

            this.PrimaryKeys = placeToLocationItems.Select(c => c.PrimaryKeysCollection).ToList();
            if (placeToLocationItems.ObjectsDataSet == null)
            {
                placeToLocationItems.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>();
            }

            this.InternalObjectIds = placeToLocationItems.Select(c => c.InternalObjectId).Cast <int>().ToList();
            this.ObjectsDataSet    = placeToLocationItems.ObjectsDataSet;
        }
示例#20
0
        protected virtual TENTITY DoSaveToDatabase(
            TENTITY entity,
            List <string> includes,
            IObjectsDataSet context,
            Parameters parameters)
        {
            // Ensure got a dataset
            if (entity.ObjectsDataSet == null)
            {
                entity.ObjectsDataSet = ApplicationSettings.Resolve <IObjectsDataSet>();
            }

            // Ensure entity is in its own dataset
            var self = entity.ObjectsDataSet.GetObject(entity);

            if (self == null)
            {
                entity.ObjectsDataSet.AddObject(entity);
            }

            // Note: We can skip objects marked for deletion, because before arriving here, the delete resolution algorithm will already have processed them
            // Wee just need to remove the marked-for-deletion objects so that they aren't mapped or returned to caller
            foreach (var deletedObj in entity.ObjectsDataSet.GetObjectsMarkedForDeletion().ToArray())
            {
                entity.ObjectsDataSet.RemoveObject(deletedObj);

                // Remove from the context too
                if (context != null)
                {
                    context.RemoveObject(deletedObj);
                }
            }

            // Get data mapping setting from the parameters (deep is the default)
            // Deep mapping means we'll explore all relations, else will only treat the specified entity (i.e. a 'flat' single entity save)
            bool deepMapping = parameters == null || !parameters.ContainsKey(ParameterKeys.DeepDataMapping) || (bool)parameters[ParameterKeys.DeepDataMapping] == true;

            // entity returned from SaveToDatabaseThroughORM can be null (e.g. if nothing dirty/new in the saveset, or if deleted)
            entity = SaveToDatabaseThroughORM(entity, deepMapping);


            // for the refetch, security can be skipped if no related data requested (since we just wrote it, it's just a flat re-sync)
            bool canRefetchSkipSecurity = includes == null || !includes.Any() || ParameterKeys.IsOptionEnabled(parameters, ParameterKeys.ORMSaveRefetchSkipSecurity);

            return(entity == null ? null : Get(entity, includes: includes, parameters: parameters, skipSecurity: canRefetchSkipSecurity));
        }
示例#21
0
        // filterExpression is used to filter data, when filter is statically known. dynamicFilterExpression is used for dynamic filtering, when filter is not known at compile time. Both can be used at the same time
        protected override int DoCountFromDatabase(
            LambdaExpression filterExpression,
            string dynamicFilterExpression,
            object[] dynamicFilterArguments,
            IObjectsDataSet context,
            Parameters parameters)
        {
            var query = Query(dynamicFilterExpression, dynamicFilterArguments, filterExpression);

            // Put the query in the transaction parameters so that custom data provider OnAfterCount extensions can see the result set
            if (parameters != null)
            {
                parameters[ParameterKeys.DataProviderCountQuery] = query;
            }

            return(query.Count());
        }
        public override void Merge(IObjectsDataSet dataSetToMerge, bool updateOrginalInternalId)
        {
            var GOUserDataSet = dataSetToMerge as GOUserObjectsDataSet;

            if (GOUserDataSet == null)
            {
                throw new PulpException("Unable to merge the current DataSet with null");
            }
            foreach (var item in GOUserDataSet.GOUserObjects.Values)
            {
                var oldInternalId = item.InternalObjectId;

                var objectToMerge = item.Clone(false);
                objectToMerge.InternalObjectId = null;
                objectToMerge.ObjectsDataSet   = this._rootObjectDataSet;

                objectToMerge.IsMarkedForDeletion = item.IsMarkedForDeletion;

                _rootObjectDataSet.AddOrReplaceObject(objectToMerge);
                var newInternalId = objectToMerge.InternalObjectId;
                if (updateOrginalInternalId)
                {
                    item.InternalObjectId = newInternalId;
                }

                if (oldInternalId != null && !_rootObjectDataSet.DatasetMergingInternalIdMapping.ContainsKey((int)oldInternalId))
                {
                    if (newInternalId == null)
                    {
                        _logEngine.LogError("Unable to merge elements in DataSet without InternalId", "The Element you are trying to merge doesn't have an internalId", "GOUserObjectsDataSet", null);
                        throw new PulpException("Unable to merge elements in dataset without InternalId");
                    }
                    var completed = false;
                    var count     = 0;
                    while (!completed && count++ < 15)
                    {
                        completed = _rootObjectDataSet.DatasetMergingInternalIdMapping.TryAdd((int)oldInternalId, (int)newInternalId);
                    }
                }

                MergedDataObjects.Enqueue(objectToMerge as GOUserDataObject);
            }
        }
        ///
        /// Bridge to DataObject
        ///
        public virtual IDataObject ToDataObject(IObjectsDataSet dataset)
        {
            var session = NHibernateSessionController.GetCurrentSession();

            session.Evict(this);

            var x = new GOUserDataObject();

            SetProperties(x);

            x.IsDirty = x.IsNew = x.IsMarkedForDeletion = false;

            x.ObjectsDataSet = dataset;
            x.ObjectsDataSet.AddObjectIfDoesNotExist(x);

            // Deep-map prefetch relations
            if (PrefetchAssociations.HasPrefetchForEntity("GOUser", ApplicationSettings.Resolve <IDataProviderTransaction>()?.Parameters))
            {
                SetRelations(x);
            }

            return(x);
        }
示例#24
0
        // filterExpression is used to filter data, when filter is statically known. dynamicFilterExpression is used for dynamic filtering, when filter is not known at compile time. Both can be used at the same time
        protected override DataObjectCollection <UserProfileDataObject> DoGetCollectionFromDatabase(
            LambdaExpression filterExpression,
            string dynamicFilterExpression,
            object[] dynamicFilterArguments,
            string orderByPredicate,
            int pageNumber,
            int pageSize,
            List <string> includes,
            IObjectsDataSet context,
            Parameters parameters)
        {
            var query = Query(dynamicFilterExpression, dynamicFilterArguments, filterExpression);

            if (!String.IsNullOrEmpty(orderByPredicate))
            {
                query = query.OrderBy(orderByPredicate);
            }

            // Normal (default generated) behaviour is:
            // includes not treated by orm but with dispatcher mechanism to allow for proper security and extension calls on all objects
            // But the following allows custom implementations to prefetch associations
            ApplicationSettings.TryResolve <IPrefetch <ORMUserProfile> >()?.Fetch(query, includes, parameters);

            // Do Paging (unless late-paging option is enabled)
            if (!ParameterKeys.IsOptionEnabled(parameters, ParameterKeys.DataProviderGetCollectionLatePaging))
            {
                if (pageNumber != 0 && pageSize > 0)
                {
                    query = query.Skip((pageNumber - 1) * pageSize).Take(pageSize);
                }
            }

            var dataset    = ApplicationSettings.Resolve <IObjectsDataSet>();
            var collection = query.Select(x => x.ToDataObject(dataset)).Cast <UserProfileDataObject>().ToList();

            return(new DataObjectCollection <UserProfileDataObject>(collection));
        }
示例#25
0
        protected override PlaceDataObject DoGet(PlaceDataObject entity, LambdaExpression securityFilterExpression, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters)
        {
            var uri = entity.URI;

            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org");

            string queryString = @"SELECT ?name, ?abstract
                  WHERE {
                            ?place rdfs:label ?name .
                            ?place dbo:abstract ?abstract .

                            FILTER langMatches(lang(?name), 'en')
                            FILTER langMatches(lang(?abstract), 'en')}";

            queryString = queryString.Replace("?place ", $"<{uri}> ");

            //Make a SELECT query against the Endpoint
            SparqlResultSet results = endpoint.QueryWithResultSet(queryString);

            var result = results.Single();

            var place   = new PlaceDataObject();
            var dataset = ApplicationSettings.Container.Resolve <IObjectsDataSet>();

            dataset.AddObject(place);

            place.URI      = entity.URI;
            place.Name     = (result.Where(r => r.Key == "name").Single().Value as BaseLiteralNode).Value;
            place.Abstract = (result.Where(r => r.Key == "abstract").Single().Value as BaseLiteralNode)?.Value;
            place.IsNew    = false;
            place.IsDirty  = false;

            return(place);
        }
示例#26
0
 protected override void DoDelete(PlaceDataObject entity, LambdaExpression securityFilterExpression, IObjectsDataSet context, Dictionary <string, object> parameters)
 {
     throw new NotImplementedException();
 }
示例#27
0
        protected override int DoCount(LambdaExpression securityFilterExpression, string filterPredicate, object[] filterArguments, IObjectsDataSet context, Dictionary <string, object> parameters)
        {
            int count;

            var regex = new Regex("Name\\.Contains\\(\"(.*)\"\\)");

            string nameFilter = null;
            var    match      = regex.Match(filterPredicate);

            if (match.Success)
            {
                nameFilter = match.Groups[1].Value;
            }

            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org");

            //Make a SELECT query against the Endpoint
            string query =
                @"SELECT count(?place) WHERE 
                    { 
                    {?place a <http://dbpedia.org/ontology/HistoricPlace>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/Monument>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/Garden>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/Cemetery>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/ArchitecturalStructure>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/Park>}
                    UNION
                    {?place a <http://dbpedia.org/ontology/NaturalPlace>}
                    
                    ?place rdfs:label ?name .
                    FILTER langMatches(lang(?name), 'en')

                    ";

            if (!String.IsNullOrEmpty(nameFilter))
            {
                query += $"FILTER regex(?name,\"{nameFilter}\",\"i\")";
            }

            query += "}";

            //Make a SELECT query against the Endpoint
            SparqlResultSet results = endpoint.QueryWithResultSet(query);

            var res = results.Single();

            count = Convert.ToInt32((res.Single().Value as BaseLiteralNode).Value);

            return(count);
        }
示例#28
0
 protected override PlaceDataObject DoSave(PlaceDataObject entity, LambdaExpression securityFilterExpression, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters)
 {
     throw new NotImplementedException();
 }
示例#29
0
        protected override DataObjectCollection <PlaceDataObject> DoGetCollection(LambdaExpression securityFilterExpression, string filterPredicate, object[] filterArguments, string orderByPredicate, int pageNumber, int pageSize, List <string> includes, IObjectsDataSet context, Dictionary <string, object> parameters)
        {
            SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://dbpedia.org/sparql"), "http://dbpedia.org");

            var regex = new Regex("Name\\.Contains\\(\"(.*)\"\\)");

            string nameFilter = null;
            var    match      = regex.Match(filterPredicate);

            if (match.Success)
            {
                nameFilter = match.Groups[1].Value;
            }
            else if (filterPredicate.Contains("(@0.Contains(outerIt.URI))"))
            {
                var places = new DataObjectCollection <PlaceDataObject>();
                places.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>();

                foreach (var arg in filterArguments[0] as string[])
                {
                    try
                    {
                        var uri   = arg;
                        var place = DoGet(new PlaceDataObject(uri), null, includes, context, parameters);
                        places.Add(place);
                    }
                    catch (Exception)
                    { }
                }

                return(places);
            }

            string query = @"SELECT distinct(?place), ?name, ?abstract
                                WHERE {
                                {?place a <http://dbpedia.org/ontology/HistoricPlace>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/Monument>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/Garden>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/Cemetery>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/ArchitecturalStructure>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/Park>}
                                UNION
                                {?place a <http://dbpedia.org/ontology/NaturalPlace>}
                                ?place rdfs:label ?name .
                                ?place dbo:abstract ?abstract .

                                FILTER langMatches(lang(?name), 'en')
                                FILTER langMatches(lang(?abstract), 'en')";

            if (!String.IsNullOrEmpty(nameFilter))
            {
                query += $"FILTER regex(?name,\"{nameFilter}\",\"i\")";
            }

            query += "}";

            if (pageNumber != 0 || pageSize != 0)
            {
                query += $"LIMIT {pageSize} OFFSET {(pageNumber - 1) * pageSize}";
            }

            //Make a SELECT query against the Endpoint
            SparqlResultSet results = endpoint.QueryWithResultSet(query);

            var toReturn = new DataObjectCollection <PlaceDataObject>();

            toReturn.ObjectsDataSet = ApplicationSettings.Container.Resolve <IObjectsDataSet>();

            foreach (var result in results)
            {
                var place = new PlaceDataObject();

                place.URI      = (result.Where(r => r.Key == "place").Single().Value as UriNode).Uri.ToString();
                place.Name     = (result.Where(r => r.Key == "name").Single().Value as BaseLiteralNode).Value;
                place.Abstract = (result.Where(r => r.Key == "abstract").Single().Value as BaseLiteralNode)?.Value;
                place.IsNew    = false;
                place.IsDirty  = false;

                toReturn.Add(place);
            }

            return(toReturn);
        }
示例#30
0
        public virtual void Delete(
            GOUserDataObject theDataObjectToDelete,
            LambdaExpression securityFilterExpression = null,
            IObjectsDataSet context = null,
            Parameters parameters   = null,
            bool skipSecurity       = false /* skipSecurity has no effect here */)
        {
            // FC Anyone know why the append .json string? Seems incompatible with EntityApiHandler.ProceeDelete (so I'm removing it)
            // var uri = new Uri(_serviceUrl + "DeleteGOUser.json");
            var uri = new Uri(_serviceUrl);

            // Honour dry-run
            bool isDryRun = parameters != null && parameters.ContainsKey(ParameterKeys.DryDelete) && (bool)parameters[ParameterKeys.DryDelete] == true;

            if (isDryRun)
            {
                uri = new Uri(_serviceUrl + "?" + ApiRequest.RequestParameter.DryDelete + "=true");
            }

            // custom query params
            uri = AppendQueryParams(uri);

            var request = WebRequest.Create(uri);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Method      = "DELETE";
            request.Timeout     = GetRequestTimeout(parameters);


            using (var stream = request.GetRequestStream())
            {
                string objectToDeleteAsString = JsonConvert.SerializeObject(new GOUserContainer(theDataObjectToDelete), JsonSerializerSettings);

                var byteArray = Encoding.UTF8.GetBytes("entity=" + HttpUtility.UrlEncode(objectToDeleteAsString));
                stream.Write(byteArray, 0, byteArray.Length);

                // get user token for currently authenticated user if any
                var userToken = UserIdentity.UserToken;

                if (!String.IsNullOrEmpty(userToken))
                {
                    byteArray = Encoding.UTF8.GetBytes("&_user_token=" + userToken);
                    stream.Write(byteArray, 0, byteArray.Length);
                }

                try
                {
                    using (var response = request.GetResponse())
                    {
                        if (response == null)
                        {
                            throw new PulpException("Unable to get the response from " + uri.ToString());
                        }

                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream == null)
                            {
                                throw new PulpException("Unable to get the response stream from " + uri.ToString());
                            }

                            // if this is a dry-run request, read the response and return to caller via the parameters
                            if (isDryRun)
                            {
                                var encoding = Encoding.UTF8;
                                using (var reader = new StreamReader(responseStream, encoding))
                                {
                                    parameters[ParameterKeys.DeleteStackJsonEncoded] = reader.ReadToEnd();
                                }
                            }
                        }

                        response.Close();
                    }
                }
                catch (WebException we)
                {
                    // See if we can decode GOServerException
                    var error = GOServerException.FromWebResponse(we);

                    if (error != null)
                    {
                        throw error;
                    }

                    throw;
                }
            }
        }