private void AddNormalContextItem()
 {
     ContextItem C = new ContextItem
     {
         Name = "Your Feature",
         Clicked = HandleContextItemClicked
     };
     //We can add an image if we like using the .Image property
     Variables.iServerGUI.AddContextItem(C);
 }
 private void AddNormalContextItem()
 {
     ContextItem C = new ContextItem
     {
         Name = "Your Feature",
         Clicked = HandleContextItemClicked //This method gets called when your context item is clicked
     };
     //We can add an image if we like using the .Image property
     IServerGUI.AddContextItem(C);
 }
        private void AddContextItemWithChildren()
        {
            List<ContextItem> Children = new List<ContextItem>();
            ContextItem ChildItem = new ContextItem
            {
                Clicked = HandleContextItemClicked,
                Name = "Your Feature"
            };
            //Creating child item 'We can add an image if we like using the .Image property
            Children.Add(ChildItem);
            //Adding child item

            ContextItem C = new ContextItem();
            C.Name = "Client";
            //Your Category, can even be an existing category in Imminent Monitor
            C.Children = Children.ToArray();

            Variables.iServerGUI.AddContextItem(C);
            // Adding the context item
        }
        private void AddContextItemWithChildren()
        {
            List<ContextItem> Children = new List<ContextItem>();
            ContextItem ChildItem = new ContextItem
            {
                Clicked = HandleContextItemClicked, //This method gets called when your context item is clicked
                Name = "Your Feature"
            };

            //Creating child item
            Children.Add(ChildItem);
            //Adding child item

            ContextItem C = new ContextItem();
            C.Name = "Client";
            //Your Category, can even be an existing category in Imminent Monitor
            C.Children = Children.ToArray();

            IServerGUI.AddContextItem(C);
            // Adding the context item
        }
예제 #5
0
파일: DbContext.cs 프로젝트: azturner/Rock
        /// <summary>
        /// Updates the Created/Modified data for any model being created or modified
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
        /// <returns></returns>
        protected virtual List<ContextItem> RockPreSave( DbContext dbContext, PersonAlias personAlias, bool enableAuditing = false )
        {
            int? personAliasId = null;
            if ( personAlias != null )
            {
                personAliasId = personAlias.Id;
            }

            var preSavedEntities = new HashSet<Guid>();

            // First loop through all models calling the PreSaveChanges
            foreach ( var entry in dbContext.ChangeTracker.Entries()
                .Where( c =>
                    c.Entity is IEntity &&
                    ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) )
            {
                if ( entry.Entity is IModel )
                {
                    var model = entry.Entity as IModel;
                    model.PreSaveChanges( this, entry );

                    if ( !preSavedEntities.Contains( model.Guid ) )
                    {
                        preSavedEntities.Add( model.Guid );
                    }
                }
            }

            // Then loop again, as new models may have been added by PreSaveChanges events
            var updatedItems = new List<ContextItem>();
            foreach ( var entry in dbContext.ChangeTracker.Entries()
                .Where( c =>
                    c.Entity is IEntity &&
                    ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) )
            {
                // Cast entry as IEntity
                var entity = entry.Entity as IEntity;

                // Get the context item to track audits
                var contextItem = new ContextItem( entity, entry );

                // If entity was added or modified, update the Created/Modified fields
                if ( entry.State == EntityState.Added || entry.State == EntityState.Modified )
                {
                    // instead of passing "true" the trigger model and UI would support a
                    // on-value-changed checkbox (or perhaps it should be the default/only behavior)
                    // and its value would be passed in to the onValueChange
                    if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreSave, personAlias ) )
                    {
                        return null;
                    }

                    if ( entry.Entity is IModel )
                    {
                        var model = entry.Entity as IModel;

                        if ( !preSavedEntities.Contains( model.Guid ) )
                        {
                            model.PreSaveChanges( this, entry );
                        }

                        // Update Guid/Created/Modified person and times
                        if ( entry.State == EntityState.Added )
                        {
                            if ( !model.CreatedDateTime.HasValue )
                            {
                                model.CreatedDateTime = RockDateTime.Now;
                            }
                            if ( !model.CreatedByPersonAliasId.HasValue )
                            {
                                model.CreatedByPersonAliasId = personAliasId;
                            }

                            if ( model.Guid == Guid.Empty )
                            {
                                model.Guid = Guid.NewGuid();
                            }

                            model.ModifiedDateTime = RockDateTime.Now;
                            model.ModifiedByPersonAliasId = personAliasId;
                        }
                        else if ( entry.State == EntityState.Modified )
                        {
                            model.ModifiedDateTime = RockDateTime.Now;
                            model.ModifiedByPersonAliasId = personAliasId;
                        }
                    }
                }
                else if ( entry.State == EntityState.Deleted )
                {
                    if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreDelete, personAlias ) )
                    {
                        return null;
                    }
                }

                if ( enableAuditing )
                {
                    try
                    {
                            GetAuditDetails( dbContext, contextItem, personAliasId );
                    }
                    catch ( SystemException ex )
                    {
                        ExceptionLogService.LogException( ex, null );
                    }
                }

                updatedItems.Add( contextItem );
            }

            return updatedItems;
        }
예제 #6
0
        private ContextItem CreateQuantitativeResultsContextItem(Model.ShippedItemInstance shippedItemInstance)
        {
            ContextItem results = CreateContextItem("QuantitativeResults", null);

            int quantitateResultIndex = 0;

            foreach (Model.Quantitative quantitativeResult in shippedItemInstance.Results.Quantitative)
            {
                ContextItem quantitativeResultContextItem = CreateContextItem((++quantitateResultIndex).ToString(), null);

                if (quantitativeResult.TypeCode != null)
                {
                    quantitativeResultContextItem.NestedItems.Add(CreateContextItem("typeCode", quantitativeResult.TypeCode));
                }
                if (quantitativeResult.Name != null)
                {
                    quantitativeResultContextItem.NestedItems.Add(CreateContextItem("name", quantitativeResult.Name));
                }

                // Unit of Measure
                ContextItem uomCodeContextItem = CreateContextItem("uomCode", null);
                if (quantitativeResult.UomCode?.Content != null)
                {
                    uomCodeContextItem.NestedItems.Add(CreateContextItem("content", quantitativeResult.UomCode.Content));
                }
                if (quantitativeResult.UomCode?.ListIdentifier != null)
                {
                    uomCodeContextItem.NestedItems.Add(CreateContextItem("listIdentifier", quantitativeResult.UomCode.ListIdentifier));
                }
                if (quantitativeResult.UomCode?.ListAgencyIdentifier != null)
                {
                    uomCodeContextItem.NestedItems.Add(CreateContextItem("listAgencyIdentifier", quantitativeResult.UomCode.ListAgencyIdentifier));
                }
                if (uomCodeContextItem.NestedItems.Count > 0)
                {
                    quantitativeResultContextItem.NestedItems.Add(uomCodeContextItem);
                }

                //Significant Digits
                if (quantitativeResult.SignificantDigitsNumber != null)
                {
                    quantitativeResultContextItem.NestedItems.Add(CreateContextItem("significantDigitsNumber", quantitativeResult.SignificantDigitsNumber));
                }

                // Measurement
                ContextItem measurementsContextItem = CreateContextItem("measurements", null);
                int         measurementIndex        = 0;
                foreach (Model.Measurement measurement in quantitativeResult.Measurements)
                {
                    ContextItem measurementContextItem = CreateContextItem((++measurementIndex).ToString(), null);
                    if (measurement.DateTime != null)
                    {
                        measurementContextItem.NestedItems.Add(CreateContextItem("dateTime", measurement.DateTime));
                    }
                    if (measurement.Measure != null)
                    {
                        measurementContextItem.NestedItems.Add(CreateContextItem("measure", measurement.Measure));
                    }

                    if (measurementContextItem.NestedItems.Count > 0)
                    {
                        measurementsContextItem.NestedItems.Add(measurementContextItem);
                    }
                }

                if (measurementsContextItem.NestedItems.Count > 0)
                {
                    quantitativeResultContextItem.NestedItems.Add(measurementsContextItem);
                }

                // Add to results if any nested items were added
                if (quantitativeResultContextItem.NestedItems.Count > 0)
                {
                    results.NestedItems.Add(quantitativeResultContextItem);
                }
            }

            return(results);
        }
예제 #7
0
 private ContextItem BuildUserContextItem(Telligent.Evolution.Extensibility.Api.Entities.Version1.User user)
 {
     var item = new ContextItem()
     {
         TypeName = "User",
         ApplicationId = user.ContentId,
         ApplicationTypeId = TEApi.Users.ContentTypeId,
         ContainerId = user.ContentId,
         ContainerTypeId = TEApi.Users.ContentTypeId,
         ContentId = user.ContentId,
         ContentTypeId = TEApi.Users.ContentTypeId,
         Id = user.Id.ToString()
     };
     return item;
 }
