Ejemplo n.º 1
0
        public async Task <IActionResult> Edit(MatterViewModel vm)
        {
            if (ModelState.IsValid)
            {
                var entity = new Matter
                {
                    Id       = vm.Id,
                    Name     = vm.Name,
                    CarrerId = Convert.ToInt32(vm.CareerId)
                };
                try
                {
                    await _matterRepository.UpdateAsync(entity);
                }
                catch
                {
                    if (!await _matterRepository.ExistAsync(entity.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            vm.Careers = _careerRepository.GetAll().Select(x => new SelectListItem
            {
                Text  = x.Name,
                Value = x.Id.ToString(),
            }).ToList();

            return(View(vm));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates list of users for sending email.
        /// </summary>
        /// <param name="matter">Matter details</param>
        /// <param name="clientContext">SharePoint client context</param>
        /// <param name="userList">List of users associated with the matter</param>
        /// <returns>List of users to whom mail is to be sent</returns>
        internal List <FieldUserValue> GenerateMailList(Matter matter, Client client, ref List <FieldUserValue> userList)
        {
            List <FieldUserValue> result = null;

            try
            {
                List <FieldUserValue> userEmailList = new List <FieldUserValue>();
                if (null != matter.AssignUserNames)
                {
                    foreach (IList <string> userNames in matter.AssignUserNames)
                    {
                        userList = matterRepositoy.ResolveUserNames(client, userNames).ToList();
                        foreach (FieldUserValue userEmail in userList)
                        {
                            userEmailList.Add(userEmail);
                        }
                    }
                }
                result = userEmailList;
            }
            catch (Exception exception)
            {
                customLogger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
            return(result);
        }
Ejemplo n.º 3
0
        public IHttpActionResult PutMatter(int id, Matter matter)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != matter.Id)
            {
                return(BadRequest());
            }

            db.Entry(matter).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!MatterExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 4
0
        public static float UnitsPerCubicMeter(this Matter matter, float cubicMeters = 1f)
        {
            switch (matter)
            {
            case Matter.MealShakes:
            case Matter.MealPowders:
                return(36f / cubicMeters);

            case Matter.OrganicMeals:
            case Matter.RationMeals:
            case Matter.Biomass:
            case Matter.Produce:
                return(18f / cubicMeters);

            case Matter.SolarPanels:
            case Matter.Piping:
            case Matter.ElectricMotor:
                return(4f / cubicMeters);

            case Matter.IronSheeting:
            case Matter.Canvas:
            case Matter.PressureCanvas:
            case Matter.Glass:
                return(2f / cubicMeters);

            default:
                return(1f / cubicMeters);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Validates content type for the matter.
 /// </summary>
 /// <param name="matter">Matter object containing Matter data</param>
 /// <returns>A string value indicating whether validations passed or fail</returns>
 private GenericResponseVM ValidateContentType(Matter matter)
 {
     if ((0 >= matter.ContentTypes.Count()) || string.IsNullOrWhiteSpace(matter.DefaultContentType))
     {
         return(GenericResponse(errorSettings.IncorrectInputContentTypeCode, errorSettings.IncorrectInputContentTypeMessage));
     }
     else
     {
         foreach (string contentType in matter.ContentTypes)
         {
             var contentTypeCheck = Regex.Match(contentType, matterSettings.SpecialCharacterExpressionContentType, RegexOptions.IgnoreCase);
             if (contentTypeCheck.Success || int.Parse(matterSettings.ContentTypeLength, CultureInfo.InvariantCulture) < contentType.Length)
             {
                 return(GenericResponse(errorSettings.IncorrectInputContentTypeCode, errorSettings.IncorrectInputContentTypeMessage));
             }
         }
         var defaultContentTypeCheck = Regex.Match(matter.DefaultContentType, matterSettings.SpecialCharacterExpressionContentType, RegexOptions.IgnoreCase);
         if (defaultContentTypeCheck.Success ||
             int.Parse(matterSettings.ContentTypeLength, CultureInfo.InvariantCulture) < matter.DefaultContentType.Length)
         {
             return(GenericResponse(errorSettings.IncorrectInputContentTypeCode, errorSettings.IncorrectInputContentTypeMessage));
         }
     }
     return(null);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Function to check user full permission on document library
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="matter"></param>
        /// <returns></returns>
        public bool CheckUserFullPermission(ClientContext clientContext, Matter matter)
        {
            bool result = false;

            try
            {
                if (null != matter)
                {
                    Web            web           = clientContext.Web;
                    List           list          = web.Lists.GetByTitle(matter.Name);
                    Users          userDetails   = GetLoggedInUserDetails(clientContext);
                    Principal      userPrincipal = web.EnsureUser(userDetails.Name);
                    RoleAssignment userRole      = list.RoleAssignments.GetByPrincipal(userPrincipal);
                    clientContext.Load(userRole, userRoleProperties => userRoleProperties.Member,
                                       userRoleProperties => userRoleProperties.RoleDefinitionBindings.Include(userRoleDefinition => userRoleDefinition.Name).Where(userRoleDefinitionName => userRoleDefinitionName.Name ==
                                                                                                                                                                    matterSettings.EditMatterAllowedPermissionLevel));
                    clientContext.ExecuteQuery();
                    if (0 < userRole.RoleDefinitionBindings.Count)
                    {
                        result = true;
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
        }
Ejemplo n.º 7
0
    internal bool BeginPrinting(Matter component)
    {
        foreach (var req in Crafting.PrinterData[component].Requirements)
        {
            if (LeftInput != null && LeftInput.Data.Container.MatterType == req.Type)
            {
                if (!LeftInput.Data.Container.TryConsumeVolume(req.AmountByVolume))
                {
                    return(false);
                }
            }
            else if (RightInput != null && RightInput.Data.Container.MatterType == req.Type)
            {
                if (!RightInput.Data.Container.TryConsumeVolume(req.AmountByVolume))
                {
                    return(false);
                }
            }
        }

        FlexData.Printing = component;
        FlexData.Progress = 0f;
        FlexData.Duration = Crafting.PrinterData[component].BuildTimeHours * SunOrbit.GameSecondsPerMartianMinute * 60f;

        return(StartPrint());
    }
Ejemplo n.º 8
0
        public static Matter MatchingOre(this Matter refined)
        {
            switch (refined)
            {
            case Matter.Iron:
            case Matter.IronPowder:
                return(Matter.IronOre);

            case Matter.Aluminium:
            case Matter.AluminiumPowder:
                return(Matter.Bauxite);

            case Matter.Copper:
            case Matter.CopperPowder:
                return(Matter.CopperOre);

            case Matter.Nickel:
            case Matter.NickelPowder:
                return(Matter.NickelOre);

            case Matter.Silver:
            case Matter.SilverPowder:
                return(Matter.SilverOre);

            case Matter.Gold:
            case Matter.GoldPowder:
                return(Matter.GoldOre);

            case Matter.Platinum:
                return(Matter.PlatinumOre);

            default:
                return(Matter.Unspecified);
            }
        }
Ejemplo n.º 9
0
 private void Awake()
 {
     interactable  = gameObject.GetComponent <InteractableObject>();
     rend          = gameObject.GetComponent <Renderer>();
     currentMatter = interactable.matter;
     rend.material = currentMatter.matterMaterial;
 }
Ejemplo n.º 10
0
 public GenericResponseVM CheckSecurityGroupInTeamMembers(Client client, Matter matter, IList <string> userId)
 {
     try
     {
         GenericResponseVM genericResponse = null;
         int securityGroupRowNumber        = -1; // Blocked user field has security group
         List <Tuple <int, Principal> > teamMemberPrincipalCollection = new List <Tuple <int, Principal> >();
         if (null != matter && null != matter.AssignUserNames && null != matter.BlockUserNames)
         {
             teamMemberPrincipalCollection = matterRespository.CheckUserSecurity(client, matter, userId);
             foreach (Tuple <int, Principal> teamMemberPrincipal in teamMemberPrincipalCollection)
             {
                 Principal currentTeamMemberPrincipal = teamMemberPrincipal.Item2;
                 if (currentTeamMemberPrincipal.PrincipalType == PrincipalType.SecurityGroup)
                 {
                     securityGroupRowNumber = teamMemberPrincipal.Item1;
                     return(ServiceUtility.GenericResponse(errorSettings.ErrorCodeSecurityGroupExists,
                                                           errorSettings.ErrorMessageSecurityGroupExists + ServiceConstants.DOLLAR + userId[securityGroupRowNumber]));
                 }
             }
         }
         else
         {
             return(ServiceUtility.GenericResponse(errorSettings.IncorrectTeamMembersCode,
                                                   errorSettings.IncorrectTeamMembersMessage));
         }
         return(genericResponse);
     }
     catch (Exception)
     {
         throw;
     }
 }
        private void processNewSite(Matter matter)
        {
            bool success = false;

            if (Settings.Default.UseTemplateExportMethod)
            {
                success = matterProvisioning.createSite(
                    matter,
                    AppDomain.CurrentDomain.BaseDirectory + Settings.Default.MatterTemplateStorageName + ".cmp"
                    );
            }
            else
            {
                success = matterProvisioning.createSiteFromTemplateSolution(
                    matter,
                    Settings.Default.ExistingTemplateSolutionName
                    );
            }

            if (success)
            {
                log.addInformation("Successfully Created a new Litigation Matter site: \"" + matter.MatterName + "\", (" + matter.LMNumber + ")");
                // Set the properties of the new site, set the site's security and generate initial tasks for the matter.
                matterProvisioning.updateProperties(matter);
                if (Settings.Default.EnableTaskGeneraton)
                {
                    matterProvisioning.generateInitialTasks(matter, Settings.Default.TaskListLocation);
                }
                matterProvisioning.setSiteSecurity(matter, Settings.Default.SiteOwnersGroupName, Settings.Default.SiteManagerGroupName, Settings.Default.SiteReadOnlyUsersGroupName, Settings.Default.SiteAdditionalContributorsGroupName);
            }
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> Create(Matter matter)
        {
            var requestHandler = new RequestManager();

            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    requestHandler.CreateRequest(matter);

                    repository.Save(matter);

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View());
                }
            }
            catch
            {
                return(View());
            }
        }
        /// <summary>
        /// Validates the roles for the matter and returns the validation status.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="client">Client Object</param>
        /// <returns>A string value indicating whether validations passed or fail</returns>
        internal static string RoleCheck(RequestObject requestObject, Matter matter, Client client)
        {
            string returnValue = string.Empty;

            try
            {
                using (ClientContext context = ServiceUtility.GetClientContext(requestObject.SPAppToken, new Uri(ServiceConstantStrings.CentralRepositoryUrl), requestObject.RefreshToken))
                {
                    if (0 >= matter.Roles.Count())
                    {
                        return(string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserRolesCode, TextConstants.IncorrectInputUserRolesMessage));
                    }
                    ListItemCollection collListItem = Lists.GetData(context, ServiceConstantStrings.DMSRoleListName, ServiceConstantStrings.DMSRoleQuery);
                    IList <string>     roles        = new List <string>();
                    roles = collListItem.AsEnumerable().Select(roleList => Convert.ToString(roleList[ServiceConstantStrings.RoleListColumnRoleName], CultureInfo.InvariantCulture)).ToList();
                    if (matter.Roles.Except(roles).Count() > 0)
                    {
                        returnValue = string.Format(CultureInfo.InvariantCulture, ConstantStrings.ServiceResponse, TextConstants.IncorrectInputUserRolesCode, TextConstants.IncorrectInputUserRolesMessage);
                    }
                }
            }
            catch (Exception exception)
            {
                ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }

            return(returnValue);
        }
Ejemplo n.º 14
0
 void Awake()
 {
     Unit_Comp       = GetComponent <Unit>();
     Health_Comp     = GetComponent <Health>();
     Matter_Comp     = GetComponent <Matter>();
     SideDefine_Comp = GetComponent <SideDefine>();
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Validates the roles for the matter and returns the validation status.
        /// </summary>
        /// <param name="requestObject">Request Object containing SharePoint App Token</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="client">Client Object</param>
        /// <returns>A string value indicating whether validations passed or fail</returns>
        internal GenericResponseVM RoleCheck(Matter matter)
        {
            GenericResponseVM genericResponse = null;

            try
            {
                if (matter.Roles.Count() <= 0)
                {
                    return(GenericResponse(errorSettings.IncorrectInputUserRolesCode, errorSettings.IncorrectInputUserRolesMessage));
                }
                IList <string> roles = matterRespository.RoleCheck(matterSettings.CentralRepositoryUrl, listNames.DMSRoleListName,
                                                                   camlQueries.DMSRoleQuery);
                if (matter.Roles.Except(roles).Count() > 0)
                {
                    return(GenericResponse(errorSettings.IncorrectInputUserRolesCode, errorSettings.IncorrectInputUserRolesMessage));
                }
                return(genericResponse);
            }
            catch (Exception exception)
            {
                //ToDo: Why in role check function, we are deleting the matter
                //ProvisionHelperFunctions.DeleteMatter(requestObject, client, matter);
                //returnValue = Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
                throw;
            }
        }
Ejemplo n.º 16
0
        public string GetMatterName(HttpClient client, int artifactId)
        {
            Matter matter = new Matter
            {
                matterArtifactID = artifactId
            };

            string queryInputJSON = JsonConvert.SerializeObject(matter);


            StringContent       content  = new StringContent(queryInputJSON, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync("/Relativity.REST/api/Relativity.Services.Matter.IMatterModule/Matter%20Manager/ReadSingleAsync", content).Result;

            string jsonString;

            if (response.IsSuccessStatusCode)
            {
                jsonString = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                throw new Exception("Failed to get matter from Relativity");
            }

            JObject jsonObject = JObject.Parse(jsonString);

            return(jsonObject["Name"].ToString());
        }
Ejemplo n.º 17
0
    // Start is called before the first frame update
    void Start()
    {
        Matter_Comp = GetComponent <Matter>();

        transform.Find("UI").Find("Canvas").Find("MaxHealth").GetChild(0).GetComponent <Image>().fillAmount     = (float)health / (float)maxHealth;
        transform.Find("UI").Find("Canvas").Find("MaxHealth").GetChild(1).GetComponent <TextMeshProUGUI>().text = health.ToString();
    }
Ejemplo n.º 18
0
    public void OnChildTriggerEnter(TriggerForwarder child, Collider c, IMovableSnappable res)
    {
        if (res == null && child.transform.name == "PumpSnap")
        {
            string valveTag = c.tag.ToLower();
            if (valveTag.EndsWith("valve"))
            {
                AttachTo(c, valveTag);
            }
        }
        else if (detachTimer == null && res is ResourceComponent)
        {
            if (ResourceMatchesCurrentPumpable(res as ResourceComponent))
            {
                capturedResource = res as ResourceComponent;
                capturedResource.SnapCrate(this, CrateAnchor.position);

                if (valveType == Matter.Unspecified)
                {
                    if (connectedPumpable is GasStorage && (connectedPumpable as GasStorage).Data.Container.CurrentAmount <= 0f)
                    {
                        this.valveType = capturedResource.Data.Container.MatterType;
                        (connectedPumpable as GasStorage).SpecifyCompound(capturedResource.Data.Container.MatterType);
                        this.SyncMeshesToMatterType();
                    }
                }

                RefreshPumpState();
            }
        }
    }
 public Exception GetReviewsByMatter(ref Matter matter)
 {
     using (OracleConnection oracleConnection = Connection.GetInstance().ConnectionDB())
     {
         OracleCommand oracleCommand = new OracleCommand();
         oracleCommand.Connection  = oracleConnection;
         oracleCommand.CommandText = "PACK_REVIEW.GET_REVIEW_BY_MATTER";
         oracleCommand.CommandType = CommandType.StoredProcedure;
         oracleCommand.Parameters.Add("MATTER_ID_PARAMETER", OracleDbType.Byte).Value = matter.MatterId;
         OracleDataReader oracleDataReader;
         Exception        exceptionToReturn = null;
         try
         {
             oracleConnection.Open();
             oracleDataReader = oracleCommand.ExecuteReader();
             while (oracleDataReader.Read())
             {
                 Review review = new Review();
                 review = Mapping(oracleDataReader);
                 matter.Review.Add(review);
             }
             return(exceptionToReturn);
         }
         catch (Exception exception)
         {
             exceptionToReturn = exception;
             return(exceptionToReturn);
         }
     }
 }
 /// <summary>
 /// Adds given matter to database.
 /// </summary>
 /// <param name="matter">
 /// The matter.
 /// </param>
 /// <returns>
 /// The <see cref="long"/>.
 /// </returns>
 public long SaveToDatabase(Matter matter)
 {
     db.Matter.Add(matter);
     db.SaveChanges();
     Cache.Clear();
     return(matter.Id);
 }
Ejemplo n.º 21
0
 public Class(Date date, Matter matter, string location, Teacher teacher)
 {
     Date     = date;
     Matter   = matter;
     Location = location;
     Teacher  = teacher;
 }
Ejemplo n.º 22
0
    public AttachNode AttachChild(Matter node)
    {
        AttachNode newNode = new AttachNode(node);

        Children.Add(newNode);
        return(newNode);
    }
Ejemplo n.º 23
0
 // Start is called before the first frame update
 void Start()
 {
     if (EmitterBase == null)
     {
         EmitterBase = GetComponentInParent <Matter>();
     }
 }
Ejemplo n.º 24
0
        public static Matter MatchingPowder(this Matter ore)
        {
            switch (ore)
            {
            case Matter.IronOre:
                return(Matter.IronPowder);

            case Matter.Bauxite:
                return(Matter.AluminiumPowder);

            case Matter.CopperOre:
                return(Matter.CopperPowder);

            case Matter.NickelOre:
                return(Matter.NickelPowder);

            case Matter.SilverOre:
                return(Matter.SilverPowder);

            //case Matter.MagnesiumOre:
            //    return Matter.;
            case Matter.GoldOre:
                return(Matter.GoldPowder);

            //case Matter.PlatinumOre:
            //    return Matter.;
            default:
                return(Matter.Unspecified);
            }
        }
Ejemplo n.º 25
0
    private void CheckMarketsForSellOrders()
    {
        if (Market.GlobalResourceList.CurrentAmount() > 0)
        {
            int[] slots = Market.GlobalResourceList.GetNonEmptyMatterSlots();
            if (slots.Length > 0)
            {
                int    randomI   = UnityEngine.Random.Range(0, slots.Length);
                Matter consuming = (Matter)((slots[randomI]) - ChemistryConstants.MinMatterOffset);
                float  amount    = Market.GlobalResourceList.CurrentAmount(consuming);
                Market.GlobalResourceList.Consume(consuming, amount, isCrafting: false);
                int    corpI    = UnityEngine.Random.Range(0, Corporations.Wholesalers.Count);
                Vendor buyer    = Corporations.Wholesalers[corpI];
                int    buyPrice = Corporations.MinimumBuyPrice;
                foreach (var stock in buyer.Stock)
                {
                    if (stock.Matter == consuming)
                    {
                        buyPrice = stock.ListPrice;
                        break;
                    }
                }

                int soldFor = Mathf.CeilToInt(buyPrice * amount);
                Game.Current.Player.BankAccount += soldFor;

                if (this.OnBankAccountChange != null)
                {
                    this.OnBankAccountChange();
                }

                GuiBridge.Instance.ShowNews(NewsSource.MarketSold.CloneWithSuffix(String.Format("{0} for ${1}", consuming.ToString(), soldFor)));
            }
        }
    }
Ejemplo n.º 26
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name")] Matter matter)
        {
            if (id != matter.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(matter);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MatterExists(matter.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(matter));
        }
Ejemplo n.º 27
0
        //---- calculates gravity force amoung two stars
        Vector2 Interaction(Matter M1, Matter M2)
        {
            Vector2 vec_r = M1.q - M2.q;
            double  r     = Vector2.Norm(vec_r);

            return(vec_r * (-G * Mass * Mass / (r * r * r)));
        }
Ejemplo n.º 28
0
        public static float RandomPurity(this Matter ore)
        {
            switch (ore)
            {
            case Matter.IronOre:
                return(UnityEngine.Random.Range(.25f, .45f));

            case Matter.Bauxite:
                return(UnityEngine.Random.Range(.25f, .45f));

            case Matter.NickelOre:
                return(UnityEngine.Random.Range(.1f, .25f));

            case Matter.CopperOre:
                return(UnityEngine.Random.Range(.1f, .2f));

            case Matter.Silica:
                return(UnityEngine.Random.Range(.15f, .35f));

            case Matter.Sulfur:
                return(UnityEngine.Random.Range(.15f, .35f));

            default:
                return(1f);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Remove old users and assign permissions to new users.
        /// </summary>
        /// <param name="clientContext">ClientContext object</param>
        /// <param name="requestObject">RequestObject</param>
        /// <param name="client">Client object</param>
        /// <param name="matter">Matter object</param>
        /// <param name="users">List of users to remove</param>
        /// <param name="isListItem">ListItem or list</param>
        /// <param name="list">List object</param>
        /// <param name="matterLandingPageId">List item id</param>
        /// <param name="isEditMode">Add/ Edit mode</param>
        /// <returns></returns>
        public static bool UpdatePermission(ClientContext clientContext, Matter matter, List <string> users,
                                            string loggedInUserTitle, bool isListItem, string listName, int matterLandingPageId, bool isEditMode)
        {
            bool result = false;

            try
            {
                if (null != clientContext && !string.IsNullOrWhiteSpace(listName))
                {
                    if (isEditMode)
                    {
                        SPList.RemoveSpecificUsers(clientContext, users, loggedInUserTitle, isListItem, listName, matterLandingPageId);
                    }
                    // Add permission
                    if (!isListItem)
                    {
                        result = SPList.SetPermission(clientContext, matter.AssignUserNames, matter.Permissions, listName);
                    }
                    else
                    {
                        result = SPList.SetItemPermission(clientContext, matter.AssignUserNames, "Site Pages",
                                                          matterLandingPageId, matter.Permissions);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            // To avoid the invalid symbol error while parsing the JSON, return the response in lower case
            return(result);
        }
Ejemplo n.º 30
0
 public void AddSink(ISink sink, Matter type)
 {
     if (sink.HasContainerFor(type))
     {
         AddInput(sink.Get(type));
     }
 }
        public ActionResult Index(string[] accessions, bool importGenes)
        {
            return Action(() =>
            {
                var matterNames = new string[accessions.Length];
                var savedMatterNames = new string[accessions.Length];
                var results = new string[accessions.Length];
                var statuses = new string[accessions.Length];

                using (var db = new LibiadaWebEntities())
                {
                    var existingAccessions = db.DnaSequence.Select(d => d.RemoteId).Distinct().ToArray();
                    var dnaSequenceRepository = new DnaSequenceRepository(db);
                    var bioSequences = NcbiHelper.GetGenBankSequences(accessions);

                    for (int i = 0; i < accessions.Length; i++)
                    {
                        string accession = accessions[i];
                        matterNames[i] = accession;
                        if (existingAccessions.Contains(accession) || existingAccessions.Contains(accession + ".1"))
                        {
                            results[i] = "Sequence already exists";
                            statuses[i] = "Exist";
                            continue;
                        }

                        try
                        {
                            var metadata = NcbiHelper.GetMetadata(bioSequences[i]);
                            if (existingAccessions.Contains(metadata.Version.CompoundAccession))
                            {
                                results[i] = "Sequence already exists";
                                statuses[i] = "Exist";
                                continue;
                            }

                            savedMatterNames[i] = NcbiHelper.ExtractSequenceName(metadata) + " | " + metadata.Version.CompoundAccession;
                            matterNames[i] = "Common name=" + metadata.Source.CommonName +
                                             ", Species=" + metadata.Source.Organism.Species +
                                             ", Definition=" + metadata.Definition +
                                             ", Saved matter name=" + savedMatterNames[i];

                            var matter = new Matter
                                             {
                                                 Name = savedMatterNames[i],
                                                 Nature = Nature.Genetic,
                                                 Group = GroupRepository.ExtractSequenceGroup(savedMatterNames[i]),
                                                 SequenceType = SequenceTypeRepsitory.ExtractSequenceGroup(savedMatterNames[i])
                                             };

                            var sequence = new CommonSequence
                                               {
                                                   Matter = matter,
                                                   NotationId = Aliases.Notation.Nucleotide,
                                                   RemoteDbId = Aliases.RemoteDb.RemoteDbNcbi,
                                                   RemoteId = metadata.Version.CompoundAccession
                                               };

                            dnaSequenceRepository.Create(sequence, bioSequences[i], metadata.Definition.ToLower().Contains("partial"));
                            if (importGenes)
                            {
                                try
                                {
                                    using (var subsequenceImporter = new SubsequenceImporter(metadata.Features.All, sequence.Id))
                                    {
                                        subsequenceImporter.CreateSubsequences();
                                    }

                                    var nonCodingCount = db.Subsequence.Count(s => s.SequenceId == sequence.Id && s.FeatureId == Aliases.Feature.NonCodingSequence);
                                    var featuresCount = db.Subsequence.Count(s => s.SequenceId == sequence.Id && s.FeatureId != Aliases.Feature.NonCodingSequence);

                                    statuses[i] = "Success";
                                    results[i] = "Successfully imported  sequence and " + featuresCount + " features and " + nonCodingCount + " non coding subsequences";
                                }
                                catch (Exception exception)
                                {
                                    results[i] = "successfully imported sequence but failed to import genes: " + exception.Message;
                                    statuses[i] = "Error";

                                    if (exception.InnerException != null)
                                    {
                                        results[i] += " " + exception.InnerException.Message;
                                    }
                                }
                            }
                            else
                            {
                                results[i] = "successfully imported sequence";
                                statuses[i] = "Success";
                            }
                        }
                        catch (Exception exception)
                        {
                            results[i] = "Error:" + exception.Message + (exception.InnerException == null ? string.Empty : exception.InnerException.Message);
                            statuses[i] = "Error";
                        }
                    }

                    // removing matters for whitch adding of sequence failed
                    var orphanMatters = db.Matter.Include(m => m.Sequence).Where(m => savedMatterNames.Contains(m.Name) && m.Sequence.Count == 0).ToArray();

                    if (orphanMatters.Length > 0)
                    {
                        db.Matter.RemoveRange(orphanMatters);
                        db.SaveChanges();
                    }
                }

                return new Dictionary<string, object>
                           {
                               { "matterNames", matterNames },
                               { "results", results },
                               { "status", statuses }
                           };
            });
        }
 /// <summary>
 /// The create matter.
 /// </summary>
 /// <param name="matter">
 /// The matter.
 /// </param>
 /// <returns>
 /// The <see cref="long"/>.
 /// </returns>
 private long CreateMatter(Matter matter)
 {
     db.Matter.Add(matter);
     db.SaveChanges();
     return matter.Id;
 }