Esempio n. 1
0
        private void _Redirect(bool endResponse)
        {
            string uri = this.ToString();

            Tracing.FrameworkInformation("UrlBuilder", "Redirect", "Redirecting to: " + uri);
            HttpContext.Current.Response.Redirect(uri, endResponse);
        }
Esempio n. 2
0
        public void Remove(OrganizationServiceCachePluginMessage message)
        {
            if (message.Category != null)
            {
                Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "Category={0}", message.Category.Value);

                Remove(message.Category.Value);
            }

            if (message.Target != null)
            {
                var entity = message.Target.ToEntityReference();

                Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "LogicalName={0}, Id={1}, Name={2}", entity.LogicalName, entity.Id, entity.Name);

                Remove(entity);
            }

            if (message.RelatedEntities != null)
            {
                var relatedEntities = message.RelatedEntities.ToEntityReferenceCollection();

                foreach (var entity in relatedEntities)
                {
                    Tracing.FrameworkInformation("OrganizationServiceCache", "Remove", "LogicalName={0}, Id={1}, Name={2}", entity.LogicalName, entity.Id, entity.Name);

                    Remove(entity);
                }
            }
        }
        protected IAsyncResult ExecuteSelect(
            IOrganizationService client,
            QueryBase query,
            AsyncCallback asyncCallback,
            object asyncState)
        {
            Request.Query = query;

            if (Owner.CacheParameters.Enabled)
            {
                string cacheKey = GetCacheKey(query);

                // try load from cache
                IEnumerable selectResult = ObjectCacheManager.GetInstance().Get(cacheKey) as IEnumerable;

                if (selectResult != null)
                {
                    Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteSelect", "Found in cache: {0}", cacheKey);
                    Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteSelect", "End");

                    return(new SynchronousAsyncSelectResult(selectResult, asyncCallback, asyncState));
                }
            }

            _execute = new Func <QueryBase, EntityCollection>(client.RetrieveMultiple);
            return(_execute.BeginInvoke(query, asyncCallback, asyncState));
        }
Esempio n. 4
0
        IEnumerable IExpandProvider.ApplyExpansions(IQueryable queryable, ICollection <ExpandSegmentCollection> expandPaths)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "ApplyExpansions", "expandPaths={0}", expandPaths);

            // $expand=property1/subproperty1,property2/subproperty2

            if (expandPaths.Count() > 0)
            {
                foreach (var entity in queryable)
                {
                    if (!(entity is Entity))
                    {
                        break;
                    }

                    foreach (var path in expandPaths)
                    {
                        foreach (var segment in path)
                        {
                            LoadProperty(entity as Entity, segment.Name);
                        }
                    }
                }
            }

            return(queryable);
        }
        protected virtual void ProcessJsonRequest(HttpContext context)
        {
            // {
            //  "MessageName":"Update",
            //  "Target":{"LogicalName":"adx_webpageaccesscontrolrule","Id":"40b062c7-1aea-e011-b5b7-001d60c95b1e"}
            // }

            // {
            //  "MessageName":"Associate",
            //  "Target":{"LogicalName":"adx_webpageaccesscontrolrule","Id":"40b062c7-1aea-e011-b5b7-001d60c95b1e"},
            //  "Relationship":{"SchemaName":"adx_webpageaccesscontrolrule_webrole","PrimaryEntityRole":"0"},
            //  "RelatedEntities":[{"LogicalName":"adx_webrole","Id":"bf5420f9-de03-e111-a1a1-00155d03a708"}]
            // }

            var body = GetRequestBody(context);

            if (!string.IsNullOrWhiteSpace(body))
            {
                var message = body.DeserializeByJson(typeof(OrganizationServiceCachePluginMessage), null) as OrganizationServiceCachePluginMessage;

                ThrowOnNull(message, "The plug-in message is unspecified.");

                Tracing.FrameworkInformation(GetType().Name, "ProcessRequest", body);

                foreach (var serviceCache in GetServiceCaches())
                {
                    serviceCache.Remove(message);
                }
            }
        }
        private OrganizationResponse InnerExecute(OrganizationRequest request)
        {
            // unwrap the KeyedRequest

            var innerRequest = (request is KeyedRequest) ? (request as KeyedRequest).Request : request;

            var timer = Stopwatch.StartNew();

            var response = base.Execute(innerRequest);

            timer.Stop();

            Tracing.FrameworkInformation("CachedOrganizationService", "InnerExecute", "{0}: {1} ms", innerRequest.GetType().Name, timer.ElapsedMilliseconds);

            var retrieveMultipleResponse = response as RetrieveMultipleResponse;

            if (retrieveMultipleResponse != null)
            {
                var count = retrieveMultipleResponse.EntityCollection != null &&
                            retrieveMultipleResponse.EntityCollection.Entities != null
                                                ? retrieveMultipleResponse.EntityCollection.Entities.Count
                                                : 0;

                Tracing.FrameworkInformation("CachedOrganizationService", "InnerExecute", "Count: {0}", count);
            }

            return(response);
        }
