public static Profile GetProfile(string ProfileName) { FilterExpression filter = new FilterExpression(LogicalOperator.And); filter.AddCondition(new ConditionExpression("appl_name", ConditionOperator.Equal, ProfileName)); EntityCollection col = XrmCore.RetrieveByFilter("appl_profiledefinition", filter); if (col.Entities.Count != 1) { throw new Exception(string.Format("There are {0} profiles with the name {1}. 1 was expected", col.Entities.Count, ProfileName)); } Guid ProfileDefinitionId = col.Entities.First().GetAttributeValue <Guid>("appl_profiledefinitionid"); using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(XrmConnection.Connection)) { IQueryable <Entity> query = from field in service.CreateQuery("appl_profilefield") join related in service.CreateQuery("appl_profilefield_appl_profiledefinitio") on field["appl_profilefieldid"] equals related["appl_profilefieldid"] join profiledef in service.CreateQuery("appl_profiledefinition") on related["appl_profiledefinitionid"] equals profiledef["appl_profiledefinitionid"] where (string)profiledef["appl_name"] == ProfileName select field; return(Profile.Factory(new EntityCollection(query.ToList()), ProfileDefinitionId)); } }
public static EntityCollection GetRelated(Entity PrimaryEntity, string RelatedEntityName, string ForeignKeyField, CrmConnection connection = null, bool CacheResults = true) { if (CacheResults) { using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection)) { IQueryable <Entity> query = from entity in service.CreateQuery(RelatedEntityName) where (Guid)entity[ForeignKeyField] == PrimaryEntity.Id select entity; EntityCollection col = new EntityCollection(query.ToList()); col.EntityName = RelatedEntityName; return(col); } } else { OrganizationService srv = new OrganizationService(connection ?? XrmConnection.Connection); using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv)) { IQueryable <Entity> query = from entity in service.CreateQuery(RelatedEntityName) where (Guid)entity[ForeignKeyField] == PrimaryEntity.Id select entity; EntityCollection col = new EntityCollection(query.ToList()); col.EntityName = RelatedEntityName; return(col); } } }
public List <Account> GetAllByName(string name) { using (var context = new CrmOrganizationServiceContext(_service)) { var accs = context.CreateQuery <Account>().Where(x => x.Name.Contains(name)).ToList(); return(accs); } }
public static Entity GetWebUserFromLogin(string LoginProvider, string ProviderKey, CrmConnection connection = null) { using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection)) { IQueryable <Entity> query = from entity in service.CreateQuery("appl_webuser") join login in service.CreateQuery("appl_webuserlogin") on entity["appl_webuserid"] equals login["appl_webuserid"] where login.GetAttributeValue <string>("appl_loginprovider") == LoginProvider && login.GetAttributeValue <string>("appl_providerkey") == ProviderKey select entity; List <Entity> result = query.ToList(); if (result.Count > 0) { return(result.First()); } } return(null); }
public Account GetByName(string name) { if (name != null && name.Length > 0) { using (var context = new CrmOrganizationServiceContext(_service)) { var acc = context.CreateQuery <Account>().Where(x => x.Name == name).FirstOrDefault(); return(acc); } } return(null); }
private static Guid DeleteDataMap(CrmOrganizationServiceContext serviceContext, string dataMapName) { Entity entity = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue <string>("name") == dataMapName); if (entity == null) { return(Guid.Empty); } Guid dataMapId = entity.Id; serviceContext.Delete("importmap", dataMapId); return(dataMapId); }
private static EntityReference FindGos(string p) { //new_gosorgan var context = new CrmOrganizationServiceContext(connection); var gos = (from i in context.CreateQuery <new_gosorgan>() where i.new_name == p select i).FirstOrDefault(); if (gos == null) { return(null); } else { return(gos.ToEntityReference()); } }
private static EntityReference ToSpravaEntity(string p) { var context = new CrmOrganizationServiceContext(connection); var sprava = (from m in context.CreateQuery <new_spravastr>() where m.new_businessnumber == p select m).FirstOrDefault(); if (sprava == null) { Console.WriteLine("{0} Ненайден дело", p); return(null); } else { return(sprava.ToEntityReference()); } }
private static EntityReference FindAccount(string p) { var context = new CrmOrganizationServiceContext(connection); var account = (from i in context.CreateQuery <Account>() where i.Name == p select i).FirstOrDefault(); if (account == null) { return(null); } else { return(account.ToEntityReference()); } }
private static IEnumerable <XObject> ToSolutions(IOrganizationService service) { using (var context = new CrmOrganizationServiceContext(service)) { var solutions = context.CreateQuery("solution") .Where(s => s.GetAttributeValue <bool>("isvisible")) .Select(s => new { UniqueName = s.GetAttributeValue <string>("uniquename"), Name = s.GetAttributeValue <string>("friendlyname"), Version = s.GetAttributeValue <string>("version"), Publisher = s.GetAttributeValue <EntityReference>("publisherid"), }) .ToList(); return(solutions.Select(s => ToRow(s.UniqueName, s.Name, s.Version, s.Publisher.Name))); } }
private static EntityCollection GetUserProfiles(Guid ContactId, Guid?ProfileId) { if (ProfileId.HasValue) { OrganizationService srv = new OrganizationService(XrmConnection.Connection); using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv)) { IQueryable <Entity> query = from entity in service.CreateQuery("appl_membershipprofile") where (Guid)entity["appl_contactid"] == ContactId && (Guid)entity["appl_profiledefinitionid"] == ProfileId.Value select entity; EntityCollection col = new EntityCollection(query.ToList()); col.EntityName = "appl_membershipprofile"; return(col); } } else { return(XrmCore.GetRelated(new Entity("contact", ContactId), "appl_membershipprofile", "appl_contactid", CacheResults: false)); } }
public static void HashAllPasswords(Func <string, string> PasswordHasher) { OrganizationService srv = new OrganizationService(XrmConnection.Connection); using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(srv)) { IQueryable <Entity> query = from member in service.CreateQuery("appl_webuser") select member; foreach (Entity e in query.ToList()) { string password = e.GetAttributeValue <string>("appl_passwordhash"); if (!string.IsNullOrEmpty(password) && password.Length < 15) { string hash = PasswordHasher(password); e["appl_passwordhash"] = hash; // e.EntityState = EntityState.Changed; service.UpdateObject(e); } } service.SaveChanges(); } }
private void ImportData() { if (!File.Exists(this.FilePath)) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find import data file {0}", this.FilePath)); return; } Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to Organization {0}.", this.OrganizationUrl)); string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout); var connection = CrmConnection.Parse(connectionString); string content = File.ReadAllText(this.FilePath); using (var serviceContext = new CrmOrganizationServiceContext(connection)) { try { var dataMap = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue<string>("name") == this.DataMapName); if (dataMap == null) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find data map {0} in the organization with Url {1}", this.DataMapName, this.OrganizationUrl)); return; } var importId = CreateImportEntity(serviceContext, this.SourceEntityName); this.CreateImportFileEntity(serviceContext, content, importId, dataMap.Id); Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing data from File {0} to entity {1}", this.FilePath, this.TargetEntityName)); serviceContext.Execute(new ParseImportRequest { ImportId = importId }); serviceContext.Execute(new TransformImportRequest { ImportId = importId }); serviceContext.Execute(new ImportRecordsImportRequest { ImportId = importId }); serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache) { cache.Mode = OrganizationServiceCacheMode.Disabled; }); int waitCount = 0; bool importCompleted = false; do { int statusCode = GetImportStatus(serviceContext, importId); switch (statusCode) { case DataImportStatusSuccess: Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported data file {0} to entity {1}.", this.FilePath, this.TargetEntityName)); importCompleted = true; break; case DataImportStatusFailed: Log.LogError(string.Format(CultureInfo.CurrentCulture, "Import of data file {0} to entity {1} failed.", this.FilePath, this.TargetEntityName)); importCompleted = true; break; } if (!importCompleted) { Log.LogMessage("Importing..."); Thread.Sleep(WaitIntervalInMilliseconds); if (++waitCount > this.timeoutInMinutes) { Log.LogError("Import failed to complete during the maximum allocated time"); break; } } } while (!importCompleted); } catch (Exception exception) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "An error occurred while importing Data file {0} to Entity {1} for Organization with Url {2}. [{3}]", this.FilePath, this.TargetEntityName, this.OrganizationUrl, exception.Message)); } } }
/// <summary> /// Parameterless initialization for calling the Bing Maps REST API that uses Settings records from within CRM when building the request URL. /// </summary> /// <remarks>Requires the following Settings from within CRM. /// BingMap/Key - (Required) Bing Maps Key used to authenticate with the Bing Maps REST API. /// BingMap/RestUrl - (Required) URL to the Bing Maps REST API. /// BingMap/UserLocation/Latitude - (Recommended) Latitude coordinate /// BingMap/UserLocation/Longitude - (Recommended) Longitude coordinate /// BingMap/IncludeNeighborhood - (Optional) (default = 0) | 0 - do not include the neighborhood with the address information in the response when it is available; 1 - include the neighborhood with the address information in the response when it is available. /// </remarks> public BingMapLookup() { const string bingMapKeySettingName = "BingMap/Key"; const string bingMapUrlSettingName = "BingMap/RestUrl"; const string bingMapUserLocationLatitudeSettingName = "BingMap/UserLocation/Latitude"; const string bingMapUserLocationLongitudeSettingName = "BingMap/UserLocation/Longitude"; const string bingMapIncludeNeighborhoodSettingName = "BingMap/IncludeNeighborhood"; var context = new CrmOrganizationServiceContext(); var setting = context.CreateQuery("adx_setting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name").EndsWith(bingMapKeySettingName)); var key = string.Empty; if (setting != null) { key = setting.GetAttributeValue <string>("adx_value"); } if (string.IsNullOrWhiteSpace(key)) { throw new ApplicationException(string.Format("No Bing Maps Key was specified in the setting {0}.", bingMapKeySettingName)); } setting = context.CreateQuery("adx_setting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name").EndsWith(bingMapUrlSettingName)); var restUrl = string.Empty; if (setting != null) { restUrl = setting.GetAttributeValue <string>("adx_value"); } if (string.IsNullOrWhiteSpace(restUrl)) { throw new ApplicationException(string.Format("No Bing Maps URL was specified in the setting {0}.", bingMapUrlSettingName)); } var userLocation = string.Empty; var latitude = string.Empty; var longitude = string.Empty; setting = context.CreateQuery("adx_setting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name").EndsWith(bingMapUserLocationLatitudeSettingName)); if (setting != null) { latitude = setting.GetAttributeValue <string>("adx_value"); } setting = context.CreateQuery("adx_setting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name").EndsWith(bingMapUserLocationLongitudeSettingName)); if (setting != null) { longitude = setting.GetAttributeValue <string>("adx_value"); } if (!string.IsNullOrWhiteSpace(latitude) && !string.IsNullOrWhiteSpace(longitude)) { userLocation = string.Format("{0},{1}", latitude, longitude); } setting = context.CreateQuery("adx_setting").FirstOrDefault(s => s.GetAttributeValue <string>("adx_name").EndsWith(bingMapIncludeNeighborhoodSettingName)); var includeNeighborhood = 0; if (setting != null) { var value = setting.GetAttributeValue <string>("adx_value"); int.TryParse(value, out includeNeighborhood); } BingMapRestUrl = restUrl; BingMapKey = key; UserLocation = userLocation; IncludeNeighborhood = includeNeighborhood; }
private static EntityReference ToSpravaEntity(string p) { var context = new CrmOrganizationServiceContext(connection); var sprava = (from m in context.CreateQuery<new_spravastr>() where m.new_businessnumber == p select m).FirstOrDefault(); if (sprava == null) { Console.WriteLine("{0} Ненайден дело", p); return null; } else { return sprava.ToEntityReference(); } }
private static EntityReference FindAccount(string p) { var context = new CrmOrganizationServiceContext(connection); var account = (from i in context.CreateQuery<Account>() where i.Name == p select i).FirstOrDefault(); if (account == null) { return null; } else { return account.ToEntityReference(); } }
private static EntityReference FindGos(string p) { //new_gosorgan var context = new CrmOrganizationServiceContext(connection); var gos = (from i in context.CreateQuery<new_gosorgan>() where i.new_name == p select i).FirstOrDefault(); if (gos == null) { return null; } else { return gos.ToEntityReference(); } }
private static Guid DeleteDataMap(CrmOrganizationServiceContext serviceContext, string dataMapName) { Entity entity = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue<string>("name") == dataMapName); if (entity == null) { return Guid.Empty; } Guid dataMapId = entity.Id; serviceContext.Delete("importmap", dataMapId); return dataMapId; }
private static EntityReference FindClient(string p) { if (p == string.Empty) { return(null); } var context = new CrmOrganizationServiceContext(connection); Contact client = null;; var splitP = p.Split(); switch (splitP.Length) { case 4: client = (from c in context.CreateQuery <Contact>() where c.FullName == splitP[0] + " " + splitP[3] select c).FirstOrDefault(); break; case 3: client = (from c in context.CreateQuery <Contact>() where c.FullName == splitP[0] + " " + splitP[2] select c).FirstOrDefault(); break; case 2: client = (from c in context.CreateQuery <Contact>() where c.FullName == p select c).FirstOrDefault(); break; case 1: client = (from c in context.CreateQuery <Contact>() where c.LastName == p select c).FirstOrDefault(); break; default: client = null; break; } if (client == null) { if (splitP.Length == 4) { client = (from c in context.CreateQuery <Contact>() where c.FullName == splitP[0] + " " + splitP[1] + " " + splitP[3] select c).FirstOrDefault(); } else { client = (from c in context.CreateQuery <Contact>() where c.FullName == p select c).FirstOrDefault(); } if (client == null) { Console.WriteLine("{0} Ненайден контакт", p); return(null); } return(client.ToEntityReference()); } else { return(client.ToEntityReference()); } }
private void ImportData() { if (!File.Exists(this.FilePath)) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find import data file {0}", this.FilePath)); return; } Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Connecting to Organization {0}.", this.OrganizationUrl)); string connectionString = string.Format(CultureInfo.CurrentCulture, "Server={0};Timeout={1}", this.OrganizationUrl, this.ConnectionTimeout); var connection = CrmConnection.Parse(connectionString); string content = File.ReadAllText(this.FilePath); using (var serviceContext = new CrmOrganizationServiceContext(connection)) { try { var dataMap = serviceContext.CreateQuery("importmap").FirstOrDefault(s => s.GetAttributeValue <string>("name") == this.DataMapName); if (dataMap == null) { Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not find data map {0} in the organization with Url {1}", this.DataMapName, this.OrganizationUrl)); return; } var importId = CreateImportEntity(serviceContext, this.SourceEntityName); this.CreateImportFileEntity(serviceContext, content, importId, dataMap.Id); Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Importing data from File {0} to entity {1}", this.FilePath, this.TargetEntityName)); serviceContext.Execute(new ParseImportRequest { ImportId = importId }); serviceContext.Execute(new TransformImportRequest { ImportId = importId }); serviceContext.Execute(new ImportRecordsImportRequest { ImportId = importId }); serviceContext.TryAccessCache(delegate(IOrganizationServiceCache cache) { cache.Mode = OrganizationServiceCacheMode.Disabled; }); int waitCount = 0; bool importCompleted = false; do { int statusCode = GetImportStatus(serviceContext, importId); switch (statusCode) { case DataImportStatusSuccess: Log.LogMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Successfully imported data file {0} to entity {1}.", this.FilePath, this.TargetEntityName)); importCompleted = true; break; case DataImportStatusFailed: Log.LogError(string.Format(CultureInfo.CurrentCulture, "Import of data file {0} to entity {1} failed.", this.FilePath, this.TargetEntityName)); importCompleted = true; break; } if (!importCompleted) { Log.LogMessage("Importing..."); Thread.Sleep(WaitIntervalInMilliseconds); if (++waitCount > this.timeoutInMinutes) { Log.LogError("Import failed to complete during the maximum allocated time"); break; } } }while (!importCompleted); } catch (Exception exception) { Log.LogError(string.Format( CultureInfo.CurrentCulture, "An error occurred while importing Data file {0} to Entity {1} for Organization with Url {2}. [{3}]", this.FilePath, this.TargetEntityName, this.OrganizationUrl, exception.Message)); } } }
private static EntityReference FindClient(string p) { if (p == string.Empty) return null; var context = new CrmOrganizationServiceContext(connection); Contact client = null; ; var splitP = p.Split(); switch (splitP.Length) { case 4: client = (from c in context.CreateQuery<Contact>() where c.FullName == splitP[0] + " " + splitP[3] select c).FirstOrDefault(); break; case 3: client = (from c in context.CreateQuery<Contact>() where c.FullName == splitP[0] + " " + splitP[2] select c).FirstOrDefault(); break; case 2: client = (from c in context.CreateQuery<Contact>() where c.FullName == p select c).FirstOrDefault(); break; case 1: client = (from c in context.CreateQuery<Contact>() where c.LastName == p select c).FirstOrDefault(); break; default: client = null; break; } if (client == null) { if (splitP.Length == 4) { client = (from c in context.CreateQuery<Contact>() where c.FullName == splitP[0] + " " + splitP[1] + " " + splitP[3] select c).FirstOrDefault(); } else { client = (from c in context.CreateQuery<Contact>() where c.FullName == p select c).FirstOrDefault(); } if (client == null) { Console.WriteLine("{0} Ненайден контакт", p); return null; } return client.ToEntityReference(); } else { return client.ToEntityReference(); } }