Пример #1
0
        public void Execute(IServiceProvider serviceProvider)
        {
            var context =
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = serviceFactory.CreateOrganizationService(context.UserId);
            var altKey  = new KeyAttributeCollection();

            altKey.Add("cr90f_name", context.InputParameters["name"]);

            var report = new Entity
            {
                KeyAttributes         = altKey,
                LogicalName           = "cr90f_report",
                ["cr90f_description"] = context.InputParameters["description"],
                ["cr90f_priority"]    = context.InputParameters["priority"],
                ["cr90f_name"]        = context.InputParameters["name"]
            };
            var request = new UpsertRequest
            {
                Target = report
            };
            var response = (UpsertResponse)service.Execute(request);
            var result   = response.RecordCreated ? "Record created" : "Record updated";

            context.OutputParameters["result"] = result;
        }
Пример #2
0
        public void KeyAttributeCollectionCanBeSerializedAndDeserialized()
        {
            KeyAttributeCollection keyAttributeCollection = new KeyAttributeCollection();

            keyAttributeCollection.Add("Test", "test");
            JsonSerializer serializer = new JsonSerializer();
            var            num        = serializer.Converters.Where(x => x.CanConvert(typeof(object)));

            serializer.TypeNameHandling = TypeNameHandling.All;
            serializer.Converters.Add(new KeyAttributeCollectionConverter());
            serializer.ContractResolver = new XrmContractResolver();


            MemoryStream memoryStream = new MemoryStream(new byte[9000], true);

            using (StreamWriter writer = new StreamWriter(memoryStream))
            {
                serializer.Serialize(new JsonTextWriter(writer), keyAttributeCollection);
            }
            KeyAttributeCollection deserializedKeyAttributeCollection;

            memoryStream = new MemoryStream(memoryStream.ToArray());
            using (StreamReader reader = new StreamReader(memoryStream))
            {
                deserializedKeyAttributeCollection = (KeyAttributeCollection)serializer.Deserialize(new JsonTextReader(reader));
            }

            Assert.Equal(keyAttributeCollection.Count, deserializedKeyAttributeCollection.Count);
            Assert.Equal(keyAttributeCollection.Keys.First(), deserializedKeyAttributeCollection.Keys.First());
            Assert.Equal(keyAttributeCollection.Values.First(), deserializedKeyAttributeCollection.Values.First());
        }
Пример #3
0
        /// <summary>
        /// Updates the set of records used in the sample
        /// </summary>
        /// <param name="service">Specifies the service to connect to.</param>
        private static void UpdateBookRecordsForSample(IOrganizationService service)
        {
            int recordsCreated = 0;

            Console.WriteLine("Adding 10 more records");
            // Create 10 book records for demo.
            for (int i = 10; i < 20; i++)
            {
                Entity book = new Entity("sample_book");
                book["sample_name"]     = "Demo Book " + i.ToString();
                book["sample_bookcode"] = "BookCode" + i.ToString();
                book["sample_author"]   = "Author" + i.ToString();

                try
                {
                    service.Create(book);
                    recordsCreated++;
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    //Record with sample_bookcode alternate key value already exists.
                    //So it is fine that we don't re-create it.
                    if (!(ex.Detail.ErrorCode == -2147088238))
                    {
                        throw;
                    }
                }
            }
            Console.WriteLine("{0} records created...", recordsCreated);

            // Update a record.
            Console.WriteLine("Updating one of the initial records.");
            //Use the alternate key to reference the entity;
            Entity demoBookZero = new Entity("sample_book", "sample_bookcode", "BookCode0");

            demoBookZero["sample_name"] = string.Format("Demo Book 0 updated {0}", DateTime.Now.ToShortTimeString());

            service.Update(demoBookZero);

            //Delete a record
            Console.WriteLine("Deleting one of the initial records.");

            //Use a KeyAttributeCollection to set the alternate key for the record.
            KeyAttributeCollection demoBookOneKeys = new KeyAttributeCollection();

            demoBookOneKeys.Add(new KeyValuePair <string, object>("sample_bookcode", "BookCode1"));

            EntityReference bookOne = new EntityReference()
            {
                LogicalName   = "sample_book",
                KeyAttributes = demoBookOneKeys
            };
            DeleteRequest deleteReq = new DeleteRequest()
            {
                Target = bookOne
            };

            service.Execute(deleteReq);
        }
        public void SetValue(object target, object value)
        {
            KeyAttributeCollection keyAttributeCollection       = (KeyAttributeCollection)target;
            IEnumerable <KeyValuePair <string, object> > values = (IEnumerable <KeyValuePair <string, object> >)value;

            foreach (var item in values)
            {
                keyAttributeCollection.Add(item);
            }
        }
        protected override Entity GetTargetEntity(DataRow row, CancellationToken cancel, IProgress <ExecutionProgress> progress)
        {
            KeyAttributeCollection keyAttributes = new KeyAttributeCollection();

            foreach (FieldValue fieldValue in keyValues)
            {
                keyAttributes.Add(((Dynamics365Field)fieldValue.DestinationField).LogicalName, fieldValue.GetValue(row, cancel, progress));
            }

            return(new Entity(Entity.LogicalName, keyAttributes));
        }
        /// <summary>
        /// Delete method override. Deletes by Alternative key
        /// </summary>
        /// <param name="reference">Entity to delete</param>
        public static void Delete(this IOrganizationService service, string logicalName, string keyName, object keyValue)
        {
            CheckParam.CheckForNull(keyName, nameof(keyName));
            CheckParam.CheckForNull(keyValue, nameof(keyValue));

            KeyAttributeCollection keys = new KeyAttributeCollection();

            keys.Add(keyName, keyValue);

            service.Delete(logicalName, keys);
        }
