コード例 #1
0
        public DataPackage CMSUploadMethod(string dmsfolderpath, string localfilepath)
        {
            if (!File.Exists(localfilepath))
            {
                throw new Exception("Test file: " + localfilepath + " does not exist");
            }
            ObjectIdentity objIdentity = new ObjectIdentity(DefaultRepository);
            DataObject     dataObject  = new DataObject(objIdentity, "dm_document"); //eifx_deliverable_doc // ecs_correspondence
            PropertySet    properties  = dataObject.Properties;

            properties.Set("object_name", "MyImage" + System.DateTime.Now.Ticks);
            properties.Set("title", "MyImage");
            properties.Set("a_content_type", "gif");
            dataObject.Contents.Add(new FileContent(Path.GetFullPath(localfilepath), "gif"));


            ObjectPath            objectPath               = new ObjectPath(dmsfolderpath);
            ObjectIdentity        sampleFolderIdentity     = new ObjectIdentity(objectPath, DefaultRepository);
            ReferenceRelationship sampleFolderRelationship = new ReferenceRelationship();

            sampleFolderRelationship.Name       = Relationship.RELATIONSHIP_FOLDER;
            sampleFolderRelationship.Target     = sampleFolderIdentity;
            sampleFolderRelationship.TargetRole = Relationship.ROLE_PARENT;
            dataObject.Relationships.Add(sampleFolderRelationship);


            OperationOptions operationOptions = null;
            DataPackage      dataPackage      = objectService.Create(new DataPackage(dataObject), operationOptions);
            string           object_          = dataPackage.DataObjects[0].Identity.GetValueAsString();

            return(dataPackage);
        }
コード例 #2
0
        /// <summary>
        /// Inserimento nuovo ruolo in amministrazione
        /// </summary>
        /// <param name="ruolo"></param>
        /// <returns></returns>
        public EsitoOperazione InserisciRuolo(OrgRuolo ruolo, bool computeAtipicita)
        {
            EsitoOperazione ret = new EsitoOperazione();
            string          logMsg;
            IObjectService  objSrvc        = null;
            String          repositoryName = DctmConfigurations.GetRepositoryName();

            // test sui campi obbligatori
            if (string.IsNullOrEmpty(ruolo.Codice) ||
                string.IsNullOrEmpty(ruolo.Descrizione))
            {
                ret.Codice      = -1;
                logMsg          = ERR_HEADER + "InserisciRuolo: dati insufficienti";
                ret.Descrizione = logMsg;
                logger.Debug(logMsg);
                return(ret);
            }

            // il campo Codice corrisponde a:
            //  (ETDOCS) DPA_CORR_GLOBALI.VAR_COD_RUBRICA varchar(128)
            //  (DCTM)   dm_group.group_name string(32)
            // se mi viene passato un codice di lunghezza > 32 lancio un'eccezione
            if (ruolo.Codice.Length > 32)
            {
                ret.Codice      = -1;
                logMsg          = ERR_HEADER + "InserisciRuolo: campo CODICE supera la lunghezza massima (32)";
                ret.Descrizione = logMsg;
                logger.Debug(logMsg);
                return(ret);
            }

            try
            {
                objSrvc = this.GetObjectServiceInstance();

                ObjectIdentity userIdentity = new ObjectIdentity(repositoryName);
                DataObject     groupData    = new DataObject(userIdentity, ObjectTypes.GRUPPO);

                groupData.Properties.Properties.AddRange(Dfs4DocsPa.getGroupProperties(ruolo, false));

                DataPackage pkg = new DataPackage(groupData);
                objSrvc.Create(pkg, null);
                logger.Debug(DEBUG_HEADER + "InserisciRuolo completata con SUCCESSO");
                return(ret);
            }
            catch (Exception ex)
            {
                String st = ex.ToString();
                logger.Debug(DEBUG_HEADER + "InserisciRuolo FALLITA, Exception=" + st);
                ret.Codice      = -1;
                ret.Descrizione = ERR_HEADER + "InserisciRuolo";
                return(ret);
            }
        }