Esempio n. 7
0
        object IUpdatable.ResetResource(object resource)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "ResetResource", "resource={0}", resource);

            // We do not clear out all attribute values except for the Id and LogicalName
            return(resource);
        }
Esempio n. 8
0
        object IUpdatable.ResolveResource(object resource)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "ResolveResource", "resource={0}", resource);

            // convert the resource from an EntityReference (key) to a full Entity

            var id = resource as EntityReference;

            if (id != null && id.Id != Guid.Empty && !string.IsNullOrWhiteSpace(id.LogicalName))
            {
                return(ResolveObject(id));
            }

            // if the entity does not have a creation date, reload the entity

            var entity = resource as Entity;

            if (entity != null &&
                entity.Id != Guid.Empty &&
                !string.IsNullOrWhiteSpace(entity.LogicalName) &&
                !entity.Attributes.Contains("createdon"))
            {
                return(ResolveObject(entity.ToEntityReference()));
            }

            return(resource);
        }
Esempio n. 9
0
        void IUpdatable.SetValue(object targetResource, string propertyName, object propertyValue)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "SetValue", "targetResource={0}, propertyName={1}, propertyValue={2}", targetResource, propertyName, propertyValue);

            var type = targetResource.GetType();
            var pi   = type.GetProperty(propertyName);

            if (pi == null)
            {
                throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
            }

            if (pi.CanWrite && IsReadOnlyEntityProperty(targetResource, propertyName))
            {
                var value = ParseValue(propertyValue);
                pi.SetValue(targetResource, value, null);

                var target = targetResource as Entity;

                if (target != null)
                {
                    UpdateObject(target);
                }
            }
        }
Esempio n. 10
0
        object IUpdatable.GetResource(IQueryable query, string fullTypeName)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "GetResource", "fullTypeName={0}", fullTypeName);

            object resource = null;

            foreach (var obj in query)
            {
                if (resource != null)
                {
                    throw new DataServiceException("Expected a single response.");
                }

                resource = obj;
            }

            if (fullTypeName != null && resource != null)
            {
                var resourceType = resource.GetType().FullName;

                if (!fullTypeName.Equals(resourceType))
                {
                    throw new DataServiceException("Expected resource of type '{0}' but retrieved a resource of type '{1}' instead.".FormatWith(fullTypeName, resourceType));
                }
            }

            return(resource);
        }
        public void Init(HttpApplication context)
        {
            var provider = _provider.Value;

            Tracing.FrameworkInformation("EmbeddedResourceVirtualPathProviderModule", "Init", "Provider '{0}' registered.", provider);

            context.PostResolveRequestCache += OnMapRequestHandler;
        }
Esempio n. 12
0
        private TResult Disabled <TRequest, TResponse, TResult>(TRequest query, Func <TRequest, TResponse> execute, Func <TResponse, TResult> selector, string selectorCacheKey)
        {
            var cacheKey = GetCacheKey(query, selectorCacheKey);

            Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.Disabled.ToString(), cacheKey);

            return(InnerExecute(query, execute, selector));
        }