Пример #7
0
        public DataLine(Context context, int lineNumber, string lineText, int columnCount, KeyAttributeCollection keyCollection) : this(context, lineNumber, lineText, columnCount)
        {
            if (!IsOk)
            {
                return;
            }
            KeyAttributeCollection keyAttributeCollection = new KeyAttributeCollection( );

            foreach (var item in keyCollection)
            {
                keyAttributeCollection.Add(item.Key, LineData [( int )item.Value]);
            }

            Entity = new Entity(context.EntityItem.EntityMetadata.LogicalName, keyAttributeCollection);
        }
Пример #8
0
        public static Entity GetBookingEntityFromPayload(Booking booking, ITracingService trace)
        {
            if (trace == null)
            {
                throw new InvalidPluginExecutionException("Trace service is null;");
            }
            trace.Trace("Booking populate fields - start");
            if (booking == null)
            {
                throw new InvalidPluginExecutionException("Booking is null.");
            }
            if (booking.BookingIdentifier == null)
            {
                throw new InvalidPluginExecutionException("Booking identifier is null.");
            }
            if (booking.BookingIdentifier.BookingNumber == null || string.IsNullOrWhiteSpace(booking.BookingIdentifier.BookingNumber))
            {
                throw new InvalidPluginExecutionException("Booking Number should not be null.");
            }

            var indexCollection = new KeyAttributeCollection();

            indexCollection.Add(Attributes.Booking.Name, booking.BookingIdentifier.BookingNumber);
            indexCollection.Add(Attributes.Booking.SourceSystem, booking.BookingIdentifier.BookingSystem.ToString());
            Entity bookingEntity = new Entity(EntityName.Booking, indexCollection);

            PopulateIdentifier(bookingEntity, booking.BookingIdentifier, trace);
            PopulateIdentity(bookingEntity, booking.BookingIdentity, trace);
            PopulateGeneralFields(bookingEntity, booking.BookingGeneral, trace);
            PopulateDurationFrom(booking, bookingEntity, trace);

            bookingEntity[Attributes.Booking.Participants]       = PrepareTravelParticipantsInfo(booking.TravelParticipant, trace);
            bookingEntity[Attributes.Booking.ParticipantRemarks] = PrepareTravelParticipantsRemarks(booking.TravelParticipant, trace);
            if (!string.IsNullOrWhiteSpace(booking.DestinationId))
            {
                bookingEntity[Attributes.Booking.DestinationId] = new EntityReference(EntityName.Region, new Guid(booking.DestinationId));
            }
            else
            {
                bookingEntity[Attributes.Booking.DestinationId] = null;
            }

            if (booking.BookingIdentifier != null)
            {
                if (!string.IsNullOrWhiteSpace(booking.Owner))
                {
                    bookingEntity[Attributes.Booking.Owner] = new EntityReference(EntityName.Team, new Guid(booking.Owner));
                }
            }

            PopulateServices(bookingEntity, booking.Services, trace);

            bookingEntity[Attributes.Booking.SourceMarketId] = (booking.BookingIdentifier.SourceMarket != null) ? new EntityReference(EntityName.Country
                                                                                                                                      , new Guid(booking.BookingIdentifier.SourceMarket))
                                                                                    : null;

            bookingEntity[Attributes.Booking.StateCode]  = new OptionSetValue((int)Statecode.Active);
            bookingEntity[Attributes.Booking.StatusCode] = CommonXrm.GetBookingStatus(booking.BookingGeneral.BookingStatus);
            bookingEntity[Attributes.Booking.Remarks]    = RemarksHelper.GetRemarksTextFromPayload(booking.Remark);
            trace.Trace("Booking populate fields - end");

            return(bookingEntity);
        }