コード例 #3
0
    public void CreateUser_Valid_Success()
    {
        // Arrange.

        // Act.
        User user = _userService.Create(_user);

        // Assert.
        Assert.Equal(_user, user);

        _output.WriteLine("Manually check Azure Queue to confirm user create operation successfully decorated.");
    }
コード例 #4
0
    public void CreatePassword_Valid_Success()
    {
        // Arrange.

        // Act.
        Password password = _passwordService.Create(_password);

        // Assert.
        Assert.Equal(_password, password);

        _output.WriteLine("Manually check Azure Queue to confirm password create operation successfully decorated.");
    }
コード例 #5
0
ファイル: DFSLogic.cs プロジェクト: minhhi227/Java
        public static void startLogic(String repository, String userName, String password)
        {
            IServiceContext context = createContext(repository, userName, password);

            //comment block 'new service'

            Console.Out.WriteLine("Creating new IObjectService instance...");

            //create a service factory and instatiate the IObjectService
            ServiceFactory sf            = ServiceFactory.Instance;
            IObjectService objectService =
                sf.GetRemoteService <IObjectService>(context);

            //comment block 'build'

            Console.Out.WriteLine("Creating new ObjectIdentiy instance...");

            //build object identity
            ObjectIdentity docIdent = new ObjectIdentity();

            docIdent.RepositoryName = repository;

            Console.Out.WriteLine("Creating new DataObject instance...");

            //build data object, seed with object identity
            DataObject dataObj = new DataObject(docIdent, "dm_document");

            Console.Out.WriteLine("Creating new PropertySet instance...");

            //build property set
            String      objName     = "lab03_test";
            PropertySet propertySet = new PropertySet();

            propertySet.Set("object_name", objName);

            //seed data object with property set
            dataObj.Properties = propertySet;

            Console.Out.WriteLine("Creating new DataPackage instance...");

            //build data package, seed with data object
            DataPackage dataPack = new DataPackage(dataObj);

            Console.Out.WriteLine("Calling the IObjectService.create() method...");

            OperationOptions options = null;

            //call the create method
            objectService.Create(dataPack, options);

            Console.Out.WriteLine("A new object called '" + objName + "' has been created...");
        }
        /// <inheritdoc />
        public virtual IEnumerable <TEntity> Create(IEnumerable <TEntity> items)
        {
            IEnumerable <TEntity> created = default;
            var isServiceException        = false;

            try
            {
                using (var auditScope = AuditScope.Create($"{EntityName}:Create+", () => created))
                {
                    auditScope.Event.Environment.UserName = UserContext.CurrentUser;
                    auditScope.Event.Target.Type          = $"{items.GetType()}";

                    try
                    {
                        created = DecoratedService.Create(items);
                    }
                    catch
                    {
                        isServiceException = true;
                        auditScope.Discard();
                        throw;
                    }
                }
            }
            catch (Exception e)
            {
                if (isServiceException)
                {
                    throw;
                }

                Logger.Warning(e, "Auditing failed for Create+ of type {Entity}.", EntityName);
            }

            return(created);
        }
コード例 #7
0
        public DataPackage CreateContentlessDocument()
        {
            ObjectIdentity objectIdentity = new ObjectIdentity(DefaultRepository);
            DataObject     dataObject     = new DataObject(objectIdentity, "dm_document");
            PropertySet    properties     = new PropertySet();

            properties.Set("object_name", "contentless-" + System.DateTime.Now.Ticks);
            dataObject.Properties = properties;
            DataPackage dataPackage = new DataPackage(dataObject);

            OperationOptions operationOptions = null;

            return(objectService.Create(dataPackage, operationOptions));
        }
