public static DSResource CreateResourceWithKeyAndReferenceSetCmdlets(ResourceType resourceType, Dictionary <string, object> keyProperties, EntityMetadata entityMetadata)
        {
            DSResource dSResource = ResourceTypeExtensions.CreateKeyOnlyResource(resourceType, keyProperties);

            if (dSResource != null)
            {
                PSEntityMetadata pSEntityMetadatum = entityMetadata as PSEntityMetadata;
                ReadOnlyCollection <ResourceProperty> properties = resourceType.Properties;
                foreach (ResourceProperty resourceProperty in properties.Where <ResourceProperty>((ResourceProperty it) => (it.Kind & ResourcePropertyKind.ResourceSetReference) == ResourcePropertyKind.ResourceSetReference))
                {
                    PSEntityMetadata.ReferenceSetCmdlets referenceSetCmdlet = null;
                    if (!pSEntityMetadatum.CmdletsForReferenceSets.TryGetValue(resourceProperty.Name, out referenceSetCmdlet) || !referenceSetCmdlet.Cmdlets.ContainsKey(CommandType.GetReference))
                    {
                        continue;
                    }
                    if (referenceSetCmdlet.GetRefHidden)
                    {
                        dSResource.SetValue(resourceProperty.Name, null);
                    }
                    else
                    {
                        PSReferencedResourceSet pSReferencedResourceSet = new PSReferencedResourceSet(resourceProperty, resourceType);
                        dSResource.SetValue(resourceProperty.Name, pSReferencedResourceSet);
                    }
                }
                return(dSResource);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 2
0
        public void UpdateResource(string token, DSResource resource)
        {
            if (resource == null)
            {
                throw new ArgumentException("resource must be specified");
            }
            if (!resource.ContainsKey("ObjectID"))
            {
                throw new ArgumentException("resource object id must be specified");
            }

            ResourceManagementClient client = Utiles.GetClient(repoCache, token);

            //ResourceObject ro =
            //    client.CreateResourceTemplateForUpdate(resource.ObjectType, new UniqueIdentifier(resource.ObjectID));

            ResourceObject ro = client.GetResource(resource.ObjectID, resource.Keys);

            Utiles.BuildResourceObject(resource, ref ro);

            try
            {
                ro.Save();
            }
            catch (AuthorizationRequiredException e)
            {
                throw new AuthZRequiredException(e.Message);
            }
        }
Esempio n. 3
0
        public static void BuildResourceObject(DSResource dsResource, ref ResourceObject resource)
        {
            foreach (KeyValuePair <string, object> kvp in dsResource)
            {
                AttributeValue attribute = resource.Attributes.FirstOrDefault(a => a.AttributeName.Equals(kvp.Key));

                if (attribute != null)
                {
                    // skip the ObjectID and ObjectType attributes, because they are readonly
                    if (kvp.Key.Equals("ObjectID") || kvp.Key.Equals("ObjectType"))
                    {
                        continue;
                    }

                    resource.Attributes[kvp.Key].SetValue(kvp.Value);

                    // obsoleted, because ObjectDictionaryConverter was added to Startup.cs
                    //if (kvp.Value is JArray arr)
                    //{
                    //    resource.Attributes[kvp.Key].SetValue(arr.ToObject<string[]>());
                    //}
                    //else
                    //{
                    //    resource.Attributes[kvp.Key].SetValue(kvp.Value);
                    //}
                }
                // attributes which are not defined in schema will cause an exception
                // if uncomment this, they will be ignored and no exceoption will be thrown
                else
                {
                    throw new ArgumentException($"invalid attribute: {kvp.Key}");
                }
            }
        }
Esempio n. 4
0
        public IHttpActionResult CreateResource(string connectionInfo, DSResource resource)
        {
            try
            {
                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    ConnectionInfo ci = ConnectionInfo.BuildConnectionInfo(connectionInfo);
                    ResourceOption ro = new ResourceOption(ci);

                    string id = repo.Value.CreateResource(resource, ro);

                    return(Ok(id));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
        }
Esempio n. 5
0
		public bool Extract(Expression tree, IQueryable<DSResource> resourceRoot, ResourceType resourceType, EntityMetadata entityMetadata)
		{
			this.resourceRoot = resourceRoot;
			this.entityMetadata = entityMetadata;
			this.navigationProperty = null;
			this.referredEntityKeys = new Dictionary<string, object>();
			this.referringEntityKeys = new Dictionary<string, object>();
			this.currentState = ReferredResourceExtractor.ExtractionState.ExtractingReferredEntityInfo;
			this.Visit(tree);
			if (this.currentState == ReferredResourceExtractor.ExtractionState.ExtractingReferringEntityInfo)
			{
				DSResource dSResource = ResourceTypeExtensions.CreateKeyOnlyResource(resourceType, this.referringEntityKeys);
				if (dSResource != null)
				{
					this.ReferredResource = ResourceTypeExtensions.CreateKeyOnlyResource(this.navigationProperty.ResourceType, this.referredEntityKeys);
					if (this.ReferredResource != null)
					{
						this.currentState = ReferredResourceExtractor.ExtractionState.ExtractionDone;
					}
				}
			}
			if (this.currentState != ReferredResourceExtractor.ExtractionState.ExtractionDone)
			{
				this.currentState = ReferredResourceExtractor.ExtractionState.ExtractionFailed;
			}
			return this.currentState == ReferredResourceExtractor.ExtractionState.ExtractionDone;
		}
Esempio n. 6
0
        public IHttpActionResult CreateResource(string encryptionKey, DSResource resource)
        {
            try
            {
                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (!encryptionKey.Equals(this.encryptionKey))
                {
                    return(InternalServerError(new Exception("Invalid Encryption Key")));
                }

                if (repo != null)
                {
                    ConnectionInfo ci = ConnectionInfo.BuildConnectionInfo(this.adminConnection);
                    ResourceOption ro = new ResourceOption(ci);

                    string id = repo.Value.CreateResource(resource, ro);

                    return(Ok(id));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
        }
Esempio n. 7
0
        public IHttpActionResult UpdateResource(string connectionInfo, DSResource resource, bool isDelta = false)
        {
            try
            {
                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    ConnectionInfo ci = ConnectionInfo.BuildConnectionInfo(connectionInfo);
                    ResourceOption ro = new ResourceOption(ci);

                    string id = repo.Value.UpdateResource(resource, isDelta, ro);

                    if (id.Equals("AuthorizationRequired"))
                    {
                        return(Content(HttpStatusCode.PartialContent, id));
                    }

                    return(Ok(id));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
        }
Esempio n. 8
0
        public IHttpActionResult GetResourceByID(
            string connectionInfo, string id, [FromUri] string[] attributesToGet = null,
            bool includePermission = false, int cultureKey = 127, bool resolveID = false, bool deepResolve = false,
            [FromUri] string[] attributesToResolve = null)
        {
            try
            {
                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    ConnectionInfo ci = ConnectionInfo.BuildConnectionInfo(connectionInfo);
                    ResourceOption ro = new ResourceOption(ci, cultureKey, resolveID, deepResolve, attributesToResolve);

                    DSResource rs = repo.Value.GetResourceByID(id, (attributesToGet == null || attributesToGet.Length == 0) ? new string[] { "DisplayName" } : attributesToGet, includePermission, ro);

                    return(Ok(rs));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
        }
Esempio n. 9
0
        public IHttpActionResult CreateResource(DSResource resource)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = ((WindowsIdentity)User.Identity).Impersonate();

                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    string id = repo.Value.CreateResource(resource);

                    return(Ok(id));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Esempio n. 10
0
        public async Task <ActionResult <string> > UpdateResource(
            [FromHeader, Required] string token,
            [FromBody] DSResource resource)
        {
            try
            {
                await Task.Run(() =>
                {
                    this.repo.UpdateResource(token, resource);
                });

                return(Ok());
            }
            catch (ArgumentException e)
            {
                return(this.BadRequest(e.Message));
            }
            catch (InvalidOperationException e)
            {
                return(this.Conflict(e.Message));
            }
            catch (AuthZRequiredException e)
            {
                return(Accepted(e.Message));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
        }
Esempio n. 11
0
        public async Task <ActionResult <DSResource> > GetResourceByID(
            [FromHeader, Required] string token,
            [FromRoute] string id,
            [FromQuery] string attributes,
            [FromQuery] string culture  = "en-US",
            [FromQuery] bool resolveRef = false,
            [FromQuery] string format   = "simple")
        {
            try
            {
                DSResource result = await Task.Run(() =>
                {
                    string[] attributeArray = string.IsNullOrEmpty(attributes) ? null :
                                              attributes.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray();

                    bool includePermission = format.Equals("full", StringComparison.OrdinalIgnoreCase) ? true : false;

                    return(this.repo.GetResourceByID(token, id, attributeArray, culture, includePermission, resolveRef));
                });

                return(result);
            }
            catch (ArgumentException e)
            {
                return(this.BadRequest(e.Message));
            }
            catch (InvalidOperationException e)
            {
                return(this.Conflict(e.Message));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
        }
Esempio n. 12
0
		public ReferredEntityInstance(DSResource resource, UserContext userContext, ResourceType type, EntityMetadata metadata, string membershipId)
		{
			this.userContext = userContext;
			this.resourceType = type;
			this.metadata = metadata;
			this.membershipId = membershipId;
			this.resource = resource;
		}
Esempio n. 13
0
        public override object Serialize(object clrObject, int depth)
        {
            object value;

            if (depth != 10)
            {
                ResourceType resourceType = base.ResourceType;
                if (clrObject != null)
                {
                    resourceType = base.ResourceType.FindResourceType(clrObject.GetType());
                }
                DSResource dSResource = new DSResource(resourceType, false);
                foreach (ResourceProperty property in resourceType.Properties)
                {
                    if (clrObject != null)
                    {
                        value = SerializerBase.GetValue(property, clrObject);
                    }
                    else
                    {
                        value = null;
                    }
                    object obj = value;
                    if (obj != null || !property.ResourceType.IsPrimitive() || property.ResourceType.IsNullable())
                    {
                        if (obj != null || (property.Kind & (ResourcePropertyKind.Primitive | ResourcePropertyKind.ResourceReference)) == 0)
                        {
                            if (clrObject != null || (property.Kind & ResourcePropertyKind.ComplexType) == 0)
                            {
                                dSResource.SetValue(property.Name, SerializerBase.SerializeResourceProperty(obj, base.ResourceType, property, depth + 1));
                            }
                            else
                            {
                                TraceHelper.Current.DebugMessage(string.Concat(property.Name, " setting null to ComplexType"));
                                dSResource.SetValue(property.Name, null);
                            }
                        }
                        else
                        {
                            TraceHelper.Current.DebugMessage(string.Concat(property.Name, " is null; skipping"));
                        }
                    }
                    else
                    {
                        object[] name = new object[1];
                        name[0] = property.Name;
                        throw new PSObjectSerializationFailedException(string.Format(CultureInfo.CurrentCulture, Resources.PropertyNotFoundInPSObject, name));
                    }
                }
                return(dSResource);
            }
            else
            {
                TraceHelper.Current.SerializationMaximumObjectDepthReached();
                return(null);
            }
        }
Esempio n. 14
0
        internal DSResource MakeDsResource()
        {
            TraceHelper.Current.DebugMessage("MakeDsResource entering");
            this.Trace("Inside MakeDsResource");
            DSResource dSResource = SerializerBase.SerializeEntity(this, this.entityType);

            TraceHelper.Current.DebugMessage("MakeDsResource exiting");
            return(dSResource);
        }
Esempio n. 15
0
		public override object Serialize(object clrObject, int depth)
		{
			object value;
			if (depth != 10)
			{
				ResourceType resourceType = base.ResourceType;
				if (clrObject != null)
				{
					resourceType = base.ResourceType.FindResourceType(clrObject.GetType());
				}
				DSResource dSResource = new DSResource(resourceType, false);
				foreach (ResourceProperty property in resourceType.Properties)
				{
					if (clrObject != null)
					{
						value = SerializerBase.GetValue(property, clrObject);
					}
					else
					{
						value = null;
					}
					object obj = value;
					if (obj != null || !property.ResourceType.IsPrimitive() || property.ResourceType.IsNullable())
					{
						if (obj != null || (property.Kind & (ResourcePropertyKind.Primitive | ResourcePropertyKind.ResourceReference)) == 0)
						{
							if (clrObject != null || (property.Kind & ResourcePropertyKind.ComplexType) == 0)
							{
								dSResource.SetValue(property.Name, SerializerBase.SerializeResourceProperty(obj, base.ResourceType, property, depth + 1));
							}
							else
							{
								TraceHelper.Current.DebugMessage(string.Concat(property.Name, " setting null to ComplexType"));
								dSResource.SetValue(property.Name, null);
							}
						}
						else
						{
							TraceHelper.Current.DebugMessage(string.Concat(property.Name, " is null; skipping"));
						}
					}
					else
					{
						object[] name = new object[1];
						name[0] = property.Name;
						throw new PSObjectSerializationFailedException(string.Format(CultureInfo.CurrentCulture, Resources.PropertyNotFoundInPSObject, name));
					}
				}
				return dSResource;
			}
			else
			{
				TraceHelper.Current.SerializationMaximumObjectDepthReached();
				return null;
			}
		}
Esempio n. 16
0
		public EntityUpdate(UserContext userContext, ResourceType type, EntityMetadata metadata, string membershipId)
		{
			this.userContext = userContext;
			this.resourceType = type;
			this.metadata = metadata;
			this.commandType = CommandType.Create;
			this.query = null;
			this.membershipId = membershipId;
			this.propertyUpdates = new SortedDictionary<string, object>();
			this.updatedResource = null;
			this.resolveResource = null;
		}
Esempio n. 17
0
        public static bool ValidateSchema(ResourceObject schemaObject, DSResource resource, out string errorAttribute)
        {
            foreach (string attributeName in resource.Keys)
            {
                if (schemaObject.Attributes.FirstOrDefault(a => a.AttributeName.Equals(attributeName)) == null)
                {
                    errorAttribute = attributeName;
                    return(false);
                }
            }

            errorAttribute = string.Empty;
            return(true);
        }
Esempio n. 18
0
        public string CreateResource(DSResource resource, ResourceOption resourceOption = null)
        {
            ResourceOption option = resourceOption == null ? new ResourceOption() : resourceOption;

            ResourceManagementClient client = getClient(option.ConnectionInfo);

            ResourceObject objResource = client.CreateResource(resource.ObjectType);

            convertToResourceObject(resource, ref objResource);

            objResource.Save();

            return(objResource.ObjectID.Value);
        }
Esempio n. 19
0
        public static DSResource CreateKeyOnlyResource(ResourceType resourceType, Dictionary <string, object> inputKeys)
        {
            DSResource dSResource;
            ReadOnlyCollection <ResourceProperty> properties         = resourceType.Properties;
            IEnumerable <ResourceProperty>        resourceProperties = properties.Where <ResourceProperty>((ResourceProperty it) => (it.Kind & ResourcePropertyKind.Key) == ResourcePropertyKind.Key);
            IEnumerable <string> strs = resourceProperties.Select <ResourceProperty, string>((ResourceProperty it) => it.Name);

            if (inputKeys.Count == strs.Count <string>())
            {
                DSResource dSResource1 = new DSResource(resourceType, true);
                Dictionary <string, object> .Enumerator enumerator = inputKeys.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        KeyValuePair <string, object> current = enumerator.Current;
                        if (strs.Contains <string>(current.Key))
                        {
                            dSResource1.SetValue(current.Key, current.Value);
                        }
                        else
                        {
                            TraceHelper.Current.DebugMessage(string.Concat("CreateKeyOnlyResource: Returning null. Property ", current.Key, " is not key in the resource ", resourceType.Name));
                            dSResource = null;
                            return(dSResource);
                        }
                    }
                    return(dSResource1);
                }
                finally
                {
                    enumerator.Dispose();
                }
                return(dSResource);
            }
            else
            {
                object[] name = new object[4];
                name[0] = "CreateKeyOnlyResource: Number of keys of ResourceType and inside properties does not match. Returning null. \nResource type name ";
                name[1] = resourceType.Name;
                name[2] = "\nInput Properties count: ";
                name[3] = inputKeys.Count;
                TraceHelper.Current.DebugMessage(string.Concat(name));
                return(null);
            }
        }
Esempio n. 20
0
        public static DSResource SerializeEntity(object instance, ResourceType resourceType)
        {
            object[] resourceTypeKind = new object[2];
            resourceTypeKind[0] = resourceType.ResourceTypeKind;
            resourceTypeKind[1] = ResourceTypeKind.EntityType;
            ExceptionHelpers.ThrowArgumentExceptionIf("resourceType", resourceType.ResourceTypeKind != ResourceTypeKind.EntityType, new ExceptionHelpers.MessageLoader(SerializerBase.GetInvalidArgMessage), resourceTypeKind);
            DSResource dSResource = SerializerBase.SerializeResourceType(instance, resourceType, 1) as DSResource;

            if (dSResource != null)
            {
                return(dSResource);
            }
            else
            {
                throw new InvalidOperationException(Resources.SerializeEntityReturnedNull);
            }
        }
Esempio n. 21
0
        public override object Serialize(object clrObject, int depth)
        {
            object obj;

            if (clrObject != null)
            {
                DSResource dSResource = new DSResource(base.ResourceType, true);
                if (this.referencePropertyType != PSEntityMetadata.ReferenceSetCmdlets.ReferencePropertyType.KeyOnly)
                {
                    EntityTypeSerializer entityTypeSerializer = new EntityTypeSerializer(base.ResourceType, true);
                    dSResource = entityTypeSerializer.Serialize(clrObject, depth + 1) as DSResource;
                }
                else
                {
                    IEnumerator <ResourceProperty> enumerator = base.ResourceType.Properties.GetEnumerator();
                    using (enumerator)
                    {
                        while (enumerator.MoveNext())
                        {
                            ResourceProperty current = enumerator.Current;
                            if ((current.Kind & ResourcePropertyKind.Key) != ResourcePropertyKind.Key)
                            {
                                continue;
                            }
                            if (clrObject != current.GetCustomState().DefaultValue)
                            {
                                object obj1 = clrObject;
                                dSResource.SetValue(current.Name, SerializerBase.SerializeResourceProperty(obj1, base.ResourceType, current, depth + 1));
                            }
                            else
                            {
                                obj = null;
                                return(obj);
                            }
                        }
                        return(dSResource);
                    }
                    return(obj);
                }
                return(dSResource);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 22
0
		public static DSResource CreateKeyOnlyResource(ResourceType resourceType, Dictionary<string, object> inputKeys)
		{
			DSResource dSResource;
			ReadOnlyCollection<ResourceProperty> properties = resourceType.Properties;
			IEnumerable<ResourceProperty> resourceProperties = properties.Where<ResourceProperty>((ResourceProperty it) => (it.Kind & ResourcePropertyKind.Key) == ResourcePropertyKind.Key);
			IEnumerable<string> strs = resourceProperties.Select<ResourceProperty, string>((ResourceProperty it) => it.Name);
			if (inputKeys.Count == strs.Count<string>())
			{
				DSResource dSResource1 = new DSResource(resourceType, true);
				Dictionary<string, object>.Enumerator enumerator = inputKeys.GetEnumerator();
				try
				{
					while (enumerator.MoveNext())
					{
						KeyValuePair<string, object> current = enumerator.Current;
						if (strs.Contains<string>(current.Key))
						{
							dSResource1.SetValue(current.Key, current.Value);
						}
						else
						{
							TraceHelper.Current.DebugMessage(string.Concat("CreateKeyOnlyResource: Returning null. Property ", current.Key, " is not key in the resource ", resourceType.Name));
							dSResource = null;
							return dSResource;
						}
					}
					return dSResource1;
				}
				finally
				{
					enumerator.Dispose();
				}
				return dSResource;
			}
			else
			{
				object[] name = new object[4];
				name[0] = "CreateKeyOnlyResource: Number of keys of ResourceType and inside properties does not match. Returning null. \nResource type name ";
				name[1] = resourceType.Name;
				name[2] = "\nInput Properties count: ";
				name[3] = inputKeys.Count;
				TraceHelper.Current.DebugMessage(string.Concat(name));
				return null;
			}
		}
Esempio n. 23
0
		public override object Serialize(object clrObject, int depth)
		{
			object obj;
			if (clrObject != null)
			{
				DSResource dSResource = new DSResource(base.ResourceType, true);
				if (this.referencePropertyType != PSEntityMetadata.ReferenceSetCmdlets.ReferencePropertyType.KeyOnly)
				{
					EntityTypeSerializer entityTypeSerializer = new EntityTypeSerializer(base.ResourceType, true);
					dSResource = entityTypeSerializer.Serialize(clrObject, depth + 1) as DSResource;
				}
				else
				{
					IEnumerator<ResourceProperty> enumerator = base.ResourceType.Properties.GetEnumerator();
					using (enumerator)
					{
						while (enumerator.MoveNext())
						{
							ResourceProperty current = enumerator.Current;
							if ((current.Kind & ResourcePropertyKind.Key) != ResourcePropertyKind.Key)
							{
								continue;
							}
							if (clrObject != current.GetCustomState().DefaultValue)
							{
								object obj1 = clrObject;
								dSResource.SetValue(current.Name, SerializerBase.SerializeResourceProperty(obj1, base.ResourceType, current, depth + 1));
							}
							else
							{
								obj = null;
								return obj;
							}
						}
						return dSResource;
					}
					return obj;
				}
				return dSResource;
			}
			else
			{
				return null;
			}
		}
Esempio n. 24
0
        public void convertToResourceObject(DSResource dsResource, ref ResourceObject objResource, bool delta = false)
        {
            foreach (KeyValuePair <string, DSAttribute> kvp in dsResource.Attributes)
            {
                if (delta && !kvp.Value.IsDirty)
                {
                    continue;
                }

                if (kvp.Value.IsMultivalued)
                {
                    objResource.Attributes[kvp.Key].SetValue(kvp.Value.Values);
                }
                else
                {
                    objResource.Attributes[kvp.Key].SetValue(kvp.Value.Value);
                }
            }
        }
Esempio n. 25
0
        public static DSResource BuildSimpleResource(
            ResourceObject resourceObject, List <string> attributesToLoad, ResourceManagementClient client)
        {
            if (resourceObject == null)
            {
                throw new ArgumentException("resource object must be specified");
            }

            DSResource result = new DSResource();

            if (attributesToLoad != null)
            {
                if (!attributesToLoad.Contains("DisplayName"))
                {
                    attributesToLoad.Add("DisplayName");
                }
                if (!attributesToLoad.Contains("ObjectID"))
                {
                    attributesToLoad.Add("ObjectID");
                }
                if (!attributesToLoad.Contains("ObjectType"))
                {
                    attributesToLoad.Add("ObjectType");
                }

                foreach (string attributeName in attributesToLoad)
                {
                    AttributeValue value = resourceObject.Attributes.FirstOrDefault(a => a.AttributeName.Equals(attributeName));

                    buildAttribute(attributeName, value, client, ref result);
                }
            }
            else
            {
                foreach (AttributeValue attributeValue in resourceObject.Attributes)
                {
                    buildAttribute(attributeValue.AttributeName, attributeValue, client, ref result);
                }
            }


            return(result);
        }
Esempio n. 26
0
 private void DataAddedEventHandler(object obj, DataAddedEventArgs eventArgs)
 {
     TraceHelper.Current.Correlate();
     lock (this.syncObject)
     {
         if (!this.isExceedsMaxExecutionTime)
         {
             PSDataCollection <PSObject> pSObjects = obj as PSDataCollection <PSObject>;
             if (pSObjects != null)
             {
                 DSResource dSResource = SerializerBase.SerializeEntity(pSObjects[eventArgs.Index], this.entityType);
                 this.dataStore.Add(dSResource);
             }
         }
         else
         {
             throw new DataServiceException();
         }
     }
 }
Esempio n. 27
0
        public async Task <ActionResult <string> > UpdateResource(
            [FromHeader, Required] string token,
            [FromBody] DSResource resource)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = ((WindowsIdentity)User.Identity).Impersonate();

                await Task.Run(() =>
                {
                    this.repo.UpdateResource(token, resource);
                });

                return(Ok());
            }
            catch (ArgumentException e)
            {
                return(this.BadRequest(e.Message));
            }
            catch (InvalidOperationException e)
            {
                return(this.Conflict(e.Message));
            }
            catch (AuthZRequiredException e)
            {
                return(Accepted(e.Message));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Esempio n. 28
0
        public string UpdateResource(DSResource resource, bool isDelta = false, ResourceOption resourceOption = null)
        {
            ResourceOption option = resourceOption == null ? new ResourceOption() : resourceOption;

            ResourceManagementClient client = getClient(option.ConnectionInfo);

            ResourceObject objResource = client.CreateResourceTemplateForUpdate(
                resource.ObjectType, new UniqueIdentifier(resource.ObjectID));

            convertToResourceObject(resource, ref objResource, isDelta);

            try
            {
                objResource.Save();
            }
            catch (AuthorizationRequiredException)
            {
                return("AuthorizationRequired");
            }

            return(objResource.ObjectID.Value);
        }
Esempio n. 29
0
        public async Task <ActionResult <string> > UpdateResource(
            [FromHeader, Required] string secret,
            [FromBody] DSResource resource)
        {
            try
            {
                await Task.Run(() =>
                {
                    try
                    {
                        if (!this.initAdminAccess(secret))
                        {
                            throw new ArgumentException("invalid secret");
                        }
                    }
                    catch
                    {
                        throw new ArgumentException("invalid secret");
                    }

                    this.repo.UpdateResource(secretToken, resource);
                });

                return(Ok());
            }
            catch (ArgumentException e)
            {
                return(this.BadRequest(e.Message));
            }
            catch (AuthZRequiredException e)
            {
                return(Accepted(e.Message));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
        }
Esempio n. 30
0
        public IHttpActionResult GetResourceByID(
            string id, [FromUri] string[] attributesToGet = null, bool includePermission = false,
            int cultureKey = 127, bool resolveID = false, bool deepResolve = false,
            [FromUri] string[] attributesToResolve = null)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = ((WindowsIdentity)User.Identity).Impersonate();

                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    ResourceOption ro = new ResourceOption(new ConnectionInfo(), cultureKey, resolveID, deepResolve, attributesToResolve);

                    DSResource rs = repo.Value.GetResourceByID(id, (attributesToGet == null || attributesToGet.Length == 0) ? new string[] { "DisplayName" } : attributesToGet, includePermission, ro);

                    return(Ok(rs));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Esempio n. 31
0
        public IHttpActionResult UpdateResource(DSResource resource, bool isDelta = false)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = ((WindowsIdentity)User.Identity).Impersonate();

                Lazy <IOCGDSRepository> repo = RepositoryManager.GetRepository(repos, "MIMResource");

                if (repo != null)
                {
                    string id = repo.Value.UpdateResource(resource, isDelta);

                    if (id.Equals("AuthorizationRequired"))
                    {
                        return(Content(HttpStatusCode.PartialContent, id));
                    }

                    return(Ok(id));
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception exp)
            {
                return(InternalServerError(exp));
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
Esempio n. 32
0
        public async Task <ActionResult <DSResource> > GetCurrentBasicUser(
            [FromHeader, Required] string secret,
            [FromQuery, Required] string accountName,
            [FromQuery] string attributes)
        {
            try
            {
                DSResource result = await Task.Run(() =>
                {
                    try
                    {
                        if (!this.initAdminAccess(secret))
                        {
                            throw new ArgumentException("invalid secret");
                        }
                    }
                    catch
                    {
                        throw new ArgumentException("invalid secret");
                    }

                    string[] attributeArray = string.IsNullOrEmpty(attributes) ? null :
                                              attributes.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray();

                    return(this.repo.GetCurrentUser(secretToken, accountName, attributeArray));
                });

                return(result);
            }
            catch (ArgumentException e)
            {
                return(this.BadRequest(e.Message));
            }
            catch (Exception e)
            {
                return(this.BadRequest(e.Message));
            }
        }
Esempio n. 33
0
        private void ExecutionCompletionEventHandler(IAsyncResult ar)
        {
            Exception dataServiceException;

            lock (this.syncObject)
            {
                this.timer.Stop();
                this.isExecutionCompleted = true;
                if (!this.isExceedsMaxExecutionTime)
                {
                    dataServiceException = PSCommand.CheckPowershellForException(this.cmdletInfo.CmdletName, this.commandType, this.powerShell);
                }
                else
                {
                    object[] cmdletName = new object[1];
                    cmdletName[0]        = this.cmdletInfo.CmdletName;
                    dataServiceException = new DataServiceException(0x193, ExceptionHelpers.GetDataServiceExceptionMessage(HttpStatusCode.Forbidden, Resources.CmdletExecutionQuotaExceeded, cmdletName));
                    TraceHelper.Current.CommandExecutionTimeExceeded(this.cmdletInfo.CmdletName, this.runspace.Borrower.Name, DataServiceController.Current.Configuration.PowerShell.Quotas.MaxExecutionTime, 0);
                    DataServiceController.Current.PerfCounters.SystemQuotaViolationsPerSec.Increment();
                    DataServiceController.Current.QuotaSystem.SystemQuotaViolation.Increment();
                }
                if (this.output != null && dataServiceException == null)
                {
                    foreach (PSObject pSObject in this.output)
                    {
                        if (pSObject == null)
                        {
                            continue;
                        }
                        DSResource dSResource = SerializerBase.SerializeEntity(pSObject, this.entityType);
                        this.dataStore.Add(dSResource);
                    }
                }
                this.dataStore.Completed(dataServiceException);
                this.powerShell.Trace();
            }
            this.Dispose();
        }
Esempio n. 34
0
		public EntityUpdate(CommandType commandType, UserContext userContext, ResourceType type, EntityMetadata metadata, IQueryable query, string membershipId)
		{
			ExceptionHelpers.ThrowArgumentExceptionIf("commandType", commandType != CommandType.Update, Resources.InternalErrorOccurred, new object[0]);
			this.query = query;
			this.userContext = userContext;
			this.membershipId = membershipId;
			this.resourceType = type;
			this.metadata = metadata;
			this.commandType = commandType;
			this.propertyUpdates = new SortedDictionary<string, object>();
			this.updatedResource = null;
			this.resolveResource = null;
			CommandArgumentVisitor commandArgumentVisitor = new CommandArgumentVisitor(this);
			commandArgumentVisitor.Visit(query.Expression);
			if (this.AreAllKeyFieldsSpecified())
			{
				return;
			}
			else
			{
				throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.KeysMissingInQuery, new object[0]));
			}
		}
Esempio n. 35
0
        public string CreateResource(string token, DSResource resource)
        {
            if (resource == null)
            {
                throw new ArgumentException("resource must be specified");
            }

            ResourceManagementClient client = Utiles.GetClient(repoCache, token);

            ResourceObject ro = client.CreateResource(resource.ObjectType);

            Utiles.BuildResourceObject(resource, ref ro);

            try
            {
                ro.Save();
                return(ro.ObjectID.Value);
            }
            catch (AuthorizationRequiredException e)
            {
                throw new AuthZRequiredException(e.Message);
            }
        }
Esempio n. 36
0
 private static void buildAttribute(string attributeName, AttributeValue value, ResourceManagementClient client, ref DSResource result)
 {
     if (value != null)
     {
         if (value.IsNull)
         {
             result.Add(attributeName, null);
         }
         else
         {
             if (value.Attribute.IsMultivalued)
             {
                 if (value.Attribute.Type.ToString().Equals("Reference"))
                 {
                     if (client != null && !value.AttributeName.Equals("ObjectID"))
                     {
                         List <Dictionary <string, object> > refValues = new List <Dictionary <string, object> >();
                         foreach (string refValue in value.StringValues)
                         {
                             ResourceObject refObject = client.GetResource(refValue, new string[] { "DisplayName" });
                             refValues.Add(new Dictionary <string, object>
                             {
                                 { "DisplayName", refObject.DisplayName },
                                 { "ObjectID", refObject.ObjectID.Value },
                                 { "ObjectType", refObject.ObjectType.ToString() }
                             });
                         }
                         result.Add(attributeName, refValues.ToArray());
                     }
                     else
                     {
                         result.Add(attributeName, value.StringValues);
                     }
                 }
                 else
                 {
                     result.Add(attributeName, value.Values);
                 }
             }
             else
             {
                 if (value.Attribute.Type.ToString().Equals("Reference"))
                 {
                     if (client != null && !value.AttributeName.Equals("ObjectID"))
                     {
                         ResourceObject refObject = client.GetResource(value.StringValue, new string[] { "DisplayName" });
                         result.Add(attributeName, new Dictionary <string, object>
                         {
                             { "DisplayName", refObject.DisplayName },
                             { "ObjectID", refObject.ObjectID.Value },
                             { "ObjectType", refObject.ObjectType.ToString() }
                         });
                     }
                     else
                     {
                         result.Add(attributeName, value.StringValue);
                     }
                 }
                 else
                 {
                     result.Add(attributeName, value.Value);
                 }
             }
         }
     }
 }
Esempio n. 37
0
        public static DSResource BuildFullResource(ResourceObject resourceObject,
                                                   List <string> attributesToLoad, Dictionary <string, DSAttribute> schema, ResourceManagementClient client = null)
        {
            if (resourceObject == null)
            {
                throw new ArgumentException("resource object must be specified");
            }

            if (attributesToLoad == null)
            {
                throw new ArgumentException("loading attributes must be specified");
            }

            DSResource result = new DSResource();

            if (!attributesToLoad.Contains("DisplayName"))
            {
                attributesToLoad.Add("DisplayName");
            }
            if (!attributesToLoad.Contains("ObjectID"))
            {
                attributesToLoad.Add("ObjectID");
            }
            if (!attributesToLoad.Contains("ObjectType"))
            {
                attributesToLoad.Add("ObjectType");
            }

            foreach (string attributeName in attributesToLoad)
            {
                AttributeValue value = resourceObject.Attributes.FirstOrDefault(a => a.AttributeName.Equals(attributeName));

                if (value == null || !schema.ContainsKey(attributeName))
                {
                    continue;
                }

                DSAttribute attributeSchema = schema.FirstOrDefault(s => s.Key.Equals(attributeName)).Value;

                if (value != null)
                {
                    DSAttribute dsAttribute = new DSAttribute
                    {
                        DisplayName    = attributeSchema.DisplayName,
                        SystemName     = attributeSchema.SystemName,
                        Description    = attributeSchema.Description,
                        Multivalued    = attributeSchema.Multivalued,
                        Required       = attributeSchema.Required,
                        DataType       = attributeSchema.DataType,
                        StringRegex    = attributeSchema.StringRegex,
                        IntegerMaximum = attributeSchema.IntegerMaximum,
                        IntegerMinimum = attributeSchema.IntegerMinimum,
                        PermissionHint = value.PermissionHint.ToString()
                    };

                    if (value.IsNull)
                    {
                        dsAttribute.Value  = null;
                        dsAttribute.Values = null;
                    }
                    else
                    {
                        if (value.Attribute.Type.ToString().Equals("Reference"))
                        {
                            if (client != null && !value.AttributeName.Equals("ObjectID"))
                            {
                                List <Dictionary <string, object> > refValues = new List <Dictionary <string, object> >();
                                List <string> ids = dsAttribute.Multivalued ?
                                                    value.StringValues.ToList() : new List <string> {
                                    value.StringValue
                                };

                                foreach (string refValue in ids)
                                {
                                    ResourceObject refObject = client.GetResource(refValue, new string[] { "DisplayName" });
                                    refValues.Add(new Dictionary <string, object>
                                    {
                                        { "DisplayName", refObject.DisplayName },
                                        { "ObjectID", refObject.ObjectID.Value },
                                        { "ObjectType", refObject.ObjectType.ToString() }
                                    });
                                }

                                dsAttribute.Value  = refValues.First();
                                dsAttribute.Values = refValues.ToList <object>();
                            }
                            else
                            {
                                dsAttribute.Value = dsAttribute.Multivalued ?
                                                    value.StringValues.First() : value.StringValue;
                                dsAttribute.Values = dsAttribute.Multivalued ?
                                                     value.StringValues.ToList <object>() : new List <object> {
                                    value.StringValue
                                };
                            }
                        }
                        else
                        {
                            dsAttribute.Value  = value.Value;
                            dsAttribute.Values = value.Values.ToList();
                        }
                    }

                    result.Add(value.AttributeName, dsAttribute);
                }
            }

            return(result);
        }
Esempio n. 38
0
		public override object Serialize(object clrObject, int depth)
		{
			object value;
			object[] name = new object[1];
			name[0] = base.ResourceType.Name;
			clrObject.ThrowIfNull("clrObject", new ParameterExtensions.MessageLoader(SerializerBase.GetNullPassedForSerializingEntityMessage), name);
			ResourceType resourceType = base.ResourceType;
			if (clrObject as PSObject == null)
			{
				resourceType = base.ResourceType.FindResourceType(clrObject.GetType());
			}
			else
			{
				PSObject pSObject = clrObject as PSObject;
				if (pSObject != null && pSObject.BaseObject != null)
				{
					resourceType = base.ResourceType.FindResourceType(pSObject.BaseObject.GetType());
				}
			}
			DSResource dSResource = new DSResource(resourceType, this.serializeKeyOnly);
			foreach (ResourceProperty property in resourceType.Properties)
			{
				if (this.serializeKeyOnly && (property.Kind & ResourcePropertyKind.Key) != ResourcePropertyKind.Key)
				{
					continue;
				}
				if ((property.Kind & ResourcePropertyKind.ResourceSetReference) == ResourcePropertyKind.ResourceSetReference)
				{
					PSEntityMetadata testHookEntityMetadata = this.TestHookEntityMetadata;
					if (testHookEntityMetadata == null)
					{
						DataContext currentContext = DataServiceController.Current.GetCurrentContext();
						if (currentContext != null)
						{
							testHookEntityMetadata = currentContext.UserSchema.GetEntityMetadata(base.ResourceType) as PSEntityMetadata;
						}
					}
					if (testHookEntityMetadata != null)
					{
						PSEntityMetadata.ReferenceSetCmdlets referenceSetCmdlet = null;
						if (testHookEntityMetadata.CmdletsForReferenceSets.TryGetValue(property.Name, out referenceSetCmdlet) && referenceSetCmdlet.Cmdlets.ContainsKey(CommandType.GetReference))
						{
							if (referenceSetCmdlet.GetRefHidden)
							{
								dSResource.SetValue(property.Name, null);
								continue;
							}
							else
							{
								PSReferencedResourceSet pSReferencedResourceSet = new PSReferencedResourceSet(property, base.ResourceType);
								dSResource.SetValue(property.Name, pSReferencedResourceSet);
								continue;
							}
						}
					}
				}
				if (clrObject != null)
				{
					value = SerializerBase.GetValue(property, clrObject);
				}
				else
				{
					value = null;
				}
				object obj = value;
				if (obj == null)
				{
					if (!property.ResourceType.IsPrimitive() || property.ResourceType.IsNullable())
					{
						if ((property.Kind & (ResourcePropertyKind.Primitive | ResourcePropertyKind.ResourceReference)) != 0)
						{
							Tracer tracer = new Tracer();
							tracer.DebugMessage(string.Concat(property.Name, " is null; skipping"));
							continue;
						}
					}
					else
					{
						object[] objArray = new object[1];
						objArray[0] = property.Name;
						throw new PSObjectSerializationFailedException(string.Format(CultureInfo.CurrentCulture, Resources.PropertyNotFoundInPSObject, objArray));
					}
				}
				dSResource.SetValue(property.Name, SerializerBase.SerializeResourceProperty(obj, base.ResourceType, property, depth));
			}
			return dSResource;
		}
Esempio n. 39
0
		public object Resolve()
		{
			if (this.commandType != CommandType.Delete)
			{
				if (this.updatedResource == null)
				{
					if (this.resolveResource == null)
					{
						this.resolveResource = new DSResource(this.resourceType, true);
					}
					return this.resolveResource;
				}
				else
				{
					return this.updatedResource;
				}
			}
			else
			{
				throw new NotImplementedException(ExceptionHelpers.GetExceptionMessage(Resources.ResolveResourceAfterDelete, new object[0]));
			}
		}
Esempio n. 40
0
		public void InvokeCommand()
		{
			if (PSCommandManager.IsReferenceCmdlet(this.commandType))
			{
				IReferenceSetCommand referenceSetCommand = DataServiceController.Current.GetReferenceSetCommand(this.commandType, this.userContext, this.referringProperty, this.metadata, this.membershipId, null);
				using (referenceSetCommand)
				{
					UriParametersHelper.AddParametersToCommand(referenceSetCommand, DataServiceController.Current.GetCurrentResourceUri());
					this.AddPropertyUpdates(referenceSetCommand);
					referenceSetCommand.AddReferredObject(this.referredInstance.GetKeyValues());
					referenceSetCommand.AddReferringObject(this.GetKeyValues());
					List<DSResource> dSResources = new List<DSResource>();
					DataServiceController.Current.QuotaSystem.CheckCmdletExecutionQuota(this.userContext);
					IEnumerator<DSResource> enumerator = referenceSetCommand.InvokeAsync(dSResources.AsQueryable<DSResource>().Expression, true);
					while (enumerator.MoveNext())
					{
					}
				}
			}
			else
			{
				ICommand command = DataServiceController.Current.GetCommand(this.commandType, this.userContext, this.resourceType, this.metadata, this.membershipId);
				using (command)
				{
					UriParametersHelper.AddParametersToCommand(command, DataServiceController.Current.GetCurrentResourceUri());
					this.AddPropertyUpdates(command);
					List<DSResource> dSResources1 = new List<DSResource>();
					IEnumerator<DSResource> enumerator1 = command.InvokeAsync(dSResources1.AsQueryable<DSResource>().Expression, true);
					while (enumerator1.MoveNext())
					{
						dSResources1.Add(enumerator1.Current);
					}
					if (this.commandType == CommandType.Delete || dSResources1.Count < 1)
					{
						if (this.commandType != CommandType.Create || dSResources1.Count > 0)
						{
							this.updatedResource = null;
						}
						else
						{
							throw new DataServiceException(string.Format(Resources.CreateCommandNotReturnedInstance, this.resourceType.Name));
						}
					}
					else
					{
						this.updatedResource = dSResources1.First<DSResource>();
					}
				}
			}
		}