Пример #9
0
        /// <summary>
        /// Read the CSV file and store lines into dataLine objects.
        /// if there is a primary key or keys in the columns list, then the Entity object will be created
        /// </summary>
        /// <param name="context"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        internal static List <DataLine> GetData(Context context, out string errorMessage)
        {
            errorMessage = string.Empty;
            List <DataLine> data        = new List <DataLine> ( );
            int             index       = 1;
            int             columnCount = context.ColumnItems.Count;

            using (StreamReader streamReader = new StreamReader(context.FilePath, true))
            {
                if (streamReader.ReadLine( ).Split(';').Count( ) != columnCount)
                {
                    errorMessage = "File must contain " + columnCount + " lines.";
                }
                else
                {
                    switch (context.QueryType)
                    {
                    case ColumnTypeCode.DynamicConditionExpression:
                        while (!streamReader.EndOfStream)
                        {
                            index++;
                            data.Add(new DataLine(context, index, streamReader.ReadLine( ), columnCount));
                        }
                        break;

                    case ColumnTypeCode.StaticConditionExpression:
                        while (!streamReader.EndOfStream)
                        {
                            index++;
                            data.Add(new DataLine(context, index, streamReader.ReadLine( ), columnCount));
                        }
                        break;

                    case ColumnTypeCode.PrimaryKey:
                        int primaryKeyItemIndex = context.ColumnItems.Where(a => a.ColumnType == ColumnTypeCode.PrimaryKey).Select(a => context.ColumnItems.IndexOf(a)).FirstOrDefault();
                        while (!streamReader.EndOfStream)
                        {
                            index++;
                            // + the index of the guid
                            data.Add(new DataLine(context, index, streamReader.ReadLine( ), columnCount, primaryKeyItemIndex));
                        }
                        break;

                    case ColumnTypeCode.Key:
                        int keyItemIndex = context.ColumnItems.Where(a => a.ColumnType == ColumnTypeCode.Key).Select(a => context.ColumnItems.IndexOf(a)).FirstOrDefault( );
                        while (!streamReader.EndOfStream)
                        {
                            index++;
                            //+ key name and index
                            data.Add(new DataLine(context, index, streamReader.ReadLine( ), columnCount, context.ColumnItems[keyItemIndex].LogicalName, keyItemIndex));
                        }
                        break;

                    case ColumnTypeCode.PartialKey:
                        List <int>             PartialKeyItems = context.ColumnItems.Where(a => a.ColumnType == ColumnTypeCode.PartialKey).Select(a => context.ColumnItems.IndexOf(a)).ToList( );
                        KeyAttributeCollection keyCollection   = new KeyAttributeCollection( );
                        foreach (var item in PartialKeyItems)
                        {
                            keyCollection.Add(context.ColumnItems[item].LogicalName, item);
                        }
                        while (!streamReader.EndOfStream)
                        {
                            index++;
                            data.Add(new DataLine(context, index, streamReader.ReadLine( ), columnCount, keyCollection));
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            return(data);
        }