コード例 #8
0
        /// <inheritdoc cref="ISessionService.StoreSession(string,string,string,string,string,string)"/>
        public void StoreSession(
            string applicationKey,
            string sessionToken,
            string environmentUrl,
            string solutionId = null,
            string userToken  = null,
            string instanceId = null)
        {
            if (applicationKey == null)
            {
                throw new ArgumentNullException(nameof(applicationKey));
            }

            if (sessionToken == null)
            {
                throw new ArgumentNullException(nameof(sessionToken));
            }

            if (environmentUrl == null)
            {
                throw new ArgumentNullException(nameof(environmentUrl));
            }

            if (HasSession(applicationKey, solutionId, userToken, instanceId))
            {
                throw new AlreadyExistsException(
                          $"Session already exists for [applicationKey:{applicationKey}|solutionId:{solutionId}|userToken:{userToken}|instanceId:{instanceId}].");
            }

            if (HasSessionToken(sessionToken))
            {
                throw new AlreadyExistsException($"Session already exists for session token {sessionToken}.");
            }

            var session = new Session
            {
                ApplicationKey = applicationKey,
                EnvironmentUrl = environmentUrl,
                Id             = Guid.NewGuid(),
                InstanceId     = instanceId,
                SessionToken   = sessionToken,
                SolutionId     = solutionId,
                UserToken      = userToken
            };

            _ = service.Create(session);
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="nodoTitolario"></param>
        /// <param name="refreshAclIfUpdate">
        /// Se true, indica di aggiornare le entries dell'ACL associata al nodo titolario
        /// </param>
        /// <returns></returns>
        public bool SaveNodoTitolario(OrgNodoTitolario nodoTitolario, bool refreshAclIfUpdate)
        {
            bool retValue = false;

            bool aclCreated = false;

            try
            {
                //titolario.ID  viene SEMPRE valorizzato da ETDOCS; se così non è --> ERRORE
                if (string.IsNullOrEmpty(nodoTitolario.ID))
                {
                    retValue = false;

                    logger.Debug("Errore passaggio dati da ETDOCS: ID nodo titolario mancante");
                }
                else
                {
                    IQueryService querySrvc = this.GetQueryServiceInstance();

                    DataObject dataObject = new DataObject();
                    dataObject.Type = ObjectTypes.NODO_TITOLARIO;

                    DataObject dataObjectFascicoloGenerale = null;

                    // Reperimento oggetto identity per il titolario corrente
                    ObjectIdentity nodoTitolarioIdentity = Dfs4DocsPa.getNodoTitolarioIdentity(nodoTitolario.ID);

                    // Verifica esistenza nodo titolario
                    bool insertMode = (!Dfs4DocsPa.containsNodoTitolario(nodoTitolario.ID, querySrvc));

                    IObjectService objSrvc = this.GetObjectServiceInstance();

                    if (insertMode)
                    {
                        // Modalità di inserimento
                        // Creazione oggetto identity per nuovo inserimento
                        dataObject.Identity = new ObjectIdentity(DctmConfigurations.GetRepositoryName());

                        // Determinazione dell'oggetto parent del nodo di titolario da inserire
                        ObjectIdentity parentIdentity = null;

                        if (nodoTitolario.Livello == "1")
                        {
                            // Se nodo di primo livello, deve essere legato alla struttura di titolario
                            parentIdentity = Dfs4DocsPa.getTitolarioIdentity(nodoTitolario.ID_Titolario);
                        }
                        else
                        {
                            // Se nodo figlio di un altro nodo, lo lega al padre
                            parentIdentity = Dfs4DocsPa.getNodoTitolarioIdentity(nodoTitolario.IDParentNodoTitolario);
                        }

                        dataObject.Relationships = new List <Relationship>();
                        dataObject.Relationships.Add(DfsHelper.createParentFolderRelationship(parentIdentity));

                        // Creazione fascicolo generale, figlio nodo del titolario da creare
                        dataObjectFascicoloGenerale          = new DataObject();
                        dataObjectFascicoloGenerale.Type     = ObjectTypes.FASCICOLO_GENERALE;
                        dataObjectFascicoloGenerale.Identity = new ObjectIdentity(DctmConfigurations.GetRepositoryName());

                        // Creazione oggetto relationship
                        dataObjectFascicoloGenerale.Relationships = new List <Relationship>();
                        dataObjectFascicoloGenerale.Relationships.Add(DfsHelper.createParentFolderRelationship(nodoTitolarioIdentity));

                        dataObjectFascicoloGenerale.Properties = new PropertySet();
                        dataObjectFascicoloGenerale.Properties.Properties.AddRange(Dfs4DocsPa.getFascicoloGeneraleProperties(nodoTitolario));
                    }
                    else
                    {
                        // Modalità di aggiornamento

                        // Reperimento oggetto identity per nodo titolario da modificare
                        dataObject.Identity = nodoTitolarioIdentity;
                    }

                    // Impostazione proprietà nodo titolario
                    dataObject.Properties = new PropertySet();
                    dataObject.Properties.Properties.AddRange(Dfs4DocsPa.getNodoTitolarioProperties(nodoTitolario));

                    List <DataObject> dataObjectList = new List <DataObject>();
                    dataObjectList.Add(dataObject);
                    if (dataObjectFascicoloGenerale != null)
                    {
                        // Inserimento DataObject relativo al fascicolo generale
                        dataObjectList.Add(dataObjectFascicoloGenerale);
                    }

                    // Creazione oggetto DataPackage
                    DataPackage dataPackage = new DataPackage();
                    dataPackage.DataObjects.AddRange(dataObjectList);
                    dataPackage.RepositoryName = DctmConfigurations.GetRepositoryName();

                    // Save oggetto nodo titolario in documentum
                    if (insertMode)
                    {
                        // Creazione ACL, comune sia per il nodo titolario che per il fascicolo generale in esso contenuto
                        CustomServices.AclDefinition aclDefinition = this.CreateAclNodoTitolario(nodoTitolario);

                        // ACL del titolario creata
                        aclCreated = true;

                        // Impostazione delle properties relative all'acl per il nodo titolario
                        AclHelper.setAclObjectProperties(dataObject.Properties, aclDefinition);

                        // Impostazione delle properties relative all'acl per il fascicolo generale
                        AclHelper.setAclObjectProperties(dataObjectFascicoloGenerale.Properties, aclDefinition);

                        dataPackage = objSrvc.Create(dataPackage, null);
                    }
                    else
                    {
                        dataPackage = objSrvc.Update(dataPackage, null);

                        if (refreshAclIfUpdate)
                        {
                            // Aggiornamento delle entries dell'acl associata al nodo
                            this.RefreshAclNodoTitolario(nodoTitolario);
                        }
                    }

                    retValue = (dataPackage.DataObjects.Count > 0);

                    if (retValue)
                    {
                        logger.Debug(string.Format("Documentum.SaveNodoTitolario: salvato nodo di titolario con id {0}", nodoTitolario.ID));
                    }
                }
            }
            catch (Exception ex)
            {
                retValue = false;

                logger.Debug("Errore in Documentum.SaveNodoTitolario: " + ex.ToString());

                if (aclCreated)
                {
                    // Se l'ACL è stata creata, viene rimossa
                    this.DeleteAclNodoTitolario(nodoTitolario);
                }
            }

            return(retValue);
        }
コード例 #10
0
        /// <summary>
        /// Inserimento o aggiornamento dei metadati generali relativi
        /// all’intera struttura di classificazione dei documenti
        /// </summary>
        /// <param name="titolario"></param>
        /// <returns></returns>
        public bool SaveTitolario(OrgTitolario titolario)
        {
            bool retValue = false;

            try
            {
                //titolario.ID viene SEMPRE valorizzato da ETDOCS; se così non è --> ERRORE
                if (string.IsNullOrEmpty(titolario.ID))
                {
                    logger.Debug("Errore passaggio dati da ETDOCS: ID Titolario mancante");
                }
                else
                {
                    // Reperimento istanza objectservice
                    IObjectService objSrvc = GetObjectServiceInstance();

                    DataObject dataObject = new DataObject();
                    dataObject.Type = ObjectTypes.TITOLARIO;

                    // Reperimento oggetto identity per il titolario corrente
                    ObjectIdentity titolarioIdentity = Dfs4DocsPa.getTitolarioIdentity(titolario.ID);

                    IQueryService querySrvc = this.GetQueryServiceInstance();

                    // Verifica se il titolario è già esistente
                    bool insertMode = (!Dfs4DocsPa.containsTitolario(titolario.ID, querySrvc));

                    if (insertMode)
                    {
                        // Creazione oggetto identity per nuovo inserimento
                        dataObject.Identity = new ObjectIdentity(DctmConfigurations.GetRepositoryName());

                        // Modalità di in inserimento, creazione oggetto Identity parent e oggetto relationship
                        ObjectIdentity parentIdentity = DfsHelper.createObjectIdentityByPath(DocsPaAdminCabinet.getRootTitolario(titolario.CodiceAmministrazione));

                        dataObject.Relationships = new List <Relationship>();
                        dataObject.Relationships.Add(DfsHelper.createParentFolderRelationship(parentIdentity));
                    }
                    else
                    {
                        // Reperimento oggetto identity per titolario da modificare
                        dataObject.Identity = titolarioIdentity;
                    }

                    // Impostazione proprietà titolario
                    dataObject.Properties = new PropertySet();
                    dataObject.Properties.Properties.AddRange(Dfs4DocsPa.getTitolarioProperties(titolario));

                    DataPackage dataPackage = new DataPackage(dataObject);
                    dataPackage.RepositoryName = DctmConfigurations.GetRepositoryName();

                    // Save oggetto titolario in documentum
                    if (insertMode)
                    {
                        // Reperimento ACL dell'amministrazione da associare al titolario
                        CustomServices.AclDefinition aclDefinition = Dfs4DocsPa.getAclDefinitionAmministrazione(titolario.CodiceAmministrazione);

                        // Impostazione delle properties relative all'acl per il nodo titolario
                        AclHelper.setAclObjectProperties(dataObject.Properties, aclDefinition);

                        dataPackage = objSrvc.Create(dataPackage, null);
                    }
                    else
                    {
                        dataPackage = objSrvc.Update(dataPackage, null);
                    }

                    retValue = (dataPackage.DataObjects.Count > 0);

                    if (retValue)
                    {
                        logger.Debug(string.Format("Documentum.SaveTitolario: salvato titolario con id {0}", titolario.ID));
                    }
                }
            }
            catch (Exception ex)
            {
                retValue = false;

                logger.Debug("Errore in Documentum.SaveTitolario: " + ex.ToString());
            }

            return(retValue);
        }
コード例 #11
0
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Post(TTSingle, string[], string[])">Post</see>
        /// </summary>
        public virtual IHttpActionResult Post(TSingle obj, [MatrixParameter] string[] zoneId = null, [MatrixParameter] string[] contextId = null)
        {
            if (!authService.VerifyAuthenticationHeader(Request.Headers))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest("Request failed for object " + typeof(TSingle).Name + " as Zone and/or Context are invalid."));
            }

            IHttpActionResult result;

            try
            {
                bool hasAdvisoryId   = !string.IsNullOrWhiteSpace(obj.RefId);
                bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                if (mustUseAdvisory.HasValue && mustUseAdvisory.Value == true)
                {
                    if (hasAdvisoryId)
                    {
                        TSingle createdObject = service.Create(obj, mustUseAdvisory, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0]));
                        string  uri           = Url.Link("DefaultApi", new { controller = typeof(TSingle).Name, id = createdObject.RefId });
                        result = Created(uri, createdObject);
                    }
                    else
                    {
                        result = BadRequest("Request failed for object " + typeof(TSingle).Name + " as object ID is not provided, but mustUseAdvisory is true.");
                    }
                }
                else
                {
                    TSingle createdObject = service.Create(obj, zoneId: (zoneId == null ? null : zoneId[0]), contextId: (contextId == null ? null : contextId[0]));
                    string  uri           = Url.Link("DefaultApi", new { controller = typeof(TSingle).Name, id = createdObject.RefId });
                    result = Created(uri, createdObject);
                }
            }
            catch (AlreadyExistsException)
            {
                result = Conflict();
            }
            catch (ArgumentException e)
            {
                result = BadRequest("Object to create of type " + typeof(TSingle).Name + " is invalid.\n " + e.Message);
            }
            catch (CreateException e)
            {
                result = BadRequest("Request failed for object " + typeof(TSingle).Name + ".\n " + e.Message);
            }
            catch (RejectedException e)
            {
                result = this.NotFound("Create request rejected for object " + typeof(TSingle).Name + " with ID of " + obj.RefId + ".\n" + e.Message);
            }
            catch (QueryException e)
            {
                result = BadRequest("Request failed for object " + typeof(TSingle).Name + ".\n " + e.Message);
            }
            catch (Exception e)
            {
                result = InternalServerError(e);
            }

            return(result);
        }