Esempio n. 13
0
        void IUpdatable.RemoveReferenceFromCollection(object targetResource, string propertyName, object resourceToBeRemoved)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "RemoveReferenceFromCollection", "targetResource={0}, propertyName={1}, resourceToBeRemoved={2}", targetResource, propertyName, resourceToBeRemoved);

            var relationship = GetRelationship(targetResource, propertyName);

            DeleteLink(targetResource as Entity, relationship, resourceToBeRemoved as Entity);
        }
Esempio n. 14
0
        void IUpdatable.SetReference(object targetResource, string propertyName, object propertyValue)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "SetReference", "targetResource={0}, propertyName={1}, propertyValue={2}", targetResource, propertyName, propertyValue);

            var relationship = GetRelationship(targetResource, propertyName);

            AddLink(targetResource as Entity, relationship, propertyValue as Entity);
        }
Esempio n. 15
0
        void IUpdatable.AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "AddReferenceToCollection", "targetResource={0}, propertyName={1}, resourceToBeAdded={2}", targetResource, propertyName, resourceToBeAdded);

            var relationship = GetRelationship(targetResource, propertyName);

            AddLink(targetResource as Entity, relationship, resourceToBeAdded as Entity);

            AddToLog(UpdatableOperation.AddReferenceToCollection, targetResource as Entity, resourceToBeAdded as Entity, propertyName, null);
        }
Esempio n. 16
0
        public override bool DirectoryExists(string virtualDir)
        {
            var exists =
                ResourceExists(virtualDir, (assembly, resources) => resources.IsDirectory) ||
                Previous.DirectoryExists(virtualDir);

            Tracing.FrameworkInformation("EmbeddedResourceVirtualPathProvider", "DirectoryExists", "virtualDir={0}, exists={1}", virtualDir, exists);

            return(exists);
        }
Esempio n. 17
0
        public override bool FileExists(string virtualPath)
        {
            var exists =
                ResourceExists(virtualPath, (assembly, resources) => resources.IsFile) ||
                Previous.FileExists(virtualPath);

            Tracing.FrameworkInformation("EmbeddedResourceVirtualPathProvider", "FileExists", "virtualPath={0}, exists={1}", virtualPath, exists);

            return(exists);
        }
Esempio n. 18
0
        public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            Tracing.FrameworkInformation("EmbeddedResourceVirtualPathProvider", "GetCacheDependency", "virtualPath={0}, utcStart={1}", virtualPath, utcStart);

            Assembly files = null;

            ResourceExists(virtualPath, (assembly, resources) => { files = assembly; return(true); });

            // create a dependency on the assembly containing the embedded resources

            return(files != null ? new CacheDependency(files.Location, utcStart) : null);
        }
        protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues)
        {
            Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteDelete", "Begin");

            if (!CanDelete)
            {
                throw new NotSupportedException("Delete not supported.");
            }

            var id         = keys["ID"] as Guid?;
            var entityName = keys["Name"] as string;

            if (id == null || entityName == null)
            {
                throw new ArgumentException("Delete requires the 'ID' and 'Name' to be specified as DataKeyNames.", "keys");
            }

            var rowsAffected     = 0;
            var deletedEventArgs = new CrmDataSourceViewDeletedEventArgs();

            try
            {
                var entity = _crmDataContext.Retrieve(entityName, id.Value, new ColumnSet(true));

                if (entity == null)
                {
                    throw new NullReferenceException("The {0} entity with ID='{1}' could not be found.".FormatWith(id, entityName));
                }

                _crmDataContext.Attach(entity);

                _crmDataContext.DeleteObject(entity);

                var result = _crmDataContext.SaveChanges();

                rowsAffected = result.HasError ? 0 : 1;
            }
            catch (Exception e)
            {
                Tracing.FrameworkError("CrmDataSourceView", "ExecuteDelete", "{0}", e);

                deletedEventArgs.Exception        = e;
                deletedEventArgs.ExceptionHandled = true;
            }

            Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteDelete", "End");

            OnDeleted(deletedEventArgs);

            return(rowsAffected);
        }