예제 #8
0
        static void Main(string[] args)
        {
            var testData = JArray.Parse(File.ReadAllText("data.json"));

            string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            var    pluginFactory   = new PluginFactory(applicationPath);

            var admPlugin = pluginFactory.GetPlugin("ADMPlugin");

            admPlugin.Initialize();

            ApplicationDataModel export = new ApplicationDataModel();

            export.Catalog   = new Catalog();
            export.Documents = new Documents();
            List <WorkRecord> workRecords = new List <WorkRecord>();
            List <Summary>    summaries   = new List <Summary>();

            // All of these records are for the same Grower/Farm/Field/CropZone/CropYear so I'm just
            // pulling the common info from the first record.

            #region Create a "crop year" TimeScope to tag each of the WorkRecords with.
            TimeScope cropYear = new TimeScope();
            UniqueId  ourId    = new UniqueId();
            ourId.Id         = testData[0]["CropYear"].ToString();
            ourId.IdType     = IdTypeEnum.String;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            cropYear.Id.UniqueIds.Add(ourId);
            cropYear.Description = testData[0]["CropYear"].ToString();
            cropYear.DateContext = DateContextEnum.CropSeason;
            export.Catalog.TimeScopes.Add(cropYear);
            #endregion

            #region Create the Grower/Farm/Field/CropZone objects for this group of applications
            Grower grower = new Grower();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["ApplicationId"]["DataSourceId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            grower.Id.UniqueIds.Add(ourId);
            grower.Name = testData[0]["GrowerName"].ToString();
            export.Catalog.Growers.Add(grower);

            Farm farm = new Farm();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["FarmId"]["Id"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            farm.Id.UniqueIds.Add(ourId);
            farm.Description = testData[0]["FarmName"].ToString();
            farm.GrowerId    = grower.Id.ReferenceId;
            export.Catalog.Farms.Add(farm);

            Field field = new Field();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["FieldId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            field.Id.UniqueIds.Add(ourId);
            field.Description = testData[0]["FieldName"].ToString();
            field.FarmId      = farm.Id.ReferenceId;
            export.Catalog.Fields.Add(field);

            Crop crop = new Crop();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["CropId"]["Id"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            crop.Id.UniqueIds.Add(ourId);
            crop.Name = testData[0]["Crop"].ToString();
            // Add EPPO code as ContextItem at some point in the future
            export.Catalog.Crops.Add(crop);

            CropZone cropZone = new CropZone();
            ourId            = new UniqueId();
            ourId.Id         = testData[0]["CropZoneId"].ToString();
            ourId.IdType     = IdTypeEnum.UUID;
            ourId.Source     = "www.somecompany.com";
            ourId.SourceType = IdSourceTypeEnum.URI;
            cropZone.Id.UniqueIds.Add(ourId);
            cropZone.Description = testData[0]["CropZoneName"].ToString();
            cropZone.FieldId     = field.Id.ReferenceId;
            cropZone.CropId      = crop.Id.ReferenceId;
            cropZone.TimeScopes.Add(cropYear);
            string areaString = testData[0]["AreaApplied"].ToString();
            double area       = Convert.ToDouble(areaString);
            cropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area));
            export.Catalog.CropZones.Add(cropZone);
            #endregion

            // Foreach Application
            var applicationIds = ((from c in testData select c["ApplicationId"]["Id"]).Distinct()).ToList();
            foreach (var applicationId in applicationIds)
            {
                var appliedProducts = (from c in testData where (string)c["ApplicationId"]["Id"] == applicationId.ToString() select c).ToList();

                // Create a WorkRecord and Summary (ADAPT's version of an Application)
                WorkRecord workRecord = new WorkRecord();
                ourId            = new UniqueId();
                ourId.Id         = appliedProducts[0]["ApplicationId"]["Id"].ToString();
                ourId.IdType     = IdTypeEnum.UUID;
                ourId.Source     = "www.somecompany.com";
                ourId.SourceType = IdSourceTypeEnum.URI;
                workRecord.Id.UniqueIds.Add(ourId);
                workRecord.Description = appliedProducts[0]["ApplicationName"].ToString();
                workRecord.TimeScopes.Add(cropYear);

                TimeScope timingEvent = new TimeScope();
                timingEvent.DateContext = DateContextEnum.TimingEvent;
                timingEvent.Description = appliedProducts[0]["TimingEvent"].ToString();
                workRecord.TimeScopes.Add(timingEvent);

                TimeScope startDate = new TimeScope();
                startDate.DateContext = DateContextEnum.ActualStart;
                startDate.TimeStamp1  = DateTime.Parse(appliedProducts[0]["StartDate"].ToString());
                workRecord.TimeScopes.Add(startDate);

                TimeScope endDate = new TimeScope();
                endDate.DateContext = DateContextEnum.ActualEnd;
                endDate.TimeStamp1  = DateTime.Parse(appliedProducts[0]["EndDate"].ToString());
                workRecord.TimeScopes.Add(endDate);

                Summary summary = new Summary();
                // This property linking the Summary to its parent WorkRecord doesn't exist in ADAPT 1.1.0.8.
                // Slated to be added in next release.
                // summary.WorkRecordId = workRecord.Id.ReferenceId;

                // This property linking the Summary to its Grower doesn't exist in ADAPT 1.1.0.8.
                // Slated to be added in next release.
                // summary.GrowerId = grower.Id.ReferenceId;

                summary.FarmId     = farm.Id.ReferenceId;
                summary.FieldId    = field.Id.ReferenceId;
                summary.CropZoneId = cropZone.Id.ReferenceId;



                // Foreach Product
                foreach (var appliedProduct in appliedProducts)
                {
                    //Note that Manufacturer is not a required property for a given product.
                    Manufacturer manufacturer  = null;
                    var          manufacturers = export.Catalog.Manufacturers.Where(x => (x.Description == appliedProduct["Manufacturer"].ToString())).ToList();
                    if (manufacturers.Count > 0)
                    {
                        manufacturer = manufacturers[0];
                    }
                    else
                    {
                        manufacturer = new Manufacturer();
                        ourId        = new UniqueId();
                        // Couldn't find Manufacturer id in your data
                        ourId.Id         = "00000000-0000-0000-0000-000000000000";
                        ourId.IdType     = IdTypeEnum.UUID;
                        ourId.Source     = "www.somecompany.com";
                        ourId.SourceType = IdSourceTypeEnum.URI;
                        manufacturer.Id.UniqueIds.Add(ourId);
                        manufacturer.Description = appliedProduct["Manufacturer"].ToString();
                        export.Catalog.Manufacturers.Add(manufacturer);
                    }

                    // This is sub-optimal, but it is what we have to work with at the moment.
                    // We're creating the use of each product as its own "operation"
                    OperationSummary operation = new OperationSummary();
                    operation.Data = new List <StampedMeteredValues>();
                    if (appliedProduct["Type"].ToString() == "Seed")
                    {
                        #region Handle Seed
                        CropVariety cropVariety = null;
                        var         products    = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropVariety = products[0] as CropVariety;
                        }
                        else
                        {
                            cropVariety      = new CropVariety();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropVariety.Id.UniqueIds.Add(ourId);
                            cropVariety.Description = appliedProduct["Product"].ToString();
                            cropVariety.CropId      = crop.Id.ReferenceId;
                            if (manufacturer != null)
                            {
                                cropVariety.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            export.Catalog.Products.Add(cropVariety);
                        }
                        operation.ProductId     = cropVariety.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.SowingAndPlanting;
                        #endregion
                    }
                    else if (appliedProduct["Type"].ToString() == "CropProtection")
                    {
                        #region Handle CropProtection
                        CropProtectionProduct cropProtection = null;
                        var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropProtection = products[0] as CropProtectionProduct;
                        }
                        else
                        {
                            cropProtection   = new CropProtectionProduct();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropProtection.Id.UniqueIds.Add(ourId);
                            cropProtection.Description = appliedProduct["Product"].ToString();
                            if (manufacturer != null)
                            {
                                cropProtection.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            if (!string.IsNullOrEmpty(appliedProduct["RegNo"].ToString()))
                            {
                                ContextItem epaNumber = new ContextItem();
                                epaNumber.Code  = "US-EPA-N";
                                epaNumber.Value = ConditionEPA(appliedProduct["RegNo"].ToString(), true, true);
                                cropProtection.ContextItems.Add(epaNumber);
                            }
                            export.Catalog.Products.Add(cropProtection);
                        }
                        operation.ProductId     = cropProtection.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.CropProtection;
                        #endregion
                    }
                    else if (appliedProduct["Type"].ToString() == "Fertilizer")
                    {
                        #region Handle Fertilizer
                        FertilizerProduct cropNutrition = null;
                        var products = export.Catalog.Products.Where(x => (x.Description == appliedProduct["Product"].ToString())).ToList();
                        if (products.Count > 0)
                        {
                            cropNutrition = products[0] as FertilizerProduct;
                        }
                        else
                        {
                            cropNutrition    = new FertilizerProduct();
                            ourId            = new UniqueId();
                            ourId.Id         = appliedProduct["ProductId"]["Id"].ToString();
                            ourId.IdType     = IdTypeEnum.UUID;
                            ourId.Source     = "www.somecompany.com";
                            ourId.SourceType = IdSourceTypeEnum.URI;
                            cropNutrition.Id.UniqueIds.Add(ourId);
                            cropNutrition.Description = appliedProduct["Product"].ToString();
                            if (manufacturer != null)
                            {
                                cropNutrition.ManufacturerId = manufacturer.Id.ReferenceId;
                            }
                            export.Catalog.Products.Add(cropNutrition);
                        }
                        operation.ProductId     = cropNutrition.Id.ReferenceId;
                        operation.OperationType = OperationTypeEnum.Fertilizing;
                        #endregion
                    }

                    StampedMeteredValues smv = new StampedMeteredValues();
                    MeteredValue         mv  = null;

                    NumericRepresentationValue rateValue = null;
                    #region Set the product rate (currently hardcoded to be per acre)
                    switch (appliedProduct["RateUnit"].ToString())
                    {
                    case ("seed"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("kernel"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateSeedsActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("short ton"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("metric ton"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("pound"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        else
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        break;

                    case ("ounce"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("kilogram"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrSeedRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        else
                        {
                            rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        }
                        break;

                    case ("gram"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateMassActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("fluid ounce"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("quart"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("pint"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("milliliter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("liter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("gallon"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("centiliter"):
                        rateValue = new NumericRepresentationValue(RepresentationInstanceList.vrAppRateVolumeActual.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl1ac-1"), Convert.ToDouble(appliedProduct["RateValue"].ToString())));
                        break;

                    case ("acre"):
                        break;

                    default:
                        break;
                    }
                    if (rateValue != null)
                    {
                        mv       = new MeteredValue();
                        mv.Value = rateValue;
                        smv.Values.Add(mv);
                    }
                    #endregion

                    // Set the "applied area" for this use of the product (currently hardcoded to be in acres)
                    NumericRepresentationValue areaValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalAreaCovered.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), Convert.ToDouble(appliedProduct["AreaApplied"].ToString())));
                    mv       = new MeteredValue();
                    mv.Value = areaValue;
                    smv.Values.Add(mv);

                    if (!string.IsNullOrEmpty(appliedProduct["ApplicationMethod"].ToString()))
                    {
                        EnumeratedValue applicationMethod = null;
                        #region Set the product application method
                        switch (appliedProduct["ApplicationMethod"].ToString())
                        {
                        case ("Aerial"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiAerial.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Air Blast"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiAirBlast.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Chemigation"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiChemigation.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Fertigation"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiFertigation.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Banded"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiBand.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Broadcast"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiBroadcast.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - Hooded"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiHoodedSprayer.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground - In Furrow"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInFurrow.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Ground Application"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Planting"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Re-Planting"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiPlanter.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Sidedress"):
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiSideDress.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;

                        case ("Fumigation"):
                        case ("Ground - Incorporated"):
                        case ("Ground - Seed Treatment"):
                        case ("Ground - Variable Rate"):
                        case ("Storage"):
                        case ("Topdress"):
                        case ("Tree Injection"):
                        case ("Water Run"):
                        default:
                            applicationMethod = new EnumeratedValue {
                                Value = DefinedTypeEnumerationInstanceList.dtiInGround.ToModelEnumMember()
                            };
                            applicationMethod.Representation = RepresentationInstanceList.dtApplicationMethod.ToModelRepresentation();
                            break;
                        }
                        if (applicationMethod != null)
                        {
                            mv       = new MeteredValue();
                            mv.Value = applicationMethod;
                            smv.Values.Add(mv);
                        }
                        #endregion
                    }

                    // There is a problem here handling seed totals by bag....will have to come back to this at some point
                    NumericRepresentationValue totalProductValue = null;
                    #region Set the total product
                    switch (appliedProduct["TotalProductUnit"].ToString())
                    {
                    case ("seed"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("kernel"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedSeed.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("seeds"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("short ton"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ton"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("metric ton"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("t"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("pound"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        else
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("lb"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        break;

                    case ("ounce"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("oz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("kilogram"):
                        if (appliedProduct["Type"].ToString() == "Seed")
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalSeedQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        else
                        {
                            totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("kg"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        }
                        break;

                    case ("gram"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedMass.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("g1ac-1"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("fluid ounce"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("floz"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("quart"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("qt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("pint"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("pt"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("milliliter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ml"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("liter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("l"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("gallon"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("gal"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("centiliter"):
                        totalProductValue = new NumericRepresentationValue(RepresentationInstanceList.vrTotalQuantityAppliedVolume.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("cl"), Convert.ToDouble(appliedProduct["TotalProductQty"].ToString())));
                        break;

                    case ("acre"):
                        break;

                    default:
                        break;
                    }
                    if (totalProductValue != null)
                    {
                        mv       = new MeteredValue();
                        mv.Value = totalProductValue;
                        smv.Values.Add(mv);
                    }
                    #endregion

                    operation.Data.Add(smv);

                    // Add the OperationSummary to the collection in Summary
                    summary.OperationSummaries.Add(operation);
                    // End - Foreach Product
                }
                // Add this Summary to the list
                summaries.Add(summary);

                // Add the WorkRecord to the list
                workRecords.Add(workRecord);
                // End - Foreach Application
            }

            // This property is an IEnumerable so we had to build up the collection in a local list then assign it
            export.Documents.Summaries = summaries;
            // This property is an IEnumerable so we had to build up the collection in a local list then assign it
            export.Documents.WorkRecords = workRecords;
            // Make sure the target directory exits
            string outputPath = applicationPath + @"\Output";
            if (Directory.Exists(outputPath))
            {
                Directory.Delete(outputPath, true);
            }
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }
            admPlugin.Export(export, outputPath);

            // NOTE: There is a fundamental problem with this version of ADAPT 1.1.0.8 and the ADMPlugin that prevents
            // the Summary and WorkRecord objects from serializing correctly. This sample will be updated after the MVP
            // process is complete.
        }
예제 #9
0
        /// <summary>
        /// Determines whether the entity matches the current and/or previous qualifier values.
        /// If
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="trigger">The trigger.</param>
        /// <returns>true if matches; false otherwise</returns>
        private static bool IsQualifierMatch(ContextItem item, Dictionary <string, PropertyInfo> properties, WorkflowTrigger trigger)
        {
            bool match = false;

            try
            {
                var dbEntity = item.DbEntityEntry;

                // Now attempt to find a match taking into account the EntityTypeQualifierValue and/or EntityTypeQualifierValuePrevious
                if (properties.ContainsKey(trigger.EntityTypeQualifierColumn.ToLower()))
                {
                    var propertyInfo = properties[trigger.EntityTypeQualifierColumn.ToLower()];

                    bool hasPrevious = !string.IsNullOrEmpty(trigger.EntityTypeQualifierValuePrevious);
                    bool hasCurrent  = !string.IsNullOrEmpty(trigger.EntityTypeQualifierValue);

                    var currentProperty = propertyInfo.GetValue(item.Entity, null);
                    var currentValue    = currentProperty != null?currentProperty.ToString() : string.Empty;

                    var previousValue = string.Empty;

                    if (item.OriginalValues != null && item.OriginalValues.ContainsKey(propertyInfo.Name))
                    {
                        previousValue = item.OriginalValues[propertyInfo.Name].ToStringSafe();
                    }
                    else
                    {
                        var dbPropertyEntry = dbEntity.Property(propertyInfo.Name);
                        if (dbPropertyEntry != null)
                        {
                            previousValue = item.PreSaveState == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue.ToStringSafe();
                        }
                    }

                    if (trigger.WorkflowTriggerType == WorkflowTriggerType.PreDelete ||
                        trigger.WorkflowTriggerType == WorkflowTriggerType.PostDelete)
                    {
                        match = (previousValue == trigger.EntityTypeQualifierValue);
                    }

                    if (trigger.WorkflowTriggerType == WorkflowTriggerType.PostAdd)
                    {
                        match = (currentValue == trigger.EntityTypeQualifierValue);
                    }

                    if (trigger.WorkflowTriggerType == WorkflowTriggerType.ImmediatePostSave ||
                        trigger.WorkflowTriggerType == WorkflowTriggerType.PostSave ||
                        trigger.WorkflowTriggerType == WorkflowTriggerType.PreSave)
                    {
                        if (trigger.WorkflowTriggerValueChangeType == WorkflowTriggerValueChangeType.ValueEqual)
                        {
                            match = trigger.EntityTypeQualifierValue == currentValue;
                        }
                        else
                        {
                            if (hasCurrent && !hasPrevious)
                            {
                                // ...and previous cannot be the same as the current (must be a change)
                                match = (currentValue == trigger.EntityTypeQualifierValue &&
                                         currentValue != previousValue);
                            }
                            else if (!hasCurrent && hasPrevious)
                            {
                                // ...and previous cannot be the same as the current (must be a change)
                                match = (previousValue == trigger.EntityTypeQualifierValuePrevious &&
                                         previousValue != currentValue);
                            }
                            else if (hasCurrent && hasPrevious)
                            {
                                match = (currentValue == trigger.EntityTypeQualifierValue &&
                                         previousValue == trigger.EntityTypeQualifierValuePrevious);
                            }
                            else if (!hasCurrent && !hasPrevious)
                            {
                                match = previousValue != currentValue;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
            }

            return(match);
        }
 private void ChangeContextSelection(ContextItem item)
 {
     for (int i = 0; i < contextMenu.MenuItems.Count; i++)
     {
         contextMenu.MenuItems[i].Checked = false;
     }
     for (int i = 0; i < workMode.Items.Count; i++)
     {
         ((System.Windows.Controls.MenuItem)workMode.Items[i]).IsChecked = false;
     }
     ((System.Windows.Controls.MenuItem)workMode.Items[(int)item]).IsChecked = true;
     contextMenu.MenuItems[(int)item].Checked = true;
     if (contextMenu.MenuItems[0].Checked == true)
     {
         modeTBG1.Text = "Przenoszenie";
         modeTBG2.Text = "Przenoszenie";
         modeTBG3.Text = "Przenoszenie";
         modeTBG4.Text = "Przenoszenie";
     }
     else if (contextMenu.MenuItems[1].Checked == true)
     {
         modeTBG1.Text = "Obracanie";
         modeTBG2.Text = "Obracanie";
         modeTBG3.Text = "Obracanie";
         modeTBG4.Text = "Obracanie";
     }
     else if (contextMenu.MenuItems[2].Checked == true)
     {
         modeTBG1.Text = "Skalowanie";
         modeTBG2.Text = "Skalowanie";
         modeTBG3.Text = "Skalowanie";
         modeTBG4.Text = "Skalowanie";
     }
     else if (contextMenu.MenuItems[3].Checked == true)
     {
         modeTBG1.Text = "Skalowanie wzdłuż osi";
         modeTBG2.Text = "Skalowanie wzdłuż osi";
         modeTBG3.Text = "Skalowanie wzdłuż osi";
         modeTBG4.Text = "Skalowanie wzdłuż osi";
     }
 }
예제 #11
0
 /// <summary>
 /// Handles overflow processing for a container. This should be called once the layout
 /// has determined contentWidth/Height. In addition to the ownerContext passed to the
 /// calculate method, this method also needs the containerSize (the object
 /// returned by getContainerSize).
 /// </summary>
 /// <param name="ownerContext">
 /// </param>
 /// <param name="containerSize">
 /// </param>
 /// <param name="dimensions"><p>A bit mask for the overflow managed dimensions. The 0-bit
 /// is for <c>width</c> and the 1-bit is for <c>height</c>. In other words, a value of 1 would be
 /// only <c>width</c>, 2 would be only <c>height</c> and 3 would be both.</p>
 /// </param>
 public void calculateOverflow(ContextItem ownerContext, object containerSize, JsNumber dimensions)
 {
 }
예제 #12
0
파일: DbContext.cs 프로젝트: Ganon11/Rock
        /// <summary>
        /// Updates the Created/Modified data for any model being created or modified
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        protected virtual List<ContextItem> RockPreSave( DbContext dbContext, PersonAlias personAlias )
        {
            int? personAliasId = null;
            if ( personAlias != null )
            {
                personAliasId = personAlias.Id;
            }

            var updatedItems = new List<ContextItem>();
            foreach ( var entry in dbContext.ChangeTracker.Entries()
                .Where( c =>
                    c.Entity is IEntity &&
                    ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) )
            {
                // Cast entry as IEntity
                var entity = entry.Entity as IEntity;

                // Get the context item to track audits
                var contextItem = new ContextItem( entity, entry.State );

                // If entity was added or modifed, update the Created/Modified fields
                if ( entry.State == EntityState.Added || entry.State == EntityState.Modified )
                {
                    if ( !TriggerWorkflows( entity, WorkflowTriggerType.PreSave, personAlias ) )
                    {
                        return null;
                    }

                    if ( entry.Entity is IModel )
                    {
                        var model = entry.Entity as IModel;

                        model.PreSaveChanges( this, entry.State );

                        // Update Guid/Created/Modified person and times
                        if ( entry.State == EntityState.Added )
                        {
                            if ( !model.CreatedDateTime.HasValue )
                            {
                                model.CreatedDateTime = RockDateTime.Now;
                            }
                            if ( !model.CreatedByPersonAliasId.HasValue )
                            {
                                model.CreatedByPersonAliasId = personAliasId;
                            }

                            if ( model.Guid == Guid.Empty )
                            {
                                model.Guid = Guid.NewGuid();
                            }

                            model.ModifiedDateTime = RockDateTime.Now;
                            model.ModifiedByPersonAliasId = personAliasId;
                        }
                        else if ( entry.State == EntityState.Modified )
                        {
                            model.ModifiedDateTime = RockDateTime.Now;
                            model.ModifiedByPersonAliasId = personAliasId;
                        }

                    }
                }
                else if ( entry.State == EntityState.Deleted )
                {
                    if ( !TriggerWorkflows( entity, WorkflowTriggerType.PreDelete, personAlias ) )
                    {
                        return null;
                    }
                }

                try
                {
                    GetAuditDetails( dbContext, contextItem, personAliasId );
                }
                catch (SystemException ex)
                {
                    ExceptionLogService.LogException( ex, null );
                }

                updatedItems.Add( contextItem );
            }

            return updatedItems;
        }
        private void ParseMapBooks_Context(PageContext pageContext)
        {
            var ApplicationId     = pageContext.GetTokenValue("ApplicationId");
            var ApplicationTypeId = pageContext.GetTokenValue("ApplicationTypeId");
            var allContext        = pageContext.ContextItems.GetAllContextItems();
            var cnt               = allContext.Count;
            int groupId           = -1;
            var applicationId     = allContext[0].ApplicationId.Value;
            var applicationTypeId = allContext[0].ApplicationTypeId.Value;
            var containerId       = allContext[0].ContainerId.Value;
            var contrainerTypeId  = allContext[0].ContainerTypeId;
            var contenId          = allContext[0].ContentId.Value;
            var contentTypeId     = allContext[0].ContentTypeId.Value;
            var typeNameId        = allContext[0].Id;
            var relationship      = allContext[0].Relationship;
            var typename          = allContext[0].TypeName;
            var hashCode          = allContext[0].GetHashCode();


            if (!int.TryParse(allContext[0].Id, out groupId))
            {
                //if groupid is not
                // find by  mapbook name only...
                // TODO: optimize database with safeName and GroupId indexing
            }

            IList <PublicApi.MapBook> mapbooks = new List <PublicApi.MapBook>();

            if (groupId > -1)
            {
                var group = TEApi.Groups.Get(new GroupsGetOptions {
                    Id = groupId
                });
                ContextItem contextItem = new ContextItem();

                try
                {
                    if (groupId >= 0)
                    {
                        mapbooks = PublicApi.MapBooks.List(groupId);
                        if (mapbooks != null)
                        {
                            if (mapbooks.Count == 1)
                            {
                                contextItem.ApplicationId = mapbooks[0].ApplicationId;
                                contextItem.ContentId     = mapbooks[0].ApplicationId;
                            }

                            contextItem.ContainerId     = mapbooks[0].Container.ContainerId;
                            contextItem.ContainerTypeId = mapbooks[0].Container.ContainerTypeId;    //Apis.Get<IGroups>().ContainerTypeId,

                            contextItem.ContentTypeId = mapbooks[0].ApplicationTypeId;
                            contextItem.TypeName      = ApplicationTypeName;
                            contextItem.Id            = mapbooks[0].Group.Id.Value.ToString();
                        }
                        contextItem.TypeName          = ApplicationTypeName;
                        contextItem.ApplicationTypeId = this.ApplicationTypeId;
                    }
                }
                catch (Exception)
                {
                    //throw;
                }

                pageContext.ContextItems.Put(contextItem);
            }
        }
예제 #14
0
 protected override void UpdateTokenContext(TokenContext context)
 {
     base.UpdateTokenContext(context);
     context[nameof(AttributeNameTokenBase)] = new ContextItem(Data, typeof(AttributeArgumentEndToken));
 }
예제 #15
0
 protected override void UpdateTokenContext(TokenContext context)
 {
     context[nameof(FloatNumberAttributeNameToken)] = new ContextItem(this, typeof(AttributeArgumentEndToken));
     base.UpdateTokenContext(context);
     context[RangeToken.AllowRangeKey] = new ContextItem(true, typeof(NumberAttributeRangeToken), typeof(NumberAttributeGreaterToken), typeof(NumberAttributeLessToken));
 }
예제 #16
0
파일: DbContext.cs 프로젝트: azturner/Rock
        /// <summary>
        /// Determines whether the entity matches the current and/or previous qualifier values.
        /// If 
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="trigger">The trigger.</param>
        /// <returns>true if matches; false otherwise</returns>
        private static bool IsQualifierMatch( ContextItem item, Dictionary<string, PropertyInfo> properties, WorkflowTrigger trigger )
        {
            bool match = false;
            var dbEntity = item.DbEntityEntry;

            // Now attempt to find a match taking into account the EntityTypeQualifierValue and/or EntityTypeQualifierValuePrevious
            if ( properties.ContainsKey( trigger.EntityTypeQualifierColumn.ToLower() ) )
            {
                var propertyInfo = properties[trigger.EntityTypeQualifierColumn.ToLower()];

                bool hasPrevious = !string.IsNullOrEmpty( trigger.EntityTypeQualifierValuePrevious );
                bool hasCurrent = !string.IsNullOrEmpty( trigger.EntityTypeQualifierValue );

                // it's apparently not possible to interrogate the dbEntity of virtual properties
                // so it's illegal if they somehow selected one of these; and it's not a match.
                if ( propertyInfo.GetGetMethod().IsVirtual )
                {
                    // TODO: log a silent exception?
                    return false;
                }

                var currentProperty = propertyInfo.GetValue( item.Entity, null );
                var currentValue = currentProperty != null ? currentProperty.ToString() : string.Empty;
                var previousValue = string.Empty;

                var dbPropertyEntry = dbEntity.Property( propertyInfo.Name );
                if ( dbPropertyEntry != null )
                {
                    previousValue = dbEntity.State == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue.ToStringSafe();
                }

                if ( trigger.WorkflowTriggerType == WorkflowTriggerType.PreDelete ||
                    trigger.WorkflowTriggerType == WorkflowTriggerType.PostDelete )
                {
                    match = ( previousValue == trigger.EntityTypeQualifierValue );
                }
                else if ( hasCurrent && !hasPrevious )
                {
                    // ...and previous cannot be the same as the current (must be a change)
                    match = ( currentValue == trigger.EntityTypeQualifierValue &&
                        currentValue != previousValue );
                }
                else if ( !hasCurrent && hasPrevious )
                {
                    // ...and previous cannot be the same as the current (must be a change)
                    match = ( previousValue == trigger.EntityTypeQualifierValuePrevious &&
                        previousValue != currentValue );
                }
                else if ( hasCurrent && hasPrevious )
                {
                    match = ( currentValue == trigger.EntityTypeQualifierValue &&
                        previousValue == trigger.EntityTypeQualifierValuePrevious );
                }
                else if ( !hasCurrent && !hasPrevious )
                {
                    // If they used an entity type qualifier column, at least one qualifier value is required.
                    // TODO: log as silent exception?
                }
            }
            return match;
        }
예제 #17
0
        public ApplicationDataModel.ADM.ApplicationDataModel Import(ISO11783_TaskData taskData)
        {
            if (Properties == null)
            {
                Properties = new Properties();
            }

            ISOTaskData    = taskData;
            UniqueIDMapper = new UniqueIdMapper(ISOTaskData.LinkList);

            AdaptDataModel         = new ApplicationDataModel.ADM.ApplicationDataModel();
            AdaptDataModel.Catalog = new Catalog()
            {
                Description = taskData.FilePath
            };
            AdaptDataModel.Documents = new Documents();

            //Comments
            CodedCommentListMapper commentListMapper = new CodedCommentListMapper(this);
            CodedCommentMapper     commentMapper     = new CodedCommentMapper(this, commentListMapper);

            //Crops - several dependencies require import prior to Products
            IEnumerable <ISOCropType> crops = taskData.ChildElements.OfType <ISOCropType>();

            if (crops.Any())
            {
                CropTypeMapper cropMapper = new CropTypeMapper(this, ProductGroupMapper);
                AdaptDataModel.Catalog.Crops.AddRange(cropMapper.ImportCropTypes(crops));
            }

            //Products
            IEnumerable <ISOProduct> products = taskData.ChildElements.OfType <ISOProduct>();

            if (products.Any())
            {
                ProductMapper         productMapper = new ProductMapper(this, ProductGroupMapper);
                IEnumerable <Product> adaptProducts = productMapper.ImportProducts(products);
                AdaptDataModel.Catalog.Products.AddRange(adaptProducts.Where(p => !AdaptDataModel.Catalog.Products.Contains(p)));
            }

            //Growers
            IEnumerable <ISOCustomer> customers = taskData.ChildElements.OfType <ISOCustomer>();

            if (customers.Any())
            {
                CustomerMapper customerMapper = new CustomerMapper(this);
                AdaptDataModel.Catalog.Growers.AddRange(customerMapper.Import(customers));
            }

            //Farms
            IEnumerable <ISOFarm> farms = taskData.ChildElements.OfType <ISOFarm>();

            if (farms.Any())
            {
                FarmMapper farmMapper = new FarmMapper(this);
                AdaptDataModel.Catalog.Farms.AddRange(farmMapper.Import(farms));
            }

            //Fields & Cropzones
            IEnumerable <ISOPartfield> partFields = taskData.ChildElements.OfType <ISOPartfield>();

            if (partFields.Any())
            {
                PartfieldMapper partFieldMapper = new PartfieldMapper(this);
                AdaptDataModel.Catalog.Fields.AddRange(partFieldMapper.ImportFields(partFields));
                AdaptDataModel.Catalog.CropZones.AddRange(partFieldMapper.ImportCropZones(partFields, crops));
            }

            //Devices

            IEnumerable <ISODevice> devices = taskData.ChildElements.OfType <ISODevice>();

            if (devices.Any())
            {
                //See explanation of MergeSingleBinsIntoBoom in DeviceElementHierarchy
                bool mergeBins;
                if (Properties == null || !bool.TryParse(Properties.GetProperty(MergeSingleBinsIntoBoom), out mergeBins))
                {
                    mergeBins = true;
                }

                //Load the internal objects modeling hierarchies of DETs per DVC
                DeviceElementHierarchies = new DeviceElementHierarchies(devices,
                                                                        RepresentationMapper,
                                                                        mergeBins,
                                                                        taskData.ChildElements.OfType <ISOTask>().SelectMany(t => t.TimeLogs),
                                                                        BaseFolder);

                //Import the ISO DVC & DET data into the actual ADAPT models.
                //During DET import, we use the DeviceElementHierarchies from above to map the actual hierarchies and fill in details.
                DeviceMapper deviceMapper = new DeviceMapper(this);
                AdaptDataModel.Catalog.DeviceModels.AddRange(deviceMapper.ImportDevices(devices));
            }

            //Workers
            IEnumerable <ISOWorker> workers = taskData.ChildElements.OfType <ISOWorker>();

            if (workers.Any())
            {
                WorkerMapper workerMapper = new WorkerMapper(this);
                AdaptDataModel.Catalog.Persons.AddRange(workerMapper.Import(workers));
            }


            //Cultural Practices
            IEnumerable <ISOCulturalPractice> practices = taskData.ChildElements.OfType <ISOCulturalPractice>();

            if (practices.Any())
            {
                foreach (ISOCulturalPractice cpc in practices)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = cpc.CulturalPracticeDesignator
                    });
                }
            }

            //OperationTechniques
            IEnumerable <ISOOperationTechnique> techniques = taskData.ChildElements.OfType <ISOOperationTechnique>();

            if (techniques.Any())
            {
                foreach (ISOOperationTechnique otq in techniques)
                {
                    (AdaptDataModel.Documents.WorkOrders as List <WorkOrder>).Add(new WorkOrder()
                    {
                        Description = otq.OperationTechniqueDesignator
                    });
                }
            }

            IEnumerable <ISOTask> prescribedTasks = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsWorkItemTask);
            IEnumerable <ISOTask> loggedTasks     = taskData.ChildElements.OfType <ISOTask>().Where(t => t.IsLoggedDataTask || t.TimeLogs.Any());

            if (prescribedTasks.Any() || loggedTasks.Any())
            {
                TaskMapper taskMapper = new TaskMapper(this);
                if (prescribedTasks.Any())
                {
                    //Prescribed Tasks
                    IEnumerable <WorkItem> workItems = taskMapper.ImportWorkItems(prescribedTasks);
                    AdaptDataModel.Documents.WorkItems = workItems;
                }

                if (loggedTasks.Any())
                {
                    //Logged Tasks
                    IEnumerable <LoggedData> loggedDatas = taskMapper.ImportLoggedDatas(loggedTasks);
                    AdaptDataModel.Documents.LoggedData = loggedDatas;

                    //Create Work Records for Logged Tasks
                    List <WorkRecord> workRecords = new List <WorkRecord>();
                    foreach (LoggedData data in loggedDatas)
                    {
                        WorkRecord record = new WorkRecord();
                        record.LoggedDataIds.Add(data.Id.ReferenceId);
                        if (data.SummaryId.HasValue)
                        {
                            record.SummariesIds.Add(data.SummaryId.Value);
                            Summary summary = AdaptDataModel.Documents.Summaries.FirstOrDefault(s => s.Id.ReferenceId == data.SummaryId);
                            if (summary != null)
                            {
                                summary.WorkRecordId = record.Id.ReferenceId;
                            }
                        }

                        //Export Derived UTC Delta as a ContextItem
                        //The value will be as accurate as the clock settings and thus terming "Delta" vs "Offset" to underscore this is not an accurate UTC offset for the local timezone
                        //Not rounding value so that relatively accurate GPS UTC values can be reverse calculated from this value.
                        string      offset      = GPSToLocalDelta.HasValue ? GPSToLocalDelta.Value.ToString(CultureInfo.InvariantCulture) : "no data";
                        ContextItem contextItem = new ContextItem()
                        {
                            Code = "GPSUTC_Local_Delta", Value = offset, ValueUOM = "hr"
                        };
                        record.ContextItems.Add(contextItem);

                        workRecords.Add(record);
                    }
                    AdaptDataModel.Documents.WorkRecords = workRecords;
                }
            }

            return(AdaptDataModel);
        }
예제 #18
0
 /// <summary>
 /// Returns the container size (that of the target). Only the fixed-sized dimensions can
 /// be returned because the shrinkWrap dimensions are based on the contentWidth/Height
 /// as determined by the container layout.
 /// If the <see cref="Ext.layout.container.Container.calculateOverflow">calculateOverflow</see> method is used and if <see cref="Ext.layout.container.ContainerConfig.manageOverflow">manageOverflow</see> is
 /// true, this may adjust the width/height by the size of scrollbars.
 /// </summary>
 /// <param name="ownerContext"><p>The owner's context item.</p>
 /// </param>
 /// <param name="inDom"><p>True if the container size must be in the DOM.</p>
 /// <p>Defaults to: <c>false</c></p></param>
 /// <returns>
 /// <span><see cref="Object">Object</see></span><div><p>The size</p>
 /// <ul><li><span>width</span> : <see cref="Number">Number</see><div><p>The width</p>
 /// </div></li><li><span>height</span> : <see cref="Number">Number</see><div><p>The height</p>
 /// </div></li></ul></div>
 /// </returns>
 protected object getContainerSize(ContextItem ownerContext, object inDom = null)
 {
     return(null);
 }
예제 #19
0
        /// <summary>
        /// Updates the Created/Modified data for any model being created or modified
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
        /// <returns></returns>
        protected virtual List <ContextItem> RockPreSave(DbContext dbContext, PersonAlias personAlias, bool enableAuditing = false)
        {
            int?personAliasId = null;

            if (personAlias != null)
            {
                personAliasId = personAlias.Id;
            }

            var preSavedEntities = new HashSet <Guid>();

            // First loop through all models calling the PreSaveChanges
            foreach (var entry in dbContext.ChangeTracker.Entries()
                     .Where(c =>
                            c.Entity is IEntity &&
                            (c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted)))
            {
                if (entry.Entity is IModel)
                {
                    var model = entry.Entity as IModel;
                    model.PreSaveChanges(this, entry, entry.State);

                    if (!preSavedEntities.Contains(model.Guid))
                    {
                        preSavedEntities.Add(model.Guid);
                    }
                }
            }

            // Then loop again, as new models may have been added by PreSaveChanges events
            var updatedItems = new List <ContextItem>();

            foreach (var entry in dbContext.ChangeTracker.Entries()
                     .Where(c =>
                            c.Entity is IEntity &&
                            (c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted)))
            {
                // Cast entry as IEntity
                var entity = entry.Entity as IEntity;

                // Get the context item to track audits
                var contextItem = new ContextItem(entity, entry, enableAuditing);

                // If entity was added or modified, update the Created/Modified fields
                if (entry.State == EntityState.Added || entry.State == EntityState.Modified)
                {
                    // instead of passing "true" the trigger model and UI would support a
                    // on-value-changed checkbox (or perhaps it should be the default/only behavior)
                    // and its value would be passed in to the onValueChange
                    if (!TriggerWorkflows(contextItem, WorkflowTriggerType.PreSave, personAlias))
                    {
                        return(null);
                    }

                    if (entry.Entity is IModel)
                    {
                        var model = entry.Entity as IModel;

                        if (!preSavedEntities.Contains(model.Guid))
                        {
                            model.PreSaveChanges(this, entry);
                        }

                        // Update Guid/Created/Modified person and times
                        if (entry.State == EntityState.Added)
                        {
                            if (!model.CreatedDateTime.HasValue)
                            {
                                model.CreatedDateTime = RockDateTime.Now;
                            }
                            if (!model.CreatedByPersonAliasId.HasValue)
                            {
                                model.CreatedByPersonAliasId = personAliasId;
                            }

                            if (model.Guid == Guid.Empty)
                            {
                                model.Guid = Guid.NewGuid();
                            }

                            model.ModifiedDateTime = RockDateTime.Now;

                            if (!model.ModifiedAuditValuesAlreadyUpdated || model.ModifiedByPersonAliasId == null)
                            {
                                model.ModifiedByPersonAliasId = personAliasId;
                            }
                        }
                        else if (entry.State == EntityState.Modified)
                        {
                            model.ModifiedDateTime = RockDateTime.Now;

                            if (!model.ModifiedAuditValuesAlreadyUpdated || model.ModifiedByPersonAliasId == null)
                            {
                                model.ModifiedByPersonAliasId = personAliasId;
                            }
                        }
                    }
                }
                else if (entry.State == EntityState.Deleted)
                {
                    if (!TriggerWorkflows(contextItem, WorkflowTriggerType.PreDelete, personAlias))
                    {
                        return(null);
                    }
                }

                if (enableAuditing)
                {
                    try
                    {
                        GetAuditDetails(dbContext, contextItem, personAliasId);
                    }
                    catch (SystemException ex)
                    {
                        ExceptionLogService.LogException(ex, null);
                    }
                }

                updatedItems.Add(contextItem);
            }

            return(updatedItems);
        }
 public void ShowContexts(ContextRouter router, ContextItem item,
                          [Context(nameof(OtherContextRouter))]   ContextRouter otherRouter,
                          [Context(nameof(ContextListBox))]       ListBox listBox)
 {
     listBox.BeginInvoke(() => listBox.Items.AddRange(otherRouter.GetAllContexts().OrderBy(c => c).ToArray()));
 }
            public void AddInstanceContext(Guid instanceId, InstanceContext instanceContext)
            {
                ContextItem contextItem;
                int? referenceCount = null;

                lock (lockObject)
                {
                    if (!contextCache.TryGetValue(instanceId, out contextItem))
                    {
                        //This will be the case for activation request.
                        contextItem = new ContextItem(instanceId);
                        referenceCount = contextItem.AddReference();
                        contextCache.Add(instanceId, contextItem);
                    }
                }
                contextItem.InstanceContext = instanceContext;

                if (DiagnosticUtility.ShouldTraceInformation && referenceCount.HasValue)
                {
                    string traceText = SR2.GetString(SR2.DurableInstanceRefCountToInstanceContext, instanceId, referenceCount.Value);
                    TraceUtility.TraceEvent(TraceEventType.Information,
                        TraceCode.InstanceContextBoundToDurableInstance, SR.GetString(SR.TraceCodeInstanceContextBoundToDurableInstance), 
                        new StringTraceRecord("InstanceDetail", traceText),
                        this, null);
                }
            }
 public void ShowTypeMaps(ContextRouter router, ContextItem item,
                          [Context(nameof(OtherContextRouter))]       ContextRouter otherRouter,
                          [Context(nameof(ContextTypeMapsListBox))]   ListBox listBox)
 {
     listBox.BeginInvoke(() => listBox.Items.AddRange(otherRouter.GetTypeContexts().Select(tc => tc.type.Name + " => " + tc.context).ToArray()));
 }
예제 #23
0
        /// <summary>
        /// Saves the entity and returns a list of any entity changes that
        /// need to be logged
        /// </summary>
        /// <param name="PersonId">The id of the person making the change</param>
        /// <param name="audits">The audits.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool Save(int?PersonId, out List <Audit> audits, out List <string> errorMessages)
        {
            audits        = new List <Audit>();
            errorMessages = new List <string>();

            Context.ChangeTracker.DetectChanges();

            var addedEntities    = new List <ContextItem>();
            var deletedEntities  = new List <ContextItem>();
            var modifiedEntities = new List <ContextItem>();

            var contextAdapter = ((IObjectContextAdapter)Context);

            foreach (ObjectStateEntry entry in contextAdapter.ObjectContext.ObjectStateManager.GetObjectStateEntries(
                         EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged))
            {
                var rockEntity = entry.Entity as Entity <T>;

                if (rockEntity != null)
                {
                    var contextItem = new ContextItem(rockEntity);
                    switch (entry.State)
                    {
                    case EntityState.Added:
                    {
                        contextItem.Audit.AuditType = AuditType.Add;
                        addedEntities.Add(contextItem);
                        break;
                    }

                    case EntityState.Deleted:
                    {
                        contextItem.Audit.AuditType = AuditType.Delete;
                        deletedEntities.Add(contextItem);
                        break;
                    }

                    case EntityState.Modified:
                    {
                        bool cancel = false;
                        rockEntity.RaiseUpdatingEvent(out cancel, PersonId);
                        if (cancel)
                        {
                            errorMessages.Add(string.Format("Update cancelled by {0} event handler", rockEntity.TypeName));
                            contextAdapter.ObjectContext.Detach(entry);
                        }
                        else
                        {
                            contextItem.Audit.AuditType = AuditType.Modify;
                            deletedEntities.Add(contextItem);
                        }

                        break;
                    }
                    }

                    Type rockEntityType = rockEntity.GetType();
                    if (rockEntityType.Namespace == "System.Data.Entity.DynamicProxies")
                    {
                        rockEntityType = rockEntityType.BaseType;
                    }

                    if (AuditClass(rockEntityType))
                    {
                        var dbEntity = Context.Entry(entry.Entity);
                        var audit    = contextItem.Audit;

                        PropertyInfo[] properties = rockEntityType.GetProperties();

                        foreach (PropertyInfo propInfo in properties)
                        {
                            if (AuditProperty(propInfo))
                            {
                                var dbPropertyEntry = dbEntity.Property(propInfo.Name);
                                if (dbPropertyEntry != null && (
                                        dbEntity.State == EntityState.Added ||
                                        dbEntity.State == EntityState.Deleted ||
                                        dbPropertyEntry.IsModified))
                                {
                                    var currentValue  = dbEntity.State != EntityState.Deleted ? dbPropertyEntry.CurrentValue : string.Empty;
                                    var originalValue = dbEntity.State != EntityState.Added ? dbPropertyEntry.OriginalValue : string.Empty;

                                    var detail = new AuditDetail();
                                    detail.Property     = propInfo.Name;
                                    detail.CurrentValue = currentValue != null?currentValue.ToString() : string.Empty;

                                    detail.OriginalValue = originalValue != null?originalValue.ToString() : string.Empty;

                                    if (detail.CurrentValue != detail.OriginalValue)
                                    {
                                        audit.Details.Add(detail);
                                    }
                                }
                            }
                        }

                        if (audit.Details.Any())
                        {
                            var entityType = Rock.Web.Cache.EntityTypeCache.Read(rockEntity.TypeName, false);
                            if (entityType != null)
                            {
                                string title = rockEntity.ToString();
                                if (string.IsNullOrWhiteSpace(title))
                                {
                                    title = entityType.FriendlyName ?? string.Empty;
                                }
                                audit.DateTime     = DateTime.Now;
                                audit.PersonId     = PersonId;
                                audit.EntityTypeId = entityType.Id;
                                audit.EntityId     = rockEntity.Id;
                                audit.Title        = title.Truncate(195);
                            }
                        }
                    }
                }
            }

            if (errorMessages.Count > 0)
            {
                return(false);
            }

            try
            {
                Context.SaveChanges();

                foreach (var contextItem in addedEntities.Where(i => i.Audit.DateTime.HasValue))
                {
                    contextItem.Audit.EntityId = contextItem.Entity.Id;
                    audits.Add(contextItem.Audit);
                }
                foreach (var contextItem in modifiedEntities.Where(i => i.Audit.DateTime.HasValue))
                {
                    audits.Add(contextItem.Audit);
                }
                foreach (var contextItem in deletedEntities.Where(i => i.Audit.DateTime.HasValue))
                {
                    audits.Add(contextItem.Audit);
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException e)
            {
                var outputLines = new List <string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
                                        "{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:",
                                        DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format(
                                            "- Property: \"{0}\", Error: \"{1}\"",
                                            ve.PropertyName, ve.ErrorMessage));
                    }
                }

                throw new Exception(outputLines.AsDelimited("\n"));
            }

            foreach (object modifiedEntity in addedEntities.Select(e => e.Entity).ToList())
            {
                var model = modifiedEntity as Entity <T>;
                if (model != null)
                {
                    model.RaiseAddedEvent(PersonId);
                }
            }

            foreach (object deletedEntity in deletedEntities.Select(e => e.Entity).ToList())
            {
                var model = deletedEntity as Entity <T>;
                if (model != null)
                {
                    model.RaiseDeletedEvent(PersonId);
                }
            }

            foreach (object modifiedEntity in modifiedEntities.Select(e => e.Entity).ToList())
            {
                var model = modifiedEntity as Entity <T>;
                if (model != null)
                {
                    model.RaiseUpdatedEvent(PersonId);
                }
            }

            return(true);
        }
 public void ShowListenerSelection(ContextRouter router, ContextItem item,
                                   [Context(nameof(ListenerTextBox))]      TextBox textBox,
                                   [Context(nameof(SelectedListener))]     string name)
 {
     textBox.BeginInvoke(() => textBox.Text = name);
 }
예제 #25
0
        private ContextItem CreateItemIdentifierSetsContextItem(Model.ShippedItemInstance shippedItemInstance)
        {
            ContextItem itemIdentifierSetsContextItem = CreateContextItem("ItemIdentifierSets", null);

            int identifierSetIndex = 0;

            foreach (Model.ItemIdentifierSet itemIdentifierSet in shippedItemInstance.ItemIdentifierSets)
            {
                ContextItem itemIdentifierSetContextItem = CreateContextItem((++identifierSetIndex).ToString(), null);
                if (itemIdentifierSet.SchemeIdentifier != null)
                {
                    itemIdentifierSetContextItem.NestedItems.Add(CreateContextItem("schemeIdentifier", itemIdentifierSet.SchemeIdentifier));
                }
                if (itemIdentifierSet.SchemeVersionIdentifier != null)
                {
                    itemIdentifierSetContextItem.NestedItems.Add(CreateContextItem("schemaVersionIdentifier", itemIdentifierSet.SchemeVersionIdentifier));
                }
                if (itemIdentifierSet.SchemeAgencyIdentifier != null)
                {
                    itemIdentifierSetContextItem.NestedItems.Add(CreateContextItem("schemaAgencyIdentifier", itemIdentifierSet.SchemeAgencyIdentifier));
                }
                if (itemIdentifierSet.TypeCode != null)
                {
                    itemIdentifierSetContextItem.NestedItems.Add(CreateContextItem("typeCode", itemIdentifierSet.TypeCode));
                }

                ContextItem identifiersContextItem = CreateContextItem("identifiers", null);
                int         identifierIndex        = 0;
                foreach (Model.ItemIdentifier identifier in itemIdentifierSet.Identifiers)
                {
                    ContextItem identifierContextItem = CreateContextItem((++identifierIndex).ToString(), null);
                    if (identifier.Content != null)
                    {
                        identifierContextItem.NestedItems.Add(CreateContextItem("content", identifier.Content));
                    }
                    if (identifier.SchemeIdentifier != null)
                    {
                        identifierContextItem.NestedItems.Add(CreateContextItem("schemaIdentifier", identifier.SchemeIdentifier));
                    }
                    if (identifier.SchemeAgencyIdentifier != null)
                    {
                        identifierContextItem.NestedItems.Add(CreateContextItem("schemaAgencyIdentifier", identifier.SchemeAgencyIdentifier));
                    }
                    if (identifier.TypeCode != null)
                    {
                        identifierContextItem.NestedItems.Add(CreateContextItem("typeCode", identifier.TypeCode));
                    }
                    if (identifierContextItem.NestedItems.Count > 0)
                    {
                        identifiersContextItem.NestedItems.Add(identifierContextItem);
                    }
                }

                if (identifiersContextItem.NestedItems.Count > 0)
                {
                    itemIdentifierSetContextItem.NestedItems.Add(identifiersContextItem);
                }

                if (itemIdentifierSetContextItem.NestedItems.Count > 0)
                {
                    itemIdentifierSetsContextItem.NestedItems.Add(itemIdentifierSetContextItem);
                }
            }

            return(itemIdentifierSetsContextItem);
        }
예제 #26
0
		internal void PushScope ()
		{
			ContextItem item = null;
			if (contextItems.Count == contextItemCount) {
				item = new ContextItem ();
				contextItems.Add (item);
			}
			else
				item = (ContextItem) contextItems [contextItemCount];
			item.BaseURI = BaseURI;
			item.XmlLang = XmlLang;
			item.XmlSpace = XmlSpace;
			contextItemCount++;
		}
예제 #27
0
        private List <ContextItem> CreateProductContextItems(Model.ShippedItemInstance shippedItemInstance)
        {
            List <ContextItem> contextItems = new List <ContextItem>();

            if (shippedItemInstance.TypeCode != null)
            {
                contextItems.Add(CreateContextItem("TypeCode", shippedItemInstance.TypeCode));
            }
            if (shippedItemInstance.Item?.Description != null)
            {
                contextItems.Add(CreateContextItem("ItemDescription", shippedItemInstance.Item.Description));
            }
            if (shippedItemInstance.Item?.ProductName != null)
            {
                contextItems.Add(CreateContextItem("ItemProductName", shippedItemInstance.Item.ProductName));
            }
            if (shippedItemInstance.Item?.BrandName != null)
            {
                contextItems.Add(CreateContextItem("ItemBrandName", shippedItemInstance.Item.BrandName));
            }
            if (shippedItemInstance.Item?.VarietyName != null)
            {
                contextItems.Add(CreateContextItem("ItemVarietyName", shippedItemInstance.Item.VarietyName));
            }

            // Classification
            ContextItem classificationContextItem = CreateContextItem("Classification", null);

            if (shippedItemInstance.Classification?.TypeCode != null)
            {
                classificationContextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.Classification.TypeCode));
            }
            if (shippedItemInstance.Classification?.Codes?.Codes?.Count > 0)
            {
                ContextItem codesContextItem = CreateContextItem("codes", null);
                int         codeIndex        = 0;
                foreach (Model.Code code in shippedItemInstance.Classification.Codes.Codes)
                {
                    ContextItem codeContextItem = CreateContextItem((++codeIndex).ToString(), null);

                    if (code.Content != null)
                    {
                        codeContextItem.NestedItems.Add(CreateContextItem("content", code.Content));
                    }
                    if (code.ListAgencyIdentifier != null)
                    {
                        codeContextItem.NestedItems.Add(CreateContextItem("listAgencyIdentifier", code.ListAgencyIdentifier));
                    }
                    if (code.TypeCode != null)
                    {
                        codeContextItem.NestedItems.Add(CreateContextItem("typeCode", code.TypeCode));
                    }

                    if (codeContextItem.NestedItems.Count > 0)
                    {
                        codesContextItem.NestedItems.Add(codeContextItem);
                    }
                }

                if (codesContextItem.NestedItems.Count > 0)
                {
                    classificationContextItem.NestedItems.Add(codesContextItem);
                }
            }
            if (classificationContextItem.NestedItems.Count > 0)
            {
                contextItems.Add(classificationContextItem);
            }

            // ManufacturingParty
            ContextItem manufacturingPartyContextItem = CreateContextItem("manufacturingParty", null);

            if (shippedItemInstance.ManufacturingParty?.Name != null)
            {
                manufacturingPartyContextItem.NestedItems.Add(CreateContextItem("name", shippedItemInstance.ManufacturingParty.Name));
            }
            ContextItem identifierContextItem = CreateContextItem("identifier", null);

            if (shippedItemInstance.ManufacturingParty?.Identifier?.Content != null)
            {
                identifierContextItem.NestedItems.Add(CreateContextItem("content", shippedItemInstance.ManufacturingParty.Identifier.Content));
            }
            if (shippedItemInstance.ManufacturingParty?.Identifier?.TypeCode != null)
            {
                identifierContextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.ManufacturingParty.Identifier.TypeCode));
            }
            if (identifierContextItem.NestedItems.Count > 0)
            {
                manufacturingPartyContextItem.NestedItems.Add(identifierContextItem);
            }
            if (manufacturingPartyContextItem.NestedItems.Count > 0)
            {
                contextItems.Add(manufacturingPartyContextItem);
            }

            return(contextItems);
        }
예제 #28
0
        /// <summary>
        /// Determines whether the entity matches the current and/or previous qualifier values.
        /// If
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="properties">The properties.</param>
        /// <param name="trigger">The trigger.</param>
        /// <returns>true if matches; false otherwise</returns>
        private static bool IsQualifierMatch(ContextItem item, Dictionary <string, PropertyInfo> properties, WorkflowTrigger trigger)
        {
            bool match    = false;
            var  dbEntity = item.DbEntityEntry;

            // Now attempt to find a match taking into account the EntityTypeQualifierValue and/or EntityTypeQualifierValuePrevious
            if (properties.ContainsKey(trigger.EntityTypeQualifierColumn.ToLower()))
            {
                var propertyInfo = properties[trigger.EntityTypeQualifierColumn.ToLower()];

                bool hasPrevious = !string.IsNullOrEmpty(trigger.EntityTypeQualifierValuePrevious);
                bool hasCurrent  = !string.IsNullOrEmpty(trigger.EntityTypeQualifierValue);

                // it's apparently not possible to interrogate the dbEntity of virtual properties
                // so it's illegal if they somehow selected one of these; and it's not a match.
                if (propertyInfo.GetGetMethod().IsVirtual)
                {
                    // TODO: log a silent exception?
                    return(false);
                }

                var currentProperty = propertyInfo.GetValue(item.Entity, null);
                var currentValue    = currentProperty != null?currentProperty.ToString() : string.Empty;

                var previousValue = string.Empty;

                var dbPropertyEntry = dbEntity.Property(propertyInfo.Name);
                if (dbPropertyEntry != null)
                {
                    previousValue = dbEntity.State == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue.ToStringSafe();
                }

                if (trigger.WorkflowTriggerType == WorkflowTriggerType.PreDelete ||
                    trigger.WorkflowTriggerType == WorkflowTriggerType.PostDelete)
                {
                    match = (previousValue == trigger.EntityTypeQualifierValue);
                }

                if (trigger.WorkflowTriggerType == WorkflowTriggerType.ImmediatePostSave ||
                    trigger.WorkflowTriggerType == WorkflowTriggerType.PostSave)
                {
                    match = (currentValue == trigger.EntityTypeQualifierValue);
                }

                if (trigger.WorkflowTriggerType == WorkflowTriggerType.PreSave)
                {
                    if (hasCurrent && !hasPrevious)
                    {
                        // ...and previous cannot be the same as the current (must be a change)
                        match = (currentValue == trigger.EntityTypeQualifierValue &&
                                 currentValue != previousValue);
                    }
                    else if (!hasCurrent && hasPrevious)
                    {
                        // ...and previous cannot be the same as the current (must be a change)
                        match = (previousValue == trigger.EntityTypeQualifierValuePrevious &&
                                 previousValue != currentValue);
                    }
                    else if (hasCurrent && hasPrevious)
                    {
                        match = (currentValue == trigger.EntityTypeQualifierValue &&
                                 previousValue == trigger.EntityTypeQualifierValuePrevious);
                    }
                    else if (!hasCurrent && !hasPrevious)
                    {
                        // If they used an entity type qualifier column, at least one qualifier value is required.
                        // TODO: log as silent exception?
                    }
                }
            }
            return(match);
        }
예제 #29
0
		public void Add(ContextItem contextItem)
		{
			items.Add(contextItem);
		}
예제 #30
0
 public DescriberForm(ContextItem item) : this(item.Data)
 {
     this.txtDescribeObject.Text = item.Name;
 }
예제 #31
0
파일: DbContext.cs 프로젝트: azturner/Rock
        private static void GetAuditDetails( DbContext dbContext, ContextItem item, int? personAliasId )
        {
            // Get the base class (not the proxy class)
            Type rockEntityType = item.Entity.GetType();
            if ( rockEntityType.IsDynamicProxyType() )
            {
                rockEntityType = rockEntityType.BaseType;
            }

            // Check to make sure class does not have [NotAudited] attribute
            if ( AuditClass( rockEntityType ) )
            {
                var dbEntity = item.DbEntityEntry;
                var audit = item.Audit;

                PropertyInfo[] properties = rockEntityType.GetProperties();

                foreach ( PropertyInfo propInfo in properties )
                {
                    // Check to make sure property does not have the [NotAudited] attribute
                    if ( AuditProperty( propInfo ) )
                    {
                        // If entire entity was added or deleted or this property was modified
                        var dbPropertyEntry = dbEntity.Property( propInfo.Name );
                        if ( dbPropertyEntry != null && (
                            dbEntity.State == EntityState.Added ||
                            dbEntity.State == EntityState.Deleted ||
                            dbPropertyEntry.IsModified ) )
                        {
                            var currentValue = dbEntity.State == EntityState.Deleted ? string.Empty : dbPropertyEntry.CurrentValue;
                            var originalValue = dbEntity.State == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue;

                            var detail = new AuditDetail();
                            detail.Property = propInfo.Name;
                            detail.CurrentValue = currentValue != null ? currentValue.ToString() : string.Empty;
                            detail.OriginalValue = originalValue != null ? originalValue.ToString() : string.Empty;
                            if ( detail.CurrentValue != detail.OriginalValue )
                            {
                                audit.Details.Add( detail );
                            }
                        }
                    }
                }

                if ( audit.Details.Any() )
                {
                    var entityType = Rock.Web.Cache.EntityTypeCache.Read( rockEntityType );
                    if ( entityType != null )
                    {
                        string title;
                        try
                        {
                            title = item.Entity.ToString();
                        }
                        catch
                        {
                            // ignore exception (Entity often overrides ToString() and we don't want that prevent the audit if it fails)
                            title = null;
                        }

                        if ( string.IsNullOrWhiteSpace( title ) )
                        {
                            title = entityType.FriendlyName ?? string.Empty;
                        }
                        audit.DateTime = RockDateTime.Now;
                        audit.PersonAliasId = personAliasId;
                        audit.EntityTypeId = entityType.Id;
                        audit.EntityId = item.Entity.Id;
                        audit.Title = title.Truncate( 195 );
                    }
                }
            }
        }
예제 #32
0
 public string DescribeItem(ContextItem item)
 {
     return(this.GetObjectDescription(item.Data));
 }
예제 #33
0
파일: DbContext.cs 프로젝트: azturner/Rock
        /// <summary>
        /// Triggers all the workflows of the given triggerType for the given entity item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="triggerType">Type of the trigger.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private bool TriggerWorkflows( ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias )
        {
            IEntity entity = item.Entity;
            Dictionary<string, PropertyInfo> properties = null;

            using ( var rockContext = new RockContext() )
            {
                var workflowTypeService = new WorkflowTypeService( rockContext );
                var workflowService = new WorkflowService( rockContext );

                // Look at each trigger for this entity and for the given trigger type
                // and see if it's a match.
                foreach ( var trigger in TriggerCache.Triggers( entity.TypeName, triggerType ).Where( t => t.IsActive == true ) )
                {
                    bool match = true;

                    // If a qualifier column was given, then we need to check the previous or current qualifier value
                    // otherwise it's just an automatic match.
                    if ( !string.IsNullOrWhiteSpace( trigger.EntityTypeQualifierColumn ) )
                    {
                        // Get and cache the properties https://lotsacode.wordpress.com/2010/04/13/reflection-type-getproperties-and-performance/
                        // (Note: its possible that none of the triggers need them, so future TODO could be to
                        // bypass all this in that case.
                        if ( properties == null )
                        {
                            properties = new Dictionary<string, PropertyInfo>();
                            foreach ( PropertyInfo propertyInfo in entity.GetType().GetProperties() )
                            {
                                properties.Add( propertyInfo.Name.ToLower(), propertyInfo );
                            }
                        }

                        match = IsQualifierMatch( item, properties, trigger );
                    }

                    // If we found a matching trigger, then fire it; otherwise do nothing.
                    if ( match )
                    {
                        // If it's one of the pre or immediate triggers, fire it immediately; otherwise queue it.
                        if ( triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete || triggerType == WorkflowTriggerType.ImmediatePostSave )
                        {
                            var workflowType = workflowTypeService.Get( trigger.WorkflowTypeId );

                            if ( workflowType != null )
                            {
                                var workflow = Rock.Model.Workflow.Activate( workflowType, trigger.WorkflowName );

                                List<string> workflowErrors;
                                if ( !workflowService.Process( workflow, entity, out workflowErrors ) )
                                {
                                    SaveErrorMessages.AddRange( workflowErrors );
                                    return false;
                                }
                            }
                        }
                        else
                        {
                            var transaction = new Rock.Transactions.WorkflowTriggerTransaction();
                            transaction.Trigger = trigger;
                            transaction.Entity = entity.Clone();
                            transaction.PersonAlias = personAlias;
                            Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
                        }
                    }
                }
            }

            return true;
        }
예제 #34
0
        private Tuple <List <ISOLink>, List <string> > GetLinksForContextItem(string isoIDRef, ContextItem item, string prefix)
        {
            List <ISOLink> output = new List <ISOLink>();
            List <string>  errors = new List <string>();

            prefix = string.Concat(prefix, item.Code);
            if (item.NestedItems != null && item.NestedItems.Any())
            {
                prefix = string.Concat(prefix, ".");
                foreach (ContextItem nestedItem in item.NestedItems)
                {
                    output.AddRange(GetLinksForContextItem(isoIDRef, nestedItem, prefix).Item1);
                }
            }
            else
            {
                string value = $"{prefix}|{item.Value}";
                if (value.Length <= 255) //We can only export links up to 255 characters
                {
                    output.Add(new ISOLink()
                    {
                        LinkValue = value, ObjectIdRef = isoIDRef
                    });
                }
                else
                {
                    errors.Add($"Value too long.  Context item skipped. {value}");
                }
            }
            return(new Tuple <List <ISOLink>, List <string> >(output, errors));
        }
예제 #35
0
        private string _extendNodeText(string nodeText, object obj, Type type)
        {
            if (obj == null)
            {
                return(nodeText);
            }

            // Don't know if thats very fancy code - but also for Int32 I'd like
            // to see their value.
            // For all other objects I try to add ReferenceId and one of Description,
            // Name or LastName.

            if (nodeText.IndexOf(':') >= 0) // Don't overwrite existing Values
            {
                System.Diagnostics.Debug.Assert(false, "Does this ever happen?");
                return(nodeText);
            }

            // OK, Text property doesn't hold a value...
            if (obj is Int32) // Is it a Int32?
            {
                Int32 n = (Int32)obj;
                nodeText += $": {n}";
            }
            else
            {
                List <string> addenum = new List <string>();

                // Special handling for ContextItems.
                // Show Code and Value. Indicate nested items with a +.
                if (obj is ContextItem)
                {
                    ContextItem ci = (ContextItem)obj;
                    if (!string.IsNullOrWhiteSpace(ci.Code))
                    {
                        addenum.Add(ci.Code);
                    }
                    if (!string.IsNullOrWhiteSpace(ci.Value))
                    {
                        addenum.Add(ci.Value);
                    }
                    if (ci.NestedItems.Count > 0)
                    {
                        addenum.Add("+");
                    }
                }
                // Special handling for MeteredValue with NumericRepresentation
                // Show the Code of the NumericRepresentationValue (vrTotalAreaCovered, ...) as
                // well as Value (Value.Value) and Code (Value.UnitOfMeasure.Code).
                else if ((obj is MeteredValue) && (((MeteredValue)obj).Value is NumericRepresentationValue))
                {
                    NumericRepresentationValue nrv = (NumericRepresentationValue)((MeteredValue)obj).Value;
                    if (!string.IsNullOrWhiteSpace(nrv.Representation.Code))
                    {
                        addenum.Add(nrv.Representation.Code);
                    }
                    // For NumericValue there is also a dedicated block some lines down :-/
                    NumericValue nv = nrv.Value;
                    if (!string.IsNullOrWhiteSpace(nv.UnitOfMeasure.Code))
                    {
                        addenum.Add($"{nv.Value:#,##0.####} {nv.UnitOfMeasure.Code}");
                    }
                }
                else
                {
                    // Generic handling for all types

                    // Add value of ReferenceId
                    PropertyInfo pi = type.GetProperty("Id");
                    if (pi != null)
                    {
                        CompoundIdentifier ci = pi.GetValue(obj) as CompoundIdentifier;
                        if (ci != null)
                        {
                            addenum.Add(ci.ReferenceId.ToString());
                        }
                    }
                    // Add one of the following...
                    pi = type.GetProperty("Description");
                    if (pi == null)
                    {
                        pi = type.GetProperty("Name");
                    }
                    if (pi == null)
                    {
                        pi = type.GetProperty("LastName");
                    }
                    if (pi != null)
                    {
                        string designator = pi.GetValue(obj) as string;
                        if (designator != null)
                        {
                            addenum.Add(designator);
                        }
                    }

                    // Additional handling for TimeScope
                    if (obj is TimeScope)
                    {
                        TimeScope ts = (TimeScope)obj;
                        addenum.Add($"dcx {ts.DateContext}");
                        if (ts.TimeStamp1.HasValue)
                        {
                            addenum.Add($"ts1 {ts.TimeStamp1.Value.ToNiceDateTime()}");
                        }
                        if (ts.TimeStamp2.HasValue)
                        {
                            addenum.Add($"ts2 {ts.TimeStamp2.Value.ToNiceDateTime()}");
                        }
                        if (ts.Duration.HasValue)
                        {
                            addenum.Add($"d {ts.Duration}");
                        }
                    }
                    // Additional handling for NumericRepresentationValue
                    else if (obj is NumericRepresentationValue)
                    {
                        NumericValue nv = ((NumericRepresentationValue)obj).Value;
                        if (nv.UnitOfMeasure != null && !string.IsNullOrWhiteSpace(nv.UnitOfMeasure.Code))
                        {
                            addenum.Add($"{nv.Value:#,##0.####} {nv.UnitOfMeasure.Code}");
                        }
                    }
                }

                if (addenum.Count > 0)
                {
                    nodeText += " [" + String.Join(", ", addenum) + "]";
                }
            }

            return(nodeText);
        }
예제 #36
0
        /// <summary>
        /// Returns a list of ContextItems from the LinkGroup matching the object ID
        /// </summary>
        /// <param name="isoObjectIdRef"></param>
        /// <param name="linkGroupDescription">If supplied, the link grup description must match</param>
        /// <returns></returns>
        public List <ContextItem> ImportContextItemsFromLinkList(string isoObjectIdRef, string linkGroupDescription)
        {
            List <ContextItem> outputItems = new List <ContextItem>();

            if (LinkList != null)
            {
                foreach (ISOLinkGroup isoLinkGroup in LinkList.LinkGroups.Where(lg => lg.LinkGroupDesignator != null && lg.LinkGroupDesignator.Equals(linkGroupDescription)))
                {
                    foreach (ISOLink link in isoLinkGroup.Links.Where(link => link.ObjectIdRef == isoObjectIdRef))
                    {
                        string[]      codesVsValue  = link.LinkValue.Split('|');
                        string        code          = codesVsValue[0];
                        string        value         = codesVsValue[1];
                        List <string> codeHierarchy = code.Split('.').ToList();

                        ContextItem parent = null;
                        ContextItem item   = FindContextItem(outputItems, new List <string>()
                        {
                            codeHierarchy[0]
                        });
                        if (item == null)
                        {
                            item = new ContextItem();
                            outputItems.Add(item); //This is the root item that gets exported from the method
                        }

                        while (codeHierarchy.Any())
                        {
                            //Remove the first code
                            item.Code = codeHierarchy[0];
                            codeHierarchy.RemoveAt(0);

                            if (codeHierarchy.Any())
                            {
                                //There is another level after this.   Create a nesting and reset the item.
                                if (item.NestedItems == null)
                                {
                                    item.NestedItems = new List <ContextItem>();
                                }
                                parent = item;
                                item   = FindContextItem(parent.NestedItems, new List <string>()
                                {
                                    codeHierarchy[0]
                                });
                                if (item == null)
                                {
                                    item      = new ContextItem();
                                    item.Code = codeHierarchy[0];
                                    parent.NestedItems.Add(item);
                                }
                            }
                            else
                            {
                                //This is the final level of the code hierarchy.
                                //Add the actual value and to the output list
                                item.Value = value;
                                parent     = null;
                            }
                        }
                    }
                }
            }
            return(outputItems);
        }
예제 #37
0
        /// <summary>
        /// The view is asking for variable names for its intellisense.
        /// </summary>
        /// <param name="atype">Data type for which we want completion options.</param>
        /// <param name="properties">If true, property suggestions will be generated.</param>
        /// <param name="methods">If true, method suggestions will be generated.</param>
        /// <param name="publishedEvents">If true, published events will be returned.</param>
        /// <param name="subscribedEvents">If true, subscribed events will be returned.</param>
        /// <returns>List of completion options.</returns>
        public static List <ContextItem> ExamineTypeForContextItems(Type atype, bool properties, bool methods, bool publishedEvents, bool subscribedEvents)
        {
            List <ContextItem> allItems = new List <ContextItem>();

            // find the properties and methods
            if (atype != null)
            {
                if (properties)
                {
                    foreach (PropertyInfo property in atype.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        VariableProperty var  = new VariableProperty(atype, property);
                        ContextItem      item = new ContextItem
                        {
                            Name        = var.Name,
                            IsProperty  = true,
                            IsEvent     = false,
                            IsWriteable = !var.IsReadOnly,
                            TypeName    = GetTypeName(var.DataType),
                            Descr       = GetDescription(property),
                            Units       = var.Units
                        };
                        allItems.Add(item);
                    }
                }

                if (methods)
                {
                    foreach (MethodInfo method in atype.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy))
                    {
                        if (!method.Name.StartsWith("get_") && !method.Name.StartsWith("set_") &&
                            !method.Name.StartsWith("add_") && !method.Name.StartsWith("remove_"))
                        {
                            ContextItem item = new ContextItem
                            {
                                Name        = method.Name,
                                IsProperty  = false,
                                IsEvent     = false,
                                IsMethod    = true,
                                IsWriteable = false,
                                TypeName    = method.ReturnType.Name,
                                Descr       = GetDescription(method),
                                Units       = string.Empty
                            };

                            // build a parameter string representation
                            ParameterInfo[] allparams = method.GetParameters();
                            StringBuilder   paramText = new StringBuilder("( ");
                            if (allparams.Count() > 0)
                            {
                                for (int p = 0; p < allparams.Count(); p++)
                                {
                                    ParameterInfo parameter = allparams[p];
                                    paramText.Append(parameter.ParameterType.Name + " " + parameter.Name);
                                    if (parameter.DefaultValue != DBNull.Value)
                                    {
                                        paramText.Append(" = " + parameter.DefaultValue?.ToString() ?? "null");
                                    }
                                    if (p < allparams.Count() - 1)
                                    {
                                        paramText.Append(", ");
                                    }
                                }
                            }
                            paramText.Append(" )");
                            item.ParamString = paramText.ToString();

                            allItems.Add(item);
                        }
                    }
                }

                if (publishedEvents)
                {
                    foreach (EventInfo evnt in atype.GetEvents(BindingFlags.Instance | BindingFlags.Public))
                    {
                        NeedContextItemsArgs.ContextItem item = new NeedContextItemsArgs.ContextItem();
                        item.Name        = evnt.Name;
                        item.IsProperty  = true;
                        item.IsEvent     = true;
                        item.IsMethod    = false;
                        item.IsWriteable = false;
                        item.TypeName    = evnt.ReflectedType.Name;
                        item.Descr       = GetDescription(evnt);
                        item.Units       = "";
                        allItems.Add(item);
                    }
                }

                if (subscribedEvents)
                {
                    foreach (MethodInfo method in atype.GetMethods(/*BindingFlags.Instance |*/ BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
                    {
                        EventSubscribeAttribute subscriberAttribute = (EventSubscribeAttribute)ReflectionUtilities.GetAttribute(method, typeof(EventSubscribeAttribute), false);
                        if (subscriberAttribute != null)
                        {
                            NeedContextItemsArgs.ContextItem item = new NeedContextItemsArgs.ContextItem();
                            item.Name        = subscriberAttribute.ToString();
                            item.IsProperty  = false;
                            item.IsEvent     = false;
                            item.IsMethod    = true;
                            item.IsWriteable = false;
                            item.TypeName    = atype.Name;
                            item.Descr       = GetDescription(atype);
                            item.Units       = "";
                            allItems.Add(item);
                        }
                    }
                }
            }

            allItems.Sort(delegate(ContextItem c1, ContextItem c2) { return(c1.Name.CompareTo(c2.Name)); });
            return(allItems);
        }
예제 #38
0
 public void Add(ContextItem contextItem)
 {
     items.Add(contextItem);
 }
예제 #39
0
        /// <summary>
        /// Triggers all the workflows of the given triggerType for the given entity item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="triggerType">Type of the trigger.</param>
        /// <param name="personAlias">The person alias.</param>
        /// <returns></returns>
        private bool TriggerWorkflows(ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias)
        {
            IEntity entity = item.Entity;
            Dictionary <string, PropertyInfo> properties = null;

            // Look at each trigger for this entity and for the given trigger type
            // and see if it's a match.
            foreach (var trigger in WorkflowTriggersCache.Triggers(entity.TypeName, triggerType).Where(t => t.IsActive == true))
            {
                bool match = true;

                // If a qualifier column was given, then we need to check the previous or current qualifier value
                // otherwise it's just an automatic match.
                if (!string.IsNullOrWhiteSpace(trigger.EntityTypeQualifierColumn))
                {
                    // Get and cache the properties https://lotsacode.wordpress.com/2010/04/13/reflection-type-getproperties-and-performance/
                    // (Note: its possible that none of the triggers need them, so future TODO could be to
                    // bypass all this in that case.
                    if (properties == null)
                    {
                        properties = new Dictionary <string, PropertyInfo>();
                        foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties())
                        {
                            properties.Add(propertyInfo.Name.ToLower(), propertyInfo);
                        }
                    }

                    match = IsQualifierMatch(item, properties, trigger);
                }

                // If we found a matching trigger, then fire it; otherwise do nothing.
                if (match)
                {
                    // If it's one of the pre or immediate triggers, fire it immediately; otherwise queue it.
                    if (triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete || triggerType == WorkflowTriggerType.ImmediatePostSave)
                    {
                        var workflowType = WorkflowTypeCache.Get(trigger.WorkflowTypeId);
                        if (workflowType != null && (workflowType.IsActive ?? true))
                        {
                            var workflow = Rock.Model.Workflow.Activate(workflowType, trigger.WorkflowName);

                            List <string> workflowErrors;

                            using (var rockContext = new RockContext())
                            {
                                var workflowService = new WorkflowService(rockContext);
                                if (!workflowService.Process(workflow, entity, out workflowErrors))
                                {
                                    SaveErrorMessages.AddRange(workflowErrors);
                                    return(false);
                                }
                            }
                        }
                    }
                    else
                    {
                        var transaction = new Rock.Transactions.WorkflowTriggerTransaction();
                        transaction.Trigger     = trigger;
                        transaction.Entity      = entity.Clone();
                        transaction.PersonAlias = personAlias;
                        Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
                    }
                }
            }


            return(true);
        }
 public void LogMe(ContextRouter router, ContextItem item,
                   [Context(nameof(LogTextBox))]   object textBox,
                   LogInfo info)     // context here defaults to the type name of the parameter.
 {
 }
예제 #41
0
        private static void GetAuditDetails(DbContext dbContext, ContextItem item, int?personAliasId)
        {
            // Get the base class (not the proxy class)
            Type rockEntityType = item.Entity.GetType();

            if (rockEntityType.IsDynamicProxyType())
            {
                rockEntityType = rockEntityType.BaseType;
            }

            // Check to make sure class does not have [NotAudited] attribute
            if (AuditClass(rockEntityType))
            {
                var dbEntity = item.DbEntityEntry;
                var audit    = item.Audit;

                PropertyInfo[] properties = rockEntityType.GetProperties();

                foreach (PropertyInfo propInfo in properties)
                {
                    // Check to make sure property does not have the [NotAudited] attribute
                    if (AuditProperty(propInfo))
                    {
                        // If entire entity was added or deleted or this property was modified
                        var dbPropertyEntry = dbEntity.Property(propInfo.Name);
                        if (dbPropertyEntry != null && (
                                dbEntity.State == EntityState.Added ||
                                dbEntity.State == EntityState.Deleted ||
                                dbPropertyEntry.IsModified))
                        {
                            var currentValue  = dbEntity.State == EntityState.Deleted ? string.Empty : dbPropertyEntry.CurrentValue;
                            var originalValue = dbEntity.State == EntityState.Added ? string.Empty : dbPropertyEntry.OriginalValue;

                            var detail = new AuditDetail();
                            detail.Property     = propInfo.Name;
                            detail.CurrentValue = currentValue != null?currentValue.ToString() : string.Empty;

                            detail.OriginalValue = originalValue != null?originalValue.ToString() : string.Empty;

                            if (detail.CurrentValue != detail.OriginalValue)
                            {
                                audit.Details.Add(detail);
                            }
                        }
                    }
                }

                if (audit.Details.Any())
                {
                    var entityType = EntityTypeCache.Get(rockEntityType);
                    if (entityType != null)
                    {
                        string title;
                        try
                        {
                            title = item.Entity.ToString();
                        }
                        catch
                        {
                            // ignore exception (Entity often overrides ToString() and we don't want that prevent the audit if it fails)
                            title = null;
                        }

                        if (string.IsNullOrWhiteSpace(title))
                        {
                            title = entityType.FriendlyName ?? string.Empty;
                        }
                        audit.DateTime      = RockDateTime.Now;
                        audit.PersonAliasId = personAliasId;
                        audit.EntityTypeId  = entityType.Id;
                        audit.EntityId      = item.Entity.Id;
                        audit.Title         = title.Truncate(195);
                    }
                }
            }
        }
 /// <summary>
 /// Handles overflow processing for a container. This should be called once the layout
 /// has determined contentWidth/Height. In addition to the ownerContext passed to the
 /// calculate method, this method also needs the containerSize (the object
 /// returned by getContainerSize).
 /// </summary>
 /// <param name="ownerContext">
 /// </param>
 /// <param name="containerSize">
 /// </param>
 /// <param name="dimensions"><p>A bit mask for the overflow managed dimensions. The 0-bit
 /// is for <c>width</c> and the 1-bit is for <c>height</c>. In other words, a value of 1 would be
 /// only <c>width</c>, 2 would be only <c>height</c> and 3 would be both.</p>
 /// </param>
 public void calculateOverflow(ContextItem ownerContext, object containerSize, JsNumber dimensions){}
            //Helper method to call from GetExistingInstanceContext
            //returns true  : If InstanceContext is found in cache & guaranteed to stay in cache until ReleaseReference is called.
            //returns false : If InstanceContext is not found in cache;
            //               reference & slot is created for the ID;
            //               InitializeInstanceContext to call AddInstanceContext.
            public bool TryGetInstanceContext(Guid instanceId, out InstanceContext instanceContext)
            {
                ContextItem contextItem;
                instanceContext = null;
                int referenceCount = -1;

                try
                {
                    lock (lockObject)
                    {
                        if (!contextCache.TryGetValue(instanceId, out contextItem))
                        {
                            contextItem = new ContextItem(instanceId);
                            referenceCount = contextItem.AddReference();
                            contextCache.Add(instanceId, contextItem);
                            return false;
                        }
                        referenceCount = contextItem.AddReference();
                    }
                }
                finally
                {
                    if (DiagnosticUtility.ShouldTraceInformation)
                    {
                        string traceText = SR2.GetString(SR2.DurableInstanceRefCountToInstanceContext, instanceId, referenceCount);
                        TraceUtility.TraceEvent(TraceEventType.Information,
                            TraceCode.InstanceContextBoundToDurableInstance, SR.GetString(SR.TraceCodeInstanceContextBoundToDurableInstance),
                            new StringTraceRecord("InstanceDetail", traceText),
                            this, null);
                    }
                }
                instanceContext = contextItem.InstanceContext;
                return true;
            }
 /// <summary>
 /// Returns the container size (that of the target). Only the fixed-sized dimensions can
 /// be returned because the shrinkWrap dimensions are based on the contentWidth/Height
 /// as determined by the container layout.
 /// If the <see cref="Ext.layout.container.Container.calculateOverflow">calculateOverflow</see> method is used and if <see cref="Ext.layout.container.ContainerConfig.manageOverflow">manageOverflow</see> is
 /// true, this may adjust the width/height by the size of scrollbars.
 /// </summary>
 /// <param name="ownerContext"><p>The owner's context item.</p>
 /// </param>
 /// <param name="inDom"><p>True if the container size must be in the DOM.</p>
 /// <p>Defaults to: <c>false</c></p></param>
 /// <returns>
 /// <span><see cref="Object">Object</see></span><div><p>The size</p>
 /// <ul><li><span>width</span> : <see cref="Number">Number</see><div><p>The width</p>
 /// </div></li><li><span>height</span> : <see cref="Number">Number</see><div><p>The height</p>
 /// </div></li></ul></div>
 /// </returns>
 protected object getContainerSize(ContextItem ownerContext, object inDom=null){return null;}
예제 #45
0
 protected override void UpdateTokenContext(TokenContext context)
 {
     base.UpdateTokenContext(context);
     context[nameof(AttributeArgumentEndToken)] = new ContextItem(value: typeof(NextTaskWhitespaceToken), validUpTo: typeof(AttributeArgumentEndToken));
 }
예제 #46
0
        private List <ContextItem> CreatePackagedProductInstanceContextItems(Model.ShippedItemInstance shippedItemInstance)
        {
            List <ContextItem> items = new List <ContextItem>();

            // Lot
            if (shippedItemInstance.Lot?.Identifier?.Content != null)
            {
                items.Add(CreateContextItem("Lot", shippedItemInstance.Lot?.Identifier?.Content));
            }

            // Packaging
            ContextItem contextItem = CreateContextItem("Packaging", null);

            // Add Packaging nested items
            if (shippedItemInstance.Packaging?.TypeCode != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.Packaging.TypeCode));
            }
            if (shippedItemInstance.Packaging?.Identifier != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("identifier", shippedItemInstance.Packaging.Identifier));
            }
            if (contextItem.NestedItems.Count > 0)
            {
                items.Add(contextItem);
            }

            // DocumentReference
            contextItem = CreateContextItem("DocumentReference", null);

            // nested items
            ContextItem nestedContextItem = CreateContextItem("Identifier", null);

            // This one has it's own nested items
            if (shippedItemInstance.DocumentReference?.Identifier?.Content != null)
            {
                nestedContextItem.NestedItems.Add(CreateContextItem("content", shippedItemInstance.DocumentReference?.Identifier?.Content));
            }
            if (shippedItemInstance.DocumentReference?.Identifier?.TypeCode != null)
            {
                nestedContextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.DocumentReference.Identifier.TypeCode));
            }
            if (nestedContextItem.NestedItems.Count > 0)
            {
                contextItem.NestedItems.Add(nestedContextItem);
            }

            if (shippedItemInstance.DocumentReference?.TypeCode != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.DocumentReference.TypeCode));
            }

            if (shippedItemInstance.DocumentReference?.DocumentDateTime != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("documentDateTime", shippedItemInstance.DocumentReference.DocumentDateTime));
            }
            if (contextItem.NestedItems.Count > 0)
            {
                items.Add(contextItem);
            }

            // Identifier
            contextItem = CreateContextItem("Identifier", null);

            // nested items
            if (shippedItemInstance.Identifier?.TypeCode != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.Identifier.TypeCode));
            }
            if (shippedItemInstance.Identifier?.Content != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("content", shippedItemInstance.Identifier.Content));
            }
            if (contextItem.NestedItems.Count > 0)
            {
                items.Add(contextItem);
            }

            // ItemIdentifierSet
            if (shippedItemInstance.ItemIdentifierSets?.Count > 0)
            {
                contextItem = CreateItemIdentifierSetsContextItem(shippedItemInstance);
                if (contextItem.NestedItems.Count > 0)
                {
                    items.Add(contextItem);
                }
            }

            // Uid
            contextItem = CreateContextItem("uid", null);
            if (shippedItemInstance.Uid?.Content != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("content", shippedItemInstance.Uid.Content));
            }
            if (shippedItemInstance.Uid?.SchemeIdentifier != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("schemaIdentifier", shippedItemInstance.Uid.SchemeIdentifier));
            }
            if (shippedItemInstance.Uid?.SchemeAgencyIdentifier != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("schemaAgencyIdentifier", shippedItemInstance.Uid.SchemeAgencyIdentifier));
            }
            if (shippedItemInstance.Uid?.TypeCode != null)
            {
                contextItem.NestedItems.Add(CreateContextItem("typeCode", shippedItemInstance.Uid.TypeCode));
            }

            if (contextItem.NestedItems.Count > 0)
            {
                items.Add(contextItem);
            }

            // Quantitative Results
            if (shippedItemInstance.Results?.Quantitative.Count > 0)
            {
                contextItem = CreateQuantitativeResultsContextItem(shippedItemInstance);
                if (contextItem.NestedItems.Count > 0)
                {
                    items.Add(contextItem);
                }
            }

            return(items);
        }
예제 #47
0
        public bool AddSignature(Contract contract, ECPoint pubkey, byte[] signature)
        {
            if (contract.IsMultiSigContract())
            {
                ContextItem item = CreateItem(contract);
                if (item == null)
                {
                    return(false);
                }
                if (item.Parameters.All(p => p.Value != null))
                {
                    return(false);
                }
                if (item.Signatures == null)
                {
                    item.Signatures = new Dictionary <ECPoint, byte[]>();
                }
                else if (item.Signatures.ContainsKey(pubkey))
                {
                    return(false);
                }
                List <ECPoint> points = new List <ECPoint>();
                {
                    int i = 0;
                    switch (contract.Script[i++])
                    {
                    case 1:
                        ++i;
                        break;

                    case 2:
                        i += 2;
                        break;
                    }
                    while (contract.Script[i++] == 33)
                    {
                        points.Add(ECPoint.DecodePoint(contract.Script.Skip(i).Take(33).ToArray(), ECCurve.Secp256r1));
                        i += 33;
                    }
                }
                if (!points.Contains(pubkey))
                {
                    return(false);
                }
                item.Signatures.Add(pubkey, signature);
                if (item.Signatures.Count == contract.ParameterList.Length)
                {
                    Dictionary <ECPoint, int> dic = points.Select((p, i) => new
                    {
                        PublicKey = p,
                        Index     = i
                    }).ToDictionary(p => p.PublicKey, p => p.Index);
                    byte[][] sigs = item.Signatures.Select(p => new
                    {
                        Signature = p.Value,
                        Index     = dic[p.Key]
                    }).OrderByDescending(p => p.Index).Select(p => p.Signature).ToArray();
                    for (int i = 0; i < sigs.Length; i++)
                    {
                        if (!Add(contract, i, sigs[i]))
                        {
                            throw new InvalidOperationException();
                        }
                    }
                    item.Signatures = null;
                }
                return(true);
            }
            else
            {
                int index = -1;
                for (int i = 0; i < contract.ParameterList.Length; i++)
                {
                    if (contract.ParameterList[i] == ContractParameterType.Signature)
                    {
                        if (index >= 0)
                        {
                            throw new NotSupportedException();
                        }
                        else
                        {
                            index = i;
                        }
                    }
                }
                return(Add(contract, index, signature));
            }
        }
예제 #48
0
 private ContextItem BuildPollContextItem(PublicApi.Poll poll)
 {
     var item = new ContextItem()
     {
         TypeName = "Poll",
         ApplicationId = poll.Group.ApplicationId,
         ApplicationTypeId = Telligent.Evolution.Components.ContentTypes.Group,
         ContainerId = poll.Group.ContainerId,
         ContainerTypeId = Telligent.Evolution.Components.ContentTypes.Group,
         ContentId = poll.ContentId,
         ContentTypeId = PublicApi.Polls.ContentTypeId,
         Id = poll.ContentId.ToString()
     };
     return item;
 }