コード例 #12
0
        /// <summary>
        /// Creazione di un nuovo fascicolo in DCTM
        /// </summary>
        /// <remarks>
        ///
        /// PreCondizioni:
        ///     Il fascicolo è stato inserito correttamente in DocsPa
        ///     ed è stato generato un'identificativo univoco
        ///
        /// PostCondizioni:
        ///     Creato un oggetto in Documentum corrispondente all'oggetto
        ///     fascicolo di DocsPa. L'oggetto avrà i metadati del fascicolo
        ///     per la sola consultazione in documentum.
        ///
        /// </remarks>
        /// <param name="classifica"></param>
        /// <param name="fascicolo"></param>
        /// <param name="ruolo"></param>
        /// <param name="enableUfficioReferente"></param>
        /// <returns></returns>
        public bool CreateProject(Classificazione classifica, Fascicolo fascicolo, Ruolo ruolo, bool enableUfficioReferente, out ResultCreazioneFascicolo result)
        {
            logger.Info("BEGIN");
            bool retValue = false;

            result = ResultCreazioneFascicolo.GENERIC_ERROR;

            CustomServices.AclDefinition aclFascicolo = null;

            try
            {
                //fascicolo.systemID  viene SEMPRE valorizzato da ETDOCS; se così non è --> ERRORE
                if (string.IsNullOrEmpty(fascicolo.systemID))
                {
                    logger.Debug("Errore passaggio dati da ETDOCS.");
                }
                else
                {
                    // Reperimento dell'objectidentity relativo al nodo titolario in cui andrà inserito il fascicolo
                    ObjectIdentity nodoTitolarioIdentity = Dfs4DocsPa.getNodoTitolarioIdentity(fascicolo.idClassificazione);

                    // Reperimento properties del fascicolo procedimentale
                    PropertySet props = new PropertySet();
                    props.Properties.AddRange(Dfs4DocsPa.getFascicoloProcedimentaleProperties(fascicolo));

                    // Creazione delle ACL per il fascicolo
                    aclFascicolo = this.CreateAclFascicolo(fascicolo, ruolo);

                    // Associazione delle ACL al fascicolo da creare
                    AclHelper.setAclObjectProperties(props, aclFascicolo);

                    ObjectIdentity identity   = new ObjectIdentity(DctmConfigurations.GetRepositoryName());
                    DataObject     dataObject = new DataObject(identity, ObjectTypes.FASCICOLO_PROCEDIMENTALE);
                    dataObject.Properties = props;
                    dataObject.Relationships.Add(DfsHelper.createParentFolderRelationship(nodoTitolarioIdentity));

                    DataPackage dataPackage = new DataPackage(dataObject);

                    IObjectService objectService = this.GetServiceInstance <IObjectService>(false);
                    dataPackage = objectService.Create(dataPackage, null);

                    retValue = (dataPackage.DataObjects.Count == 1);

                    if (retValue)
                    {
                        result = ResultCreazioneFascicolo.OK;

                        logger.Debug(string.Format("Documentum.CreateProject: creato fascicolo con id {0}", fascicolo.systemID));
                    }
                }
            }
            catch (Exception ex)
            {
                retValue = false;
                result   = ResultCreazioneFascicolo.GENERIC_ERROR;

                logger.Debug(string.Format("Errore in Documentum.CreateProject:\n{0}", ex.ToString()));

                if (aclFascicolo != null)
                {
                    // Rimozione ACL fascicolo in caso di errore
                    this.DeleteAcl(aclFascicolo);
                }
            }
            logger.Info("END");
            return(retValue);
        }