Esempio n. 20
0
        object IUpdatable.GetValue(object targetResource, string propertyName)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "GetValue", "targetResource={0}, propertyName={1}", targetResource, propertyName);

            var type = targetResource.GetType();
            var pi   = type.GetProperty(propertyName);

            if (pi == null)
            {
                throw new DataServiceException("The target resource of type '{0}' does not contain a property named '{1}'.".FormatWith(type, propertyName));
            }

            return(pi.GetValue(targetResource, null));
        }
Esempio n. 21
0
        private RouteCollection Register()
        {
            var mappings = Utility.GetEmbeddedResourceMappingAttributes().ToList();
            var paths    = GetPaths().ToArray();

            var routes = Register(
                RouteTable.Routes,
                new PortalRouteHandler(PortalName),
                new EmbeddedResourceRouteHandler(mappings),
                new CompositeEmbeddedResourceRouteHandler(mappings, paths));

            Tracing.FrameworkInformation("PortalRoutingModule", "Init", "Added '{0}' route entries.", routes.Count);

            return(routes);
        }
        public override void Delete(string entityName, Guid id)
        {
            var timer = Stopwatch.StartNew();

            base.Delete(entityName, id);

            if (Cache != null)
            {
                Cache.Remove(entityName, id);
            }

            timer.Stop();

            Tracing.FrameworkInformation("CachedOrganizationService", "Delete", "id={0}: {1} ms", id, timer.ElapsedMilliseconds);
        }
        public override void Update(Entity entity)
        {
            var timer = Stopwatch.StartNew();

            base.Update(entity);

            if (Cache != null)
            {
                Cache.Remove(entity);
            }

            timer.Stop();

            Tracing.FrameworkInformation("CachedOrganizationService", "Update", "{0} ms", timer.ElapsedMilliseconds);
        }
Esempio n. 24
0
        private TResult LookupAndInsert <TRequest, TResponse, TResult>(TRequest query, Func <TRequest, TResponse> execute, Func <TResponse, TResult> selector, string selectorCacheKey)
        {
            var cacheKey = GetCacheKey(query, selectorCacheKey);

            var response = Cache.Get(cacheKey,
                                     cache =>
            {
                Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.LookupAndInsert.ToString(), cacheKey);
                return(InnerExecute(query, execute, selector));
            },
                                     (cache, result) => Insert(cacheKey, query, result),
                                     CacheRegionName);

            return(ReturnMode == OrganizationServiceCacheReturnMode.Cloned ? CloneResponse(response) : response);
        }
        /// <summary>
        /// Provides the object that processes the request.
        /// </summary>
        /// <param name="requestContext">An object that encapsulates information about the request.</param>
        /// <returns></returns>
        public virtual IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            var portal = PortalCrmConfigurationManager.CreatePortalContext(PortalName, requestContext);

            portal = OnPortalLoaded(requestContext, portal);

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

            var isInvalidNode = portal.Entity == null || portal.Path == null;

            // there's nothing else we can really do--we'll exit with a bare-bones 404.
            if (isInvalidNode)
            {
                Tracing.FrameworkInformation("PortalRouteHandler", "GetHttpHandler", "FindSiteMapNode failed to find a non-null CrmSiteMapNode. Responding with a basic 404.");

                RenderNotFound(requestContext);

                return(null);
            }

            if (portal.StatusCode == HttpStatusCode.NotFound)
            {
                var response = requestContext.HttpContext.Response;
                response.StatusCode = (int)HttpStatusCode.NotFound;
            }

            IHttpHandler handler;

            if (TryCreateHandler(portal, out handler))
            {
                return(handler);
            }

            // remove the querystring

            var rewritePath = portal.Path;
            var index       = rewritePath.IndexOf("?");
            var path        = index > -1 ? rewritePath.Substring(0, index) : rewritePath;

            Tracing.FrameworkInformation("PortalRouteHandler", "GetHttpHandler", "path={0}".FormatWith(path));

            return(CreateHandlerFromVirtualPath(path));
        }
        protected override int ExecuteInsert(IDictionary values)
        {
            Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteInsert", "Begin");

            if (!CanInsert)
            {
                throw new NotSupportedException("Insert not supported.");
            }

            string entityName = values["EntityName"] as string;

            if (string.IsNullOrEmpty(entityName))
            {
                throw new ArgumentException("Insert requires an 'EntityName' to be specified as one of the values.", "values");
            }

            var entity = new Entity(entityName);

            SetEntityAttributes(entity, values);

            var rowsAffected      = 0;
            var insertedEventArgs = new CrmDataSourceViewInsertedEventArgs();

            try
            {
                _crmDataContext.AddObject(entity);
                _crmDataContext.SaveChanges();

                insertedEventArgs.EntityId = entity.Id;

                rowsAffected = 1;
            }
            catch (Exception e)
            {
                Tracing.FrameworkError("CrmDataSourceView", "ExecuteInsert", "{0}", e);

                insertedEventArgs.Exception        = e;
                insertedEventArgs.ExceptionHandled = true;
            }

            Tracing.FrameworkInformation("CrmDataSourceView", "ExecuteInsert", "End: rowsAffected={0}", rowsAffected);

            OnInserted(insertedEventArgs);

            return(rowsAffected);
        }
