Exemplo n.º 1
0
        public static async Task GetAccountCounts(CRMWebAPI api, ITurnContext <IMessageActivity> context)
        {
            await Task.Run(async() =>
            {
                dynamic whoamiResults = await api.ExecuteFunction("WhoAmI");
                var opt = new CRMGetListOptions
                {
                    Top    = 5000,
                    Filter = "_createdby_value eq " + whoamiResults.UserId + " or _modifiedby_value eq " + whoamiResults.UserId
                };
                var count = await api.GetList("accounts", QueryOptions: opt);
                if (count == null)
                {
                    count      = new Xrm.Tools.WebAPI.Results.CRMGetListResult <ExpandoObject>();
                    count.List = new List <ExpandoObject>();
                }
                else if (count.List == null)
                {
                    count.List = new List <ExpandoObject>();
                }

                var card = new HeroCard();

                var action = new CardAction()
                {
                    Type  = ActionTypes.MessageBack,
                    Title = $"Accounts owned by me: {count.List.Count}",
                    Value = count.ToString()
                };
                card.Buttons = new List <CardAction>();
                card.Buttons.Add(action);
                await DisplayMessage(card, context);
            });
        }
Exemplo n.º 2
0
        public static bool IsTokenValid(ITurnContext <IMessageActivity> context, string accessToken, IConfiguration ConfigurationManager)
        {
            var result = false;

            Task.Run(async() =>
            {
                string crmBaseUrl = ConfigurationManager["CrmServerUrlProd"];
                var api           = new CRMWebAPI(crmBaseUrl + "/api/data/v8.1/", accessToken);
                try
                {
                    var results = await api.GetList("accounts", new CRMGetListOptions()
                    {
                        Top = 1
                    });
                    if (results != null && results.Count >= 0)
                    {
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                }
            }).Wait();

            return(result);
        }
Exemplo n.º 3
0
        public async Task <IEnumerable <Product> > GetProductsAsync()
        {
            try
            {
                var result = await _api.GetList("stq_products", new CRMGetListOptions()
                {
                    Select = new List <string>()
                    {
                        "stq_name", "stq_price", "stq_text", "stq_imgurl", "stq_productid", "stq_supplier", "stq_otherimagescsv", "stq_attributescsv", "stq_subtitle"
                    }.ToArray()
                });


                return(result.List.Select <dynamic, Product>((e) => {
                    return new Product()
                    {
                        Name = e.stq_name,
                        Price = e.stq_price ?? 0,
                        ImgUrl = e.stq_imgurl,
                        Text = e.stq_text,
                        Id = new Guid(e.stq_productid),
                        Supplier = e.stq_supplier,
                        AttributesCSV = e.stq_attributescsv,
                        OtherImagesCSV = e.stq_otherimagescsv,
                        Subtitle = e.stq_subtitle,
                        ProductId = e.stq_productid
                    };
                }));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
Exemplo n.º 4
0
        public static async Task GetTopAccounts(CRMWebAPI api, ITurnContext <IMessageActivity> context, int count)
        {
            await Task.Run(async() =>
            {
                var card  = new HeroCard();
                var names = new List <string>();
                //var results = await api.GetList("accounts", new CRMGetListOptions() { Top = 5, FormattedValues = true });
                string fetchXml  = "<fetch mapping='logical' count='{0}'><entity name='account'><attribute name='accountid'/><attribute name='name'/></entity></fetch>";
                fetchXml         = string.Format(fetchXml, count);
                var fetchResults = await api.GetList("accounts", QueryOptions: new CRMGetListOptions()
                {
                    FetchXml = fetchXml
                });

                foreach (var item in fetchResults.List)
                {
                    IDictionary <string, object> propertyValues = item;

                    foreach (var property in propertyValues.Keys)
                    {
                        if (property.ToLowerInvariant() == "name")
                        {
                            names.Add(propertyValues[property].ToString());
                        }
                        //await context.PostAsync(String.Format("{0} : {1}", property, propertyValues[property]));
                    }
                }
                card.Buttons = CreateButtons(names);
                await DisplayMessage(card, context);
            });
        }
Exemplo n.º 5
0
        public async Task <IEnumerable <SupportEntity> > GetSupportsAsync()
        {
            var list = await api.GetList <SupportEntity>("era_supports", new CRMGetListOptions
            {
                Select = new[] { "era_name", "era_supportid" }
            });

            return(list.List);
        }
Exemplo n.º 6
0
        public static async Task <List <CRMAttributeDisplayName> > GetAttributeDisplayNameList(this CRMWebAPI api, Guid entityID, int LCID = 0)
        {
            var result = new List <CRMAttributeDisplayName>();

            CRMGetListOptions options = new CRMGetListOptions()
            {
                Filter = "((IsValidForRead eq true) and (AttributeOf eq null))",

                Select = new[] { "MetadataId", "DisplayName", "LogicalName", "SchemaName", "AttributeType", "IsPrimaryId" }
            };

            var queryResults = await api.GetList("EntityDefinitions(" + entityID.ToString() + ")/Attributes", options);

            foreach (dynamic attrib in queryResults.List)
            {
                CRMAttributeDisplayName edm = new CRMAttributeDisplayName();
                edm.MetadataId    = Guid.Parse(attrib.MetadataId);
                edm.LogicalName   = attrib.LogicalName;
                edm.SchemaName    = attrib.SchemaName;
                edm.IsPrimaryId   = attrib.IsPrimaryId;
                edm.AttributeType = attrib.AttributeType;
                if (attrib.AttributeType == "Lookup" || attrib.AttributeType == "Customer" || attrib.AttributeType == "Owner")
                {
                    edm.ODataLogicalName = "_" + attrib.LogicalName + "_value";
                }
                else
                {
                    edm.ODataLogicalName = attrib.LogicalName;
                }

                if ((attrib.DisplayName.LocalizedLabels != null) && (attrib.DisplayName.LocalizedLabels.Count > 0))
                {
                    edm.DisplayName = attrib.DisplayName.LocalizedLabels[0].Label;
                    if (LCID != 0)
                    {
                        foreach (dynamic label in attrib.DisplayName.LocalizedLabels)
                        {
                            if (label.LanguageCode == LCID)
                            {
                                edm.DisplayName = label.Label;
                            }
                        }
                    }
                }
                else
                {
                    edm.DisplayName = edm.LogicalName;
                }
                edm.LogicalDisplayName = edm.DisplayName + "(" + edm.LogicalName + ")";
                result.Add(edm);
            }



            return(result);
        }
        // Retrieve all accounts
        public static async Task <Xrm.Tools.WebAPI.Results.CRMGetListResult <System.Dynamic.ExpandoObject> > GetAccounts(CRMWebAPI api)
        {
            var results = await api.GetList("accounts",
                                            new Xrm.Tools.WebAPI.Requests.CRMGetListOptions()
            {
                TrackChanges = true, FormattedValues = true
            });

            return(results);
        }
Exemplo n.º 8
0
        public ErasePiiBuilderWebApi GetEntityRecords(string entityName)
        {
            var fetchXml     = "<fetch mapping='logical'><entity name='" + entityName + "'> <all-attributes/></entity></fetch>";
            var fetchResults = _api.GetList(entityName, new CRMGetListOptions
            {
                FetchXml = fetchXml
            });

            _entityRecords = fetchResults.Result.List;
            return(this);
        }
Exemplo n.º 9
0
        private void EraseTextFieldData(string fieldName)
        {
            ///Get all entities and entityId...
            ///add them to an expando object....
            ///Loop the entities to update the records...
            Task.Run(async() =>
            {
                const string fetchXml
                    = "<fetch><entity name='contact'><all-attributes/></entity></fetch>";
                var fetchResults = await _api.GetList("contacts",
                                                      new CRMGetListOptions
                {
                    FetchXml = fetchXml
                });

                var myListTrackChanged = fetchResults.TrackChangesLink;
                Console.WriteLine("the tracked changes are: " + myListTrackChanged);
                myFetchResults = fetchResults.List.Count;

                myApiCount = await _api.GetCount("contacts");


                //var getEntityFetchRecords = await _api.GetList(_entityName + "s", new CRMGetListOptions
                //{

                //    FormattedValues = true
                //});

                //if (getEntityFetchRecords.List.Count > 0)
                //{
                //    foreach (var entities in getEntityFetchRecords.List)
                //    {
                //        Console.WriteLine("The number of entities is: " + entities.ToList().Count);
                //        foreach (var entity in entities)
                //        {
                //            if (entity.Key == "value") continue;
                //            if (entity.Key == fieldName)
                //            {
                //                var updateObj = new ExpandoObject() as IDictionary<string, object>;
                //                updateObj.Add(fieldName, string.Empty);
                //                await _api.Update(_entityName, _entityId, updateObj);
                //            }
                //        }
                //    }
                //}
            }).Wait();
            Console.WriteLine("The fetch results is: " + myFetchResults);
        }
Exemplo n.º 10
0
        public async Task <Guid> GetAccountIdByExternalIdAsync(string id)
        {
            var result = await _api.GetList("accounts", new CRMGetListOptions()
            {
                Select = new List <string>()
                {
                    "accountid"
                }.ToArray(),
                Filter = $@"stq_externalid eq '{id}'",
            });

            if ((result?.List?.Count ?? 0) < 1)
            {
                return(Guid.Empty);
            }

            return(new Guid((result.List.FirstOrDefault() as dynamic).accountid));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Checks if CRM can be accessed
        /// </summary>
        /// <returns>True/False, based on CRM connectivity</returns>
        public async Task <bool> CRMHealthcheck()
        {
            try
            {
                // Simple query to CRM to make sure connection can get response
                CRMGetListResult <SupportEntity> list = await api.GetList <SupportEntity>("era_supports", new CRMGetListOptions
                {
                    Select = new[] { "era_name", "era_supportid" }
                });

                return(list.List.Count > 0);
            }
            catch (Exception e)
            {
                logger.LogError(e, "Failed to connect to CRM during health check.");
                return(false);
            }
        }
Exemplo n.º 12
0
        public static async Task <ExpandoObject> GetOptionSetByName(this CRMWebAPI api, string optionSetName)
        {
            CRMGetListOptions options = new CRMGetListOptions()
            {
                Select = new[] { "Name" }
            };

            var queryResult = await api.GetList("GlobalOptionSetDefinitions", options);

            foreach (dynamic optionSet in queryResult.List)
            {
                if ((optionSet != null) && (optionSet.Name == optionSetName))
                {
                    var matchingOptionSet = await api.Get("GlobalOptionSetDefinitions", Guid.Parse(optionSet.MetadataId));

                    return(matchingOptionSet);
                }
            }

            return(null);
        }
Exemplo n.º 13
0
        public static async Task GetProductInfo(CRMWebAPI api, ITurnContext <IMessageActivity> context, string product)
        {
            var isTeams = context.Activity.ChannelId.ToLowerInvariant() == "msteams";
            var isSkype = context.Activity.ChannelId.ToLowerInvariant() == "skypeforbusiness";
            await Task.Run(async() =>
            {
                var card      = new HeroCard();
                var adaptCard = new AdaptiveCard(new AdaptiveSchemaVersion());
                var factSet   = new AdaptiveChoiceSetInput()
                {
                    Choices = new List <AdaptiveChoice>(), Spacing = AdaptiveSpacing.Medium
                };
                //card.Body.Add(factSet);

                var names        = new List <string>();
                string fetchXml  = @"<fetch mapping='logical'>
                                        <entity name='product'> 
                                          <attribute name='productid'/> 
                                          <attribute name='name'/> 
                                        <filter type='and'> 
                                            <condition attribute='name' operator='eq' value='{0}' /> 
                                        </filter> 
                                       </entity> 
                                </fetch>";
                fetchXml         = string.Format(fetchXml, product);
                var fetchResults = await api.GetList("products", QueryOptions: new CRMGetListOptions()
                {
                    FetchXml = fetchXml
                });

                foreach (var item in fetchResults.List)
                {
                    IDictionary <string, object> propertyValues = item;

                    foreach (var property in propertyValues.Keys)
                    {
                        string text = $"*{property}* : {propertyValues[property].ToString()}";
                        if (isTeams || isSkype)
                        {
                            card.Buttons.Add(new CardAction()
                            {
                                Text = text, Value = text, Type = ActionTypes.MessageBack
                            });
                        }
                        else
                        {
                            adaptCard.Body.Add(new AdaptiveTextBlock()
                            {
                                Text = text
                            });
                        }
                    }
                }
                if (isTeams || isSkype)
                {
                    await DisplayMessage(card, context);
                }
                else
                {
                    await DisplayMessage(adaptCard, context);
                }
            });
        }
Exemplo n.º 14
0
        public static async Task <List <CRMEntityDisplayName> > GetEntityDisplayNameList(this CRMWebAPI api, int LCID = 0)
        {
            var result = new List <CRMEntityDisplayName>();

            CRMGetListOptions options = new CRMGetListOptions()
            {
                Filter = "IsPrivate eq false",

                Select = new[] { "MetadataId", "EntitySetName", "DisplayName",
                                 "DisplayCollectionName", "LogicalName", "LogicalCollectionName", "PrimaryIdAttribute" }
            };

            var queryResults = await api.GetList("EntityDefinitions", options);

            foreach (dynamic entity in queryResults.List)
            {
                CRMEntityDisplayName edm = new CRMEntityDisplayName();
                edm.MetadataId            = Guid.Parse(entity.MetadataId);
                edm.EntitySetName         = entity.EntitySetName;
                edm.LogicalName           = entity.LogicalName;
                edm.LogicalCollectionName = entity.LogicalCollectionName;
                edm.PrimaryIdAttribute    = entity.PrimaryIdAttribute;
                if ((entity.DisplayName.LocalizedLabels != null) && (entity.DisplayName.LocalizedLabels.Count > 0))
                {
                    edm.DisplayName = entity.DisplayName.LocalizedLabels[0].Label;
                    if (LCID != 0)
                    {
                        foreach (dynamic label in entity.DisplayName.LocalizedLabels)
                        {
                            if (label.LanguageCode == LCID)
                            {
                                edm.DisplayName = label.Label;
                            }
                        }
                    }
                }
                else
                {
                    edm.DisplayName = edm.LogicalName;
                }
                if ((entity.DisplayCollectionName.LocalizedLabels != null) && (entity.DisplayCollectionName.LocalizedLabels.Count > 0))
                {
                    edm.DisplayCollectionName = entity.DisplayCollectionName.LocalizedLabels[0].Label;
                    if (LCID != 0)
                    {
                        foreach (dynamic label in entity.DisplayCollectionName.LocalizedLabels)
                        {
                            if (label.LanguageCode == LCID)
                            {
                                edm.DisplayCollectionName = label.Label;
                            }
                        }
                    }
                }
                else
                {
                    edm.DisplayCollectionName = entity.LogicalCollectionName;
                }
                edm.LogicalDisplayName           = edm.DisplayName + "(" + edm.LogicalName + ")";
                edm.LogicalDisplayCollectionName = edm.DisplayCollectionName + "(" + edm.LogicalCollectionName + ")";

                result.Add(edm);
            }

            return(result);
        }