コード例 #13
0
        /// <summary>
        /// <see cref="IProvider{TTSingle,TMultiple,TPrimaryKey}.Post(TTSingle, string[], string[])">Post</see>
        /// </summary>
        public virtual IHttpActionResult Post(
            TSingle obj,
            [MatrixParameter] string[] zoneId    = null,
            [MatrixParameter] string[] contextId = null)
        {
            if (!authenticationService.VerifyAuthenticationHeader(Request.Headers, out string sessionToken))
            {
                return(Unauthorized());
            }

            // Check ACLs and return StatusCode(HttpStatusCode.Forbidden) if appropriate.
            if (!authorisationService.IsAuthorised(Request.Headers, sessionToken, $"{TypeName}s", RightType.CREATE))
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }

            if ((zoneId != null && zoneId.Length != 1) || (contextId != null && contextId.Length != 1))
            {
                return(BadRequest($"Request failed for object {TypeName} as Zone and/or Context are invalid."));
            }

            IHttpActionResult result;

            try
            {
                bool hasAdvisoryId   = !string.IsNullOrWhiteSpace(obj.RefId);
                bool?mustUseAdvisory = HttpUtils.GetMustUseAdvisory(Request.Headers);

                if (mustUseAdvisory.HasValue && mustUseAdvisory.Value == true)
                {
                    if (hasAdvisoryId)
                    {
                        RequestParameter[] requestParameters = GetQueryParameters(Request);
                        TSingle            createdObject     =
                            service.Create(obj, mustUseAdvisory, zoneId?[0], contextId?[0], requestParameters);
                        string uri = Url.Link("DefaultApi", new { controller = TypeName, id = createdObject.RefId });
                        result = Created(uri, createdObject);
                    }
                    else
                    {
                        result = BadRequest($"Request failed for object {TypeName} as object ID is not provided, but mustUseAdvisory is true.");
                    }
                }
                else
                {
                    RequestParameter[] requestParameters = GetQueryParameters(Request);
                    TSingle            createdObject     = service.Create(
                        obj,
                        zoneId: zoneId?[0],
                        contextId: contextId?[0],
                        requestParameters: requestParameters);
                    string uri = Url.Link("DefaultApi", new { controller = TypeName, id = createdObject.RefId });
                    result = Created(uri, createdObject);
                }
            }
            catch (AlreadyExistsException)
            {
                result = Conflict();
            }
            catch (ArgumentException e)
            {
                result = BadRequest($"Object to create of type {TypeName} is invalid.\n{e.Message}");
            }
            catch (CreateException e)
            {
                result = BadRequest($"Request failed for object {TypeName}.\n{e.Message}");
            }
            catch (RejectedException e)
            {
                result = this.NotFound(
                    $"Create request rejected for object {TypeName} with ID of {obj.RefId}.\n{e.Message}");
            }
            catch (QueryException e)
            {
                result = BadRequest($"Request failed for object {TypeName}.\n{e.Message}");
            }
            catch (Exception e)
            {
                result = InternalServerError(e);
            }

            return(result);
        }