Esempio n. 27
0
        object IUpdatable.CreateResource(string containerName, string fullTypeName)
        {
            Tracing.FrameworkInformation("CrmOrganizationServiceContext", "CreateResource", "containerName={0}, fullTypeName={1}", containerName, fullTypeName);

            var entityType = TypeExtensions.GetType(fullTypeName);

            if (entityType.IsA(typeof(Entity)))
            {
                var entity = Activator.CreateInstance(entityType) as Entity;

                AddObject(entity);

                return(entity);
            }

            return(Activator.CreateInstance(entityType));
        }
        public override Guid Create(Entity entity)
        {
            var timer = Stopwatch.StartNew();

            var id = base.Create(entity);

            if (Cache != null)
            {
                Cache.Remove(entity);
            }

            timer.Stop();

            Tracing.FrameworkInformation("CachedOrganizationService", "Create", "id={0}: {1} ms", id, timer.ElapsedMilliseconds);

            return(id);
        }
Esempio n. 29
0
        private TResult InsertOnly <TRequest, TResponse, TResult>(TRequest query, Func <TRequest, TResponse> execute, Func <TResponse, TResult> selector, string selectorCacheKey)
        {
            var cacheKey = GetCacheKey(query, selectorCacheKey);
            var result   = default(TResult);

            LockManager.Lock(
                cacheKey,
                () =>
            {
                Tracing.FrameworkInformation("OrganizationServiceCache", OrganizationServiceCacheMode.InsertOnly.ToString(), cacheKey);

                result = InnerExecute(query, execute, selector);

                Insert(cacheKey, query, result);
            });

            return(result);
        }
        private string GetCacheKey(QueryBase query)
        {
            if (_cacheKey == null)
            {
                CacheParameters cacheParameters = Owner.GetCacheParameters();
                _cacheKey = cacheParameters.CacheKey.GetCacheKey(
                    Context,
                    Owner,
                    Owner,
                    delegate
                {
                    string serializedQuery = Serialize(query);
                    Tracing.FrameworkInformation("CrmDataSourceView", "GetCacheKey: QueryByAttribute", serializedQuery.GetHashCode().ToString(CultureInfo.InvariantCulture));
                    return("Adxstudio:Type={0}:ID={1}:Hash={2}".FormatWith(Owner.GetType().FullName, Owner.ID, serializedQuery.GetHashCode()));
                });
            }

            return(_cacheKey);
        }