コード例 #14
0
        /// <summary>
        /// Inserimento di un nuovo utente in amministrazione
        /// </summary>
        /// <param name="utente"></param>
        /// <returns></returns>
        public EsitoOperazione InserisciUtente(OrgUtente utente)
        {
            EsitoOperazione retValue = new EsitoOperazione();

            string logMsg      = string.Empty;
            bool   userCreated = false;
            bool   pathCreated = false;

            // test sui campi obbligatori
            if (string.IsNullOrEmpty(utente.Codice) ||
                string.IsNullOrEmpty(utente.Email) ||
                string.IsNullOrEmpty(utente.IDPeople) ||
                string.IsNullOrEmpty(utente.UserId))
            {
                retValue.Codice      = -1;
                retValue.Descrizione = ERR_HEADER + "InserisciUtente: dati insufficienti";
                logger.Debug(retValue.Descrizione);
            }
            else
            {
                try
                {
                    IObjectService objSrvc = this.GetObjectServiceInstance();
                    string         repo    = DctmConfigurations.GetRepositoryName();

                    string         homePath            = string.Concat("/", TypeUtente.getHomeFolderName(utente.UserId));
                    ObjectIdentity identityHomeCabinet = objSrvc.CreatePath(new ObjectPath(homePath), repo);
                    pathCreated = true;

                    ObjectIdentity userIdentity = new ObjectIdentity(repo);
                    DataObject     userData     = new DataObject(userIdentity, ObjectTypes.UTENTE);

                    // Reperimento properties utente
                    userData.Properties.Properties.AddRange(Dfs4DocsPa.getUserProperties(utente));
                    userData.Properties.Set <string>("default_folder", homePath);

                    DataPackage dataPackage = new DataPackage(userData);

                    dataPackage = objSrvc.Create(dataPackage, null);

                    if (dataPackage.DataObjects.Count > 0)
                    {
                        userCreated = true;

                        // Impotazione proprietà "is_private = 1", per fare in modo
                        // che il cabinet sia visibile solamente all'utente che l'ha creato
                        // e 'owner_name' con il nome dell'utente
                        DataObject homeCabinetData = new DataObject(identityHomeCabinet, "dm_cabinet");
                        //homeCabinetData.Properties.Set<int>("is_private", 1);  //Vecchio 6.0
                        homeCabinetData.Properties.Set <string>("is_private", "1");
                        homeCabinetData.Properties.Set <string>("owner_name", TypeUtente.getUserName(utente));

                        dataPackage = new DataPackage(homeCabinetData);
                        dataPackage = objSrvc.Update(dataPackage, null);

                        if (dataPackage.DataObjects.Count > 0)
                        {
                            this.inserisciUtenteInAmministrazione(utente, userData);

                            retValue.Codice      = 0;
                            retValue.Descrizione = string.Empty;
                            logger.Debug(DEBUG_HEADER + "InserisciUtente completata con SUCCESSO");
                        }
                        else
                        {
                            throw new ApplicationException();
                        }
                    }
                    else
                    {
                        undoCreateHomeFolder(utente);
                        pathCreated = false;
                        throw new ApplicationException();
                    }
                }
                catch (Exception ex)
                {
                    string errorMessage = string.Format("Errore in {0}: {1}", DEBUG_HEADER, ex.ToString());

                    logger.Debug(errorMessage);
                    retValue.Codice      = -1;
                    retValue.Descrizione = ERR_HEADER + "InserisciUtente";

                    if (pathCreated)
                    {
                        this.undoCreateHomeFolder(utente);
                    }

                    if (userCreated)
                    {
                        this.undoCreateUser(utente);
                    }
                }
            }

            return(retValue);
        }