/// <summary> /// Returns an XML structure containing all the audience details. /// </summary> /// <param name="audienceName">Name of the audience.</param> /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param> /// <returns></returns> internal static string Export(SPServiceContext context, string audienceName, bool includeAllAttributes) { AudienceManager manager = new AudienceManager(context); if (!string.IsNullOrEmpty(audienceName) && !manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } StringBuilder sb = new StringBuilder(); XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb)); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartElement("Audiences"); if (!string.IsNullOrEmpty(audienceName)) { Audience audience = manager.Audiences[audienceName]; ExportAudience(xmlWriter, audience, includeAllAttributes); } else { foreach (Audience audience in manager.Audiences) { ExportAudience(xmlWriter, audience, includeAllAttributes); } } xmlWriter.WriteEndElement(); // Audiences xmlWriter.Flush(); return(sb.ToString()); }
public ChannelController() { audienceManager = new AudienceManager(); _audienceChannelManager = new AudienceChannelManager(); _proposalManager = new ProposalManager(); telemetria = new Trace(); }
public AudienceDocument GetAudienceById(string IdAudience) { AudienceManager repository = new AudienceManager(); AudienceDocument audience = repository.GetAudienceById(IdAudience); return(audience); }
public PublisherProfileController() { publisherProfileManager = new PublisherProfileManager(); siteViewModelManager = new SiteViewModelManager(); audienceManager = new AudienceManager(); _cosmosIdentityManager = new CosmosIdentityManager(); }
public string Protect(AuthenticationTicket data) { if (data == null) { throw new ArgumentNullException("data"); } string publicKey = data.Properties.Dictionary.ContainsKey(PublicKeyPropertyKey) ? data.Properties.Dictionary[PublicKeyPropertyKey] : null; if (string.IsNullOrWhiteSpace(publicKey)) { throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience"); } AudienceManager manager = new AudienceManager(); AudienceModel audience = manager.Find(publicKey); string symmetricKeyAsBase64 = audience.PrivateKey; var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64); var signingKey = new HmacSigningCredentials(keyByteArray); var issued = data.Properties.IssuedUtc; var expires = data.Properties.ExpiresUtc; var token = new JwtSecurityToken(_issuer, publicKey, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey); var handler = new JwtSecurityTokenHandler(); var jwt = handler.WriteToken(token); return(jwt); }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; string symmetricKeyAsBase64 = string.Empty; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { context.SetError("invalid_clientId", "client_Id is not set"); return(Task.FromResult <object>(null)); } AudienceManager manager = new AudienceManager(); AudienceModel audience = manager.Find(context.ClientId); if (audience == null) { context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId)); return(Task.FromResult <object>(null)); } context.Validated(); return(Task.FromResult <object>(null)); }
/// <summary> /// Deletes the specified audience or all audience rules for the specified audience. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="deleteRulesOnly">if set to <c>true</c> [delete rules only].</param> internal static void Delete(SPServiceContext context, string audienceName, bool deleteRulesOnly) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; if (audience.AudienceRules != null && deleteRulesOnly) { audience.AudienceRules = new ArrayList(); if (audience.GroupOperation == AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { // You can't change from mixed mode using the property without setting some internal fields. object audienceInfo = Utilities.GetFieldValue(audience, "m_AudienceInfo"); Utilities.SetPropertyValue(audienceInfo, "NewGroupOperation", AudienceGroupOperation.AUDIENCE_OR_OPERATION); Utilities.SetFieldValue(audience, typeof(Audience), "m_AuidenceGroupOperationChanged", true); } audience.Commit(); return; } if (!deleteRulesOnly) { manager.Audiences.Remove(audience.AudienceID); } }
/// <summary> /// Returns an XML structure containing all the audience details. /// </summary> /// <param name="audienceName">Name of the audience.</param> /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param> /// <returns></returns> internal static string Export(SPServiceContext context, string audienceName, bool includeAllAttributes) { AudienceManager manager = new AudienceManager(context); if (!string.IsNullOrEmpty(audienceName) && !manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } StringBuilder sb = new StringBuilder(); XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb)); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartElement("Audiences"); if (!string.IsNullOrEmpty(audienceName)) { Audience audience = manager.Audiences[audienceName]; ExportAudience(xmlWriter, audience, includeAllAttributes); } else { foreach (Audience audience in manager.Audiences) ExportAudience(xmlWriter, audience, includeAllAttributes); } xmlWriter.WriteEndElement(); // Audiences xmlWriter.Flush(); return sb.ToString(); }
public AudienceController() { _audienceManager = new AudienceChannelManager(); _publisherProfileManager = new PublisherProfileManager(); manager = new AudienceManager(); sessionKey = "AudienceViewModel"; }
/// <summary> /// Deletes the specified audience or all audience rules for the specified audience. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="deleteRulesOnly">if set to <c>true</c> [delete rules only].</param> internal static void Delete(SPServiceContext context, string audienceName, bool deleteRulesOnly) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; if (audience.AudienceRules != null && deleteRulesOnly) { audience.AudienceRules = new ArrayList(); if (audience.GroupOperation == AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { // You can't change from mixed mode using the property without setting some internal fields. object audienceInfo = Utilities.GetFieldValue(audience, "m_AudienceInfo"); Utilities.SetPropertyValue(audienceInfo, "NewGroupOperation", AudienceGroupOperation.AUDIENCE_OR_OPERATION); Utilities.SetFieldValue(audience, typeof (Audience), "m_AuidenceGroupOperationChanged", true); } audience.Commit(); return; } if (!deleteRulesOnly) manager.Audiences.Remove(audience.AudienceID); }
public static Boolean IsInAudience(String audienceNames) { var manager = new AudienceManager(); foreach (var audienceGroup in audienceNames.Split(',')) { var all = true; foreach (String audienceName in audienceGroup.Split('+')) { if (manager.IsMemberOfAudience(SPControl.GetContextWeb(HttpContext.Current).CurrentUser.LoginName, audienceName) == false) { all = false; break; } } if (all == true) { return (true); } } return (false); }
public FileStreamResult CreateScriptFile(Guid IdAudience) { AudienceManager repository = new AudienceManager(); AudienceDocument _audience = repository.GetAudienceById(IdAudience.ToString()); if (_audience != null) { string datafile = CreateScriptGtm(IdAudience); if (datafile.Length > 0) { var byteArray = System.Text.Encoding.ASCII.GetBytes(datafile); var stream = new System.IO.MemoryStream(byteArray); System.Web.Mvc.FileStreamResult _sfile = new System.Web.Mvc.FileStreamResult(stream, "text/plain"); _sfile.FileDownloadName = "scriptGTM.txt"; return(_sfile); } else { return(null); } } return(null); }
public AudienceViewModel() { manager = new AudienceManager(); audience = new AudienceDocument(); preferences = new List <AudiencePreferenceDocument>(); preferencesStringify = string.Empty; telemetria = new Trace(); }
/// <summary> /// Returns an XML structure containing all the rules associated with the audience. /// </summary> /// <param name="audienceName">Name of the audience.</param> /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param> /// <returns></returns> internal static string EnumRules(SPServiceContext context, string audienceName, bool includeAllAttributes) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; ArrayList audienceRules = audience.AudienceRules; if (audienceRules == null || audienceRules.Count == 0) { return("The audience contains no rules."); } string rulesXml = "<rules>\r\n"; foreach (AudienceRuleComponent rule in audienceRules) { if (includeAllAttributes) { rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent); } else { switch (rule.Operator.ToLowerInvariant()) { case "=": case ">": case ">=": case "<": case "<=": case "contains": case "<>": case "not contains": rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent); break; case "reports under": case "member of": rulesXml += string.Format("\t<rule op=\"{0}\" value=\"{1}\" />\r\n", rule.Operator, rule.RightContent); break; case "and": case "or": case "(": case ")": rulesXml += string.Format("\t<rule op=\"{0}\" />\r\n", rule.Operator); break; } } } rulesXml += "</rules>"; return(rulesXml); }
/// <summary> /// Returns an XML structure containing all the rules associated with the audience. /// </summary> /// <param name="audienceName">Name of the audience.</param> /// <param name="includeAllAttributes">if set to <c>true</c> [include all attributes].</param> /// <returns></returns> internal static string EnumRules(SPServiceContext context, string audienceName, bool includeAllAttributes) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; ArrayList audienceRules = audience.AudienceRules; if (audienceRules == null || audienceRules.Count == 0) return "The audience contains no rules."; string rulesXml = "<rules>\r\n"; foreach (AudienceRuleComponent rule in audienceRules) { if (includeAllAttributes) { rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent); } else { switch (rule.Operator.ToLowerInvariant()) { case "=": case ">": case ">=": case "<": case "<=": case "contains": case "<>": case "not contains": rulesXml += string.Format("\t<rule field=\"{1}\" op=\"{0}\" value=\"{2}\" />\r\n", rule.Operator, rule.LeftContent, rule.RightContent); break; case "reports under": case "member of": rulesXml += string.Format("\t<rule op=\"{0}\" value=\"{1}\" />\r\n", rule.Operator, rule.RightContent); break; case "and": case "or": case "(": case ")": rulesXml += string.Format("\t<rule op=\"{0}\" />\r\n", rule.Operator); break; } } } rulesXml += "</rules>"; return rulesXml; }
protected override Audience CreateObject(SiteModelHost typedModelHost, AudienceDefinition definition) { var site = typedModelHost.HostSite; var serverContext = SPServiceContext.GetContext(site); var audienceManager = new AudienceManager(serverContext); var audiencies = audienceManager.Audiences; var result = audiencies.Create(definition.AudienceName, definition.AudienceDescription); return(result); }
private static async Task Main() { //var client = new HttpClient(); //// request token //var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest //{ // Address = "https://sso.local.dealersocket.com/connect/token", // ClientId = "crm_campaign_api" //}); //if (tokenResponse.IsError) //{ // Console.WriteLine(tokenResponse.Error); // return; //} //Console.WriteLine(tokenResponse.Json); //Console.WriteLine("\n\n"); AudienceManager facebookAudienceManager = new AudienceManager { Account = new Account { Id = "2312694348987835", AccessToken = "exampleAccessToken", CustomAudienceId = "exampleCustomAudienceId" }, AddressId = 1, Description = "Testing to get custom response fields", Name = "Test_fields", SiteId = 3, UseMock = false }; // call api var apiClient = new HttpClient(); apiClient.SetBearerToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjVFMDJSYnBLZHhEZ0tWczlMSVhRN3lQcXFhOCIsImtpZCI6IjVFMDJSYnBLZHhEZ0tWczlMSVhRN3lQcXFhOCJ9.eyJpc3MiOiJodHRwczovL2xvY2FsLmRlYWxlcnNvY2tldC5jb20iLCJhdWQiOiJodHRwczovL2xvY2FsLmRlYWxlcnNvY2tldC5jb20vcmVzb3VyY2VzIiwiZXhwIjoxNTg1NjQ4MjYyLCJuYmYiOjE1ODU2NDEwNjIsImNsaWVudF9pZCI6ImNybV9ibGFja2JpcmQiLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJibGFja2JpcmQiLCJzZWFyY2giLCJhcGkiXSwic3ViIjoiMTAwMDk3IiwiYXV0aF90aW1lIjoxNTg1NjQxMDU5LCJpZHAiOiJpZHNydiIsImNybV9yb2xlIjoiYWRtaW4iLCJhZG1pbl9yb2xlIjoic3NvIiwiY3JtX3VzZXJuYW1lIjoiZnNhZmFpciIsImNybV9zdWIiOiJmc2FmYWlyIiwicHJvZHVjdCI6ImNybSIsImFtciI6WyJwYXNzd29yZCJdfQ.Qmmu_GVov0y5vdGnXd_f0kPM6OoY7zsR1POULJJC8iBGIh9_BtpwGwx_c1YxdgXqjZlBcEkdCL1Io3EzeQDn_S7he8YyuNLJm5VADyKP3MsGAftHjAgujlFTqh_jByBzjizQ1wUAkwsUWrwElnbtiWDOOHpyXeCys7HLRehFqHWxTdVM2Roj7cSflJZuZYiTrKniPXUiJf9hAokFBq6a3NMhzB1a6fRh4dGdwx4umaIWZIQprXtKJQecFmyYNiYHidCW5E9vDLRVuh-qqlYCuZssJ4p7ScEndwaQMzaHsPg2Yx1u43396yF8olp9BlLXYND7uhfejTy0PSAgehTKHQ"); var stringContent = new StringContent(JsonConvert.SerializeObject(facebookAudienceManager), Encoding.UTF8, "application/json"); var response = await apiClient.PostAsync("https://localhost:5001/Facebook", stringContent); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } }
/// <summary> /// Creates the specified audience. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="description">The description.</param> /// <param name="rule">The rule.</param> /// <param name="owner">The owner.</param> /// <param name="update">if set to <c>true</c> [update].</param> /// <returns></returns> internal static Audience Create(SPServiceContext context, string audienceName, string description, RuleEnum? rule, string owner, bool update) { AudienceManager manager = new AudienceManager(context); AudienceCollection auds = manager.Audiences; Audience audience; if (auds.AudienceExist(audienceName)) { if (update) { audience = auds[audienceName]; audience.AudienceDescription = description ?? ""; } else throw new SPException("Audience name already exists"); } else audience = auds.Create(audienceName, description??"");// IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null. if (update && rule.HasValue && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { if (rule.Value == RuleEnum.Any && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_OR_OPERATION) audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; else if (rule.Value == RuleEnum.All && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_AND_OPERATION) audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION; } else { if (audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { if (rule.HasValue) { if (rule == RuleEnum.Any) audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; else if (rule == RuleEnum.All) audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION; } else audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; } } if (!string.IsNullOrEmpty(owner)) { audience.OwnerAccountName = owner; } else { audience.OwnerAccountName = string.Empty; } audience.Commit(); return audience; }
private void GetListItems(string str, MenuItem _spMenu, SPList _spListMenu, SPSite thisSite) { AudienceManager audMgr = new AudienceManager(SPServiceContext.GetContext(thisSite)); AudienceCollection audiences = audMgr.Audiences; AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader(); try { SPQuery _spQuery = new SPQuery(); string target = ""; _spQuery.Query = String.Format("<OrderBy><FieldRef Name='LinkOrder' Ascending='True' /><FieldRef Name='Title' Ascending='True' /></OrderBy><Where><And><Eq><FieldRef Name='ParentMenu' LookupId= 'TRUE' /><Value Type='Lookup'>{0}</Value></Eq><Eq><FieldRef Name='ShowMenuItem' /><Value Type='Choice'>Yes</Value></Eq></And></Where>", str); SPListItemCollection _spListItems = _spListMenu.GetItems(_spQuery); MenuItem _spMenuItem = new MenuItem(); foreach (SPListItem item in _spListItems) { target = ""; string audienceFieldValue = (string)item["CanBeSeenBy"]; if (string.IsNullOrEmpty(audienceFieldValue) || AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false)) { if (item["Link URL"] == null) { _spMenuItem = new MenuItem(item["Title"].ToString()); } else { if (_NewWindowFieldExists && item["OpenNewWindow"] != null && (Boolean)item["OpenNewWindow"] == true) { target = "_blank"; } _spMenuItem = new MenuItem(item["Title"].ToString(), "", "", SetServerURL(item["Link URL"].ToString()), target); } GetListItems(item["ID"].ToString(), _spMenuItem, _spListMenu, thisSite); _spMenu.ChildItems.Add(_spMenuItem); } } } catch (Exception ex) { ULSLoggingService myULS = new ULSLoggingService("TopNavProvider", SPContext.Current.Site.WebApplication.Farm); if (myULS != null) { SPDiagnosticsCategory cat = new SPDiagnosticsCategory("CreateChildControls", TraceSeverity.High, EventSeverity.Verbose); cat = myULS[CategoryId.WebPart]; myULS.WriteTrace(1, cat, TraceSeverity.Verbose, String.Format("{0};{1}", ex.Message, ex.StackTrace), myULS.TypeName); } Controls.Add(new LiteralControl(String.Format("An error has occured with this web part. Please contact your system administrator and relay this error message: {0} sub:GetListItems", ex.Message))); } }
protected override IEnumerable <Audience> RetrieveDataObjects() { List <Audience> audiences = new List <Audience>(); SPServiceContext context = null; if (ParameterSetName == "UPA") { SPSiteSubscriptionIdentifier subId; if (SiteSubscription != null) { SPSiteSubscription siteSub = SiteSubscription.Read(); subId = siteSub.Id; } else { subId = SPSiteSubscriptionIdentifier.Default; } SPServiceApplication svcApp = UserProfileServiceApplication.Read(); context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId); } else { using (SPSite site = ContextSite.Read()) { context = SPServiceContext.GetContext(site); } } AudienceManager manager = new AudienceManager(context); if (!string.IsNullOrEmpty(Identity) && !manager.Audiences.AudienceExist(Identity)) { throw new SPException("Audience name does not exist"); } if (!string.IsNullOrEmpty(Identity)) { audiences.Add(manager.Audiences[Identity]); return(audiences); } foreach (Audience audience in manager.Audiences) { audiences.Add(audience); } return(audiences); }
protected override Audience GetCurrentObject(SiteModelHost typedModelHost, AudienceDefinition definition) { var site = typedModelHost.HostSite; var serverContext = SPServiceContext.GetContext(site); var audienceManager = new AudienceManager(serverContext); var audiencies = audienceManager.Audiences; try { return(audiencies[definition.AudienceName]); } catch (Exception) { return(null); } }
public ActionResult MyAudiences() { List <AudienceListItemViewModel> audiences = new List <AudienceListItemViewModel>(); try { string userId = User.Identity.GetUserId(); var publisher = manager.GetPublisherProfile(userId); manager = new AudienceManager(); audiences = manager.GetAudiencesViewModelByPublisherProfileId(publisher.Id); } catch (Exception e) { var messageException = telemetria.MakeMessageException(e, System.Reflection.MethodBase.GetCurrentMethod().Name); telemetria.Critical(messageException); } return(View(audiences)); }
public bool SiteWithTxtVerified(Guid IdAudience) { bool result = false; AudienceManager repository = new AudienceManager(); AudienceDocument audience = repository.GetAudienceById(IdAudience.ToString()); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(audience.WebSiteUrl + "/kindads.txt"); request.Method = "GET"; try { System.Net.WebResponse webResponse = request.GetResponse(); using (System.IO.Stream webStream = webResponse.GetResponseStream()) { if (webStream != null) { using (System.IO.StreamReader responseReader = new System.IO.StreamReader(webStream)) { var _response = responseReader.ReadToEnd(); if (_response != null) { if (_response.Trim() == audience.VerificationString.Trim()) { //Verify Site audience.Verified = true; repository.UpdateAudience(audience); result = true; } } } } } } catch (Exception Ex) { //Do nothing } return(result); }
private string BuildTAQuery() { string query = string.Empty; string audienceGroups = string.Empty; try { SPSite site = new SPSite(SPContext.Current.Web.Url); SPServiceContext context = SPServiceContext.GetContext(site); SPUser currentUser = SPContext.Current.Web.CurrentUser; string loginName = currentUser.ToString().Split('|')[1]; AudienceManager audMgr = new AudienceManager(context); AudienceCollection audiences = audMgr.Audiences; for (int i = 0; i < audiences.Count; i++) { if (audiences[i].AudienceName != "All site users") { if (audiences[i].IsMember(loginName)) { //audienceGroups = audienceGroups + "," + audiences[i].AudienceID; //TargetAudience is the managed property name in the search schema query += "TargetAudience:\"" + audiences[i].AudienceID + "\" OR "; } } } query = query.Substring(0, query.LastIndexOf(" OR ")); } catch (Exception ex) { SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("Content Search Ext Web Part", TraceSeverity.Medium, EventSeverity.Error), TraceSeverity.Medium, "Audience Build Failed: " + ex.Message, null); } return(query); }
public MarketplaceController() { manager = new MarketplaceManager(); audienceChannelManager = new AudienceChannelManager(); audienceManager = new AudienceManager(); }
public SiteManager() { telemetria = new Trace(); repository = new AudienceManager(); }
/// <summary> /// Imports the specified XML. /// </summary> /// <param name="xml">The XML.</param> /// <param name="context">The context.</param> /// <param name="deleteExisting">if set to <c>true</c> [delete existing].</param> /// <param name="compile">if set to <c>true</c> [compile].</param> /// <param name="mapFile">The map file.</param> internal static void Import(string xml, SPServiceContext context, bool deleteExisting, bool compile, string mapFile) { AudienceManager manager = new AudienceManager(context); XmlDocument audiencesDoc = new XmlDocument(); audiencesDoc.LoadXml(xml); XmlNodeList audienceElements = audiencesDoc.SelectNodes("//Audience"); if (audienceElements == null) throw new ArgumentException("The input file does not contain any audience elements."); StringBuilder sb = new StringBuilder(); XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb)); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartElement("Replacements"); Dictionary<Guid, string> ids = new Dictionary<Guid, string>(); if (deleteExisting) { Logger.Write("Progrss: Deleting existing audiences."); foreach (Audience au in manager.Audiences) ids.Add(au.AudienceID, au.AudienceName); foreach (Guid id in ids.Keys) { if (id == Guid.Empty) continue; string name = manager.Audiences[id].AudienceName; manager.Audiences.Remove(id); } } foreach (XmlElement audienceElement in audienceElements) { string audienceName = audienceElement.GetAttribute("AudienceName"); string audienceDesc = audienceElement.GetAttribute("AudienceDescription"); Audience audience; bool updatedAudience = false; if (manager.Audiences.AudienceExist(audienceName)) { Logger.Write("Progress: Updating audience {0}.", audienceName); audience = manager.Audiences[audienceName]; audience.AudienceDescription = audienceDesc ?? ""; updatedAudience = true; } else { // IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null. Logger.Write("Progress: Creating audience {0}.", audienceName); audience = manager.Audiences.Create(audienceName, audienceDesc ?? ""); } audience.GroupOperation = (AudienceGroupOperation)Enum.Parse(typeof (AudienceGroupOperation), audienceElement.GetAttribute("GroupOperation")); audience.OwnerAccountName = audienceElement.GetAttribute("OwnerAccountName"); audience.Commit(); if (updatedAudience && audience.AudienceID != Guid.Empty) { // We've updated an existing audience. xmlWriter.WriteStartElement("Replacement"); xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", (new Guid(audienceElement.GetAttribute("AudienceID")).ToString().ToUpper()))); xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper()); xmlWriter.WriteEndElement(); // Replacement } else if (!updatedAudience && audience.AudienceID != Guid.Empty && ids.ContainsValue(audience.AudienceName)) { // We've added a new audience which we just previously deleted. xmlWriter.WriteStartElement("Replacement"); foreach (Guid id in ids.Keys) { if (ids[id] == audience.AudienceName) { xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", id.ToString().ToUpper())); break; } } xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper()); xmlWriter.WriteEndElement(); // Replacement } XmlElement rulesElement = (XmlElement)audienceElement.SelectSingleNode("rules"); if (rulesElement == null || rulesElement.ChildNodes.Count == 0) { audience.AudienceRules = new ArrayList(); audience.Commit(); continue; } string rules = rulesElement.OuterXml; Logger.Write("Progress: Adding rules to audience {0}.", audienceName); AddAudienceRule.AddRules(context, audienceName, rules, true, compile, false, AppendOp.AND); } xmlWriter.WriteEndElement(); // Replacements if (!string.IsNullOrEmpty(mapFile)) { xmlWriter.Flush(); File.WriteAllText(mapFile, sb.ToString()); } }
protected override void OnListItemClick(ListView l, View v, int position, long id) { switch (position) { case 0: Android.Widget.Toast.MakeText(this, Config.Version, Android.Widget.ToastLength.Short).Show(); break; case 1: Android.Widget.Toast.MakeText(this, Config.PrivacyStatus.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 2: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusOptIn; break; case 3: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusOptOut; break; case 4: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusUnknown; break; case 5: Android.Widget.Toast.MakeText(this, Config.LifetimeValue.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 6: Android.Widget.Toast.MakeText(this, Config.UserIdentifier, Android.Widget.ToastLength.Short).Show(); break; case 7: Config.UserIdentifier = "customUserIdentifier"; break; case 8: Android.Widget.Toast.MakeText(this, Config.DebugLogging.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 9: Config.DebugLogging = (Java.Lang.Boolean)true; break; case 10: Config.DebugLogging = (Java.Lang.Boolean)false; break; case 11: Config.SetSmallIconResourceId(Resource.Drawable.Icon); break; case 12: Config.SetLargeIconResourceId(Resource.Drawable.Icon); break; case 13: Stream st = Assets.Open("ADBMobileConfig-Another.json"); Config.OverrideConfigStream(st); break; case 14: var sd = new Dictionary <string, Java.Lang.Object> (); sd.Add("key", (Java.Lang.Object) "value"); Analytics.TrackState("stateName", (IDictionary <string, Java.Lang.Object>)sd); break; case 15: Analytics.TrackAction("actionName", cData); break; case 16: Location loc = new Location(LocationManager.GpsProvider);; loc.Latitude = 111; loc.Longitude = 44; loc.Accuracy = 5; Analytics.TrackLocation(loc, cData); break; case 17: Analytics.TrackBeacon("UUID", "1", "2", Analytics.BEACON_PROXIMITY.ProximityImmediate, cData); break; case 18: Analytics.ClearBeacon(); break; case 19: Analytics.TrackLifetimeValueIncrease(new Java.Math.BigDecimal("1.11"), null); break; case 20: Analytics.TrackTimedActionStart("timedAction", null); break; case 21: IDictionary <string, Java.Lang.Object> updateCData = new Dictionary <string, Java.Lang.Object> (); updateCData.Add("key", "value"); Analytics.TrackTimedActionUpdate("timedAction", (IDictionary <string, Java.Lang.Object>)updateCData); break; case 22: Analytics.TrackTimedActionEnd("timedAction", new TimedActionBlock()); break; case 23: Android.Widget.Toast.MakeText(this, Analytics.TrackingTimedActionExists("timedAction").ToString(), Android.Widget.ToastLength.Short).Show(); break; case 24: Android.Widget.Toast.MakeText(this, Analytics.TrackingIdentifier, Android.Widget.ToastLength.Short).Show(); break; case 25: Android.Widget.Toast.MakeText(this, Analytics.QueueSize.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 26: Analytics.ClearQueue(); break; case 27: Analytics.SendQueuedHits(); break; // AAM case 28: Android.Widget.Toast.MakeText(this, AudienceManager.Dpuuid, Android.Widget.ToastLength.Short).Show(); Android.Widget.Toast.MakeText(this, AudienceManager.Dpid, Android.Widget.ToastLength.Short).Show(); break; case 29: Android.Widget.Toast.MakeText(this, AudienceManager.VisitorProfile != null? AudienceManager.VisitorProfile.ToString():"", Android.Widget.ToastLength.Short).Show(); break; case 30: AudienceManager.SetDpidAndDpuuid("testDppid", "testDpuuid"); break; case 31: IDictionary <string, Java.Lang.Object> traits = new Dictionary <string, Java.Lang.Object> (); traits.Add("trait", "b"); AudienceManager.SignalWithData(traits, new AudienceManagerCallback()); break; case 32: AudienceManager.Reset(); break; //Target case 33: IDictionary <string, Java.Lang.Object> parameters = new Dictionary <string, Java.Lang.Object> (); parameters.Add("key", "value"); var req = Target.CreateRequest("AndroidTest", "defGal", parameters); Target.LoadRequest(req, new TargetCallback()); break; case 34: var orderConfirm = Target.CreateOrderConfirmRequest("myOrder", "12345", "29.41", "cool stuff", null); Target.LoadRequest(orderConfirm, new TargetCallback()); break; case 35: Target.ClearCookies(); break; case 36: Android.Widget.Toast.MakeText(this, Target.PcID, Android.Widget.ToastLength.Short).Show(); break; case 37: Android.Widget.Toast.MakeText(this, Target.SessionID, Android.Widget.ToastLength.Short).Show(); break; //VisitorID case 38: Android.Widget.Toast.MakeText(this, Visitor.MarketingCloudId, Android.Widget.ToastLength.Short).Show(); break; case 39: IDictionary <string, string> ids = new Dictionary <string, string> (); ids.Add("pushID", "value2"); Visitor.SyncIdentifiers(ids); break; //Media case 40: settings = Media.SettingsWith("name1", 10, "playerName1", "playerID1"); settings.Milestones = "25,50,75"; break; case 41: MediaSettings adSettings = Media.AdSettingsWith("adName1", 2, "playerName1", "name1", "podName1", 4, "CPM1"); break; case 42: Media.Open(settings, new MediaCallback()); break; case 43: Media.Close("name1"); break; case 44: Media.Play("name1", 0); break; case 45: Media.Complete("name1", 3); break; case 46: Media.Stop("name1", 3); break; case 47: Media.Click("adName1", 3); break; case 48: Media.Track("name1", null); break; } }
/// <summary> /// Adds the rules. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="rules">The rules.</param> /// <param name="clearExistingRules">if set to <c>true</c> [clear existing rules].</param> /// <param name="compile">if set to <c>true</c> [compile].</param> /// <param name="groupExisting">if set to <c>true</c> [group existing].</param> /// <param name="appendOp">The append op.</param> /// <returns></returns> internal static ArrayList AddRules(SPServiceContext context, string audienceName, string rules, bool clearExistingRules, bool compile, bool groupExisting, AppendOp appendOp) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; /* * Operator Need left and right operands (not a group operator) * = Yes * > Yes * >= Yes * < Yes * <= Yes * Contains Yes * Reports Under Yes (Left operand must be 'Everyone') * <> Yes * Not contains Yes * AND No * OR No * ( No * ) No * Member Of Yes (Left operand must be 'DL') */ XmlDocument rulesDoc = new XmlDocument(); rulesDoc.LoadXml(rules); ArrayList audienceRules = audience.AudienceRules; bool ruleListNotEmpty = false; if (audienceRules == null || clearExistingRules) { audienceRules = new ArrayList(); } else { ruleListNotEmpty = true; } //if the rule is not emply, start with a group operator 'AND' to append if (ruleListNotEmpty) { if (groupExisting) { audienceRules.Insert(0, new AudienceRuleComponent(null, "(", null)); audienceRules.Add(new AudienceRuleComponent(null, ")", null)); } audienceRules.Add(new AudienceRuleComponent(null, appendOp.ToString(), null)); } if (rulesDoc.SelectNodes("//rule") == null || rulesDoc.SelectNodes("//rule").Count == 0) { throw new ArgumentException("No rules were supplied."); } foreach (XmlElement rule in rulesDoc.SelectNodes("//rule")) { string op = rule.GetAttribute("op").ToLowerInvariant(); string field = null; string val = null; bool valIsRequired = true; bool fieldIsRequired = false; switch (op) { case "=": case ">": case ">=": case "<": case "<=": case "contains": case "<>": case "not contains": field = rule.GetAttribute("field"); val = rule.GetAttribute("value"); fieldIsRequired = true; break; case "reports under": field = "Everyone"; val = rule.GetAttribute("value"); break; case "member of": field = "DL"; val = rule.GetAttribute("value"); break; case "and": case "or": case "(": case ")": valIsRequired = false; break; default: throw new ArgumentException(string.Format("Rule operator is invalid: {0}", rule.GetAttribute("op"))); } if (valIsRequired && string.IsNullOrEmpty(val)) { throw new ArgumentNullException(string.Format("Rule value attribute is missing or invalid: {0}", rule.GetAttribute("value"))); } if (fieldIsRequired && string.IsNullOrEmpty(field)) { throw new ArgumentNullException(string.Format("Rule field attribute is missing or invalid: {0}", rule.GetAttribute("field"))); } AudienceRuleComponent r0 = new AudienceRuleComponent(field, op, val); audienceRules.Add(r0); } audience.AudienceRules = audienceRules; audience.Commit(); if (compile) { SPServiceApplication svcApp = Utilities.GetUserProfileServiceApplication(context); if (svcApp != null) { CompileAudience(svcApp.Id, audience.AudienceName); } } return(audienceRules); }
private static void Main(string[] args) { SPSecurity.CatchAccessDeniedException = false; SPSite site = new SPSite("http://chiron"); UserProfileManager pm = new UserProfileManager(ServerContext.GetContext(site)); foreach (UserProfile profile in pm) { //User PropertyConstants to get values Console.WriteLine("Account: " + profile[PropertyConstants.AccountName]); //Check for null if (profile[PropertyConstants.WebSite].Value != null) { Console.WriteLine(profile[PropertyConstants.WebSite]); } } //ToDo: Create the AD User "class\bart" and remove the breakpoint Console.WriteLine("Current Number of Profiles" + pm.Count); if (pm.GetUserProfile(@"class\bart") != null) { pm.RemoveUserProfile(@"class\bart"); } //Create Bart's Profile UserProfile p = pm.CreateUserProfile(@"class\bart"); //Set it's Office to Springfield p[PropertyConstants.Office].Value = "Springfield"; p.Commit(); Console.WriteLine("Current Number of Profiles" + pm.Count); //Showing Audiences AudienceManager am = new AudienceManager(ServerContext.GetContext(site)); foreach (Audience a in am.Audiences) { Console.WriteLine("Audience: " + a.AudienceName); } Audience simpsons; try { simpsons = am.Audiences.Create("Springfield Users", "All users working in Springfield"); ArrayList audienceRules = new ArrayList(); AudienceRuleComponent arc = new AudienceRuleComponent("Office", "Contains", "Springfield"); audienceRules.Add(arc); simpsons.AudienceRules = audienceRules; simpsons.Commit(); } catch (AudienceDuplicateNameException e) { simpsons = am.Audiences["Springfield Users"]; } //Compiling Audience can only be done using the UI - sorry :) }
protected override void OnListItemClick(ListView l, View v, int position, long id) { switch (position) { case 0: Android.Widget.Toast.MakeText(this, Config.Version, Android.Widget.ToastLength.Short).Show(); break; case 1: Android.Widget.Toast.MakeText(this, Config.PrivacyStatus.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 2: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusOptIn; break; case 3: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusOptOut; break; case 4: Config.PrivacyStatus = MobilePrivacyStatus.MobilePrivacyStatusUnknown; break; case 5: Android.Widget.Toast.MakeText(this, Config.LifetimeValue.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 6: Android.Widget.Toast.MakeText(this, Config.UserIdentifier, Android.Widget.ToastLength.Short).Show(); break; case 7: Config.UserIdentifier = "customUserIdentifier"; break; case 8: Android.Widget.Toast.MakeText(this, Config.DebugLogging.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 9: Config.DebugLogging = (Java.Lang.Boolean)true; break; case 10: Config.DebugLogging = (Java.Lang.Boolean)false; break; case 11: Config.SetSmallIconResourceId(Resource.Drawable.Icon); break; case 12: Config.SetLargeIconResourceId(Resource.Drawable.Icon); break; case 13: Stream st = Assets.Open("ADBMobileConfig-Another.json"); Config.OverrideConfigStream(st); break; case 14: var sd = new Dictionary <string, Java.Lang.Object> (); sd.Add("key", (Java.Lang.Object) "value"); Analytics.TrackState("stateName", (IDictionary <string, Java.Lang.Object>)sd); break; case 15: Analytics.TrackAction("actionName", cData); break; case 16: Location loc = new Location(LocationManager.GpsProvider);; loc.Latitude = 111; loc.Longitude = 44; loc.Accuracy = 5; Analytics.TrackLocation(loc, cData); break; case 17: Analytics.TrackBeacon("UUID", "1", "2", Analytics.BEACON_PROXIMITY.ProximityImmediate, cData); break; case 18: Analytics.ClearBeacon(); break; case 19: Analytics.TrackLifetimeValueIncrease(new Java.Math.BigDecimal("1.11"), null); break; case 20: Analytics.TrackTimedActionStart("timedAction", null); break; case 21: IDictionary <string, Java.Lang.Object> updateCData = new Dictionary <string, Java.Lang.Object> (); updateCData.Add("key", "value"); Analytics.TrackTimedActionUpdate("timedAction", (IDictionary <string, Java.Lang.Object>)updateCData); break; case 22: Analytics.TrackTimedActionEnd("timedAction", new TimedActionBlock()); break; case 23: Android.Widget.Toast.MakeText(this, Analytics.TrackingTimedActionExists("timedAction").ToString(), Android.Widget.ToastLength.Short).Show(); break; case 24: Android.Widget.Toast.MakeText(this, Analytics.TrackingIdentifier, Android.Widget.ToastLength.Short).Show(); break; case 25: Android.Widget.Toast.MakeText(this, Analytics.QueueSize.ToString(), Android.Widget.ToastLength.Short).Show(); break; case 26: Analytics.ClearQueue(); break; case 27: Analytics.SendQueuedHits(); break; // AAM case 28: Android.Widget.Toast.MakeText(this, AudienceManager.Dpuuid, Android.Widget.ToastLength.Short).Show(); Android.Widget.Toast.MakeText(this, AudienceManager.Dpid, Android.Widget.ToastLength.Short).Show(); break; case 29: Android.Widget.Toast.MakeText(this, AudienceManager.VisitorProfile != null? AudienceManager.VisitorProfile.ToString():"", Android.Widget.ToastLength.Short).Show(); break; case 30: AudienceManager.SetDpidAndDpuuid("testDppid", "testDpuuid"); break; case 31: IDictionary <string, Java.Lang.Object> traits = new Dictionary <string, Java.Lang.Object> (); traits.Add("trait", "b"); AudienceManager.SignalWithData(traits, new AudienceManagerCallback()); break; case 32: AudienceManager.Reset(); break; //Target case 33: IDictionary <string, Java.Lang.Object> parameters = new Dictionary <string, Java.Lang.Object> (); parameters.Add("key", "value"); var req = Target.CreateRequest("AndroidTest", "defGal", parameters); Target.LoadRequest(req, new TargetCallback()); break; case 34: var orderConfirm = Target.CreateOrderConfirmRequest("myOrder", "12345", "29.41", "cool stuff", null); Target.LoadRequest(orderConfirm, new TargetCallback()); break; case 35: Target.ClearCookies(); break; case 36: Android.Widget.Toast.MakeText(this, Target.PcID, Android.Widget.ToastLength.Short).Show(); break; case 37: Android.Widget.Toast.MakeText(this, Target.SessionID, Android.Widget.ToastLength.Short).Show(); break; //VisitorID case 38: Android.Widget.Toast.MakeText(this, Visitor.MarketingCloudId, Android.Widget.ToastLength.Short).Show(); break; case 39: IDictionary <string, string> ids = new Dictionary <string, string> (); ids.Add("pushID", "value2"); Visitor.SyncIdentifiers(ids); break; //Media case 40: settings = Media.SettingsWith("name1", 10, "playerName1", "playerID1"); settings.Milestones = "25,50,75"; break; case 41: MediaSettings adSettings = Media.AdSettingsWith("adName1", 2, "playerName1", "name1", "podName1", 4, "CPM1"); break; case 42: Media.Open(settings, new MediaCallback()); break; case 43: Media.Close("name1"); break; case 44: Media.Play("name1", 0); break; case 45: Media.Complete("name1", 3); break; case 46: Media.Stop("name1", 3); break; case 47: Media.Click("adName1", 3); break; case 48: Media.Track("name1", null); break; case 49: // "setAdvertisingIdentifier", Config.SubmitAdvertisingIdentifierTask(new AdidTaskNotNull()); break; case 50: // "setPushIdentifier", Config.SetPushIdentifier("testPushId"); break; case 51: // "registerAdobeDataCallback" Config.RegisterAdobeDataCallback(new AdobeDataCallback()); break; case 52: // "trackAdobeDeepLink" Config.TrackAdobeDeepLink(Android.Net.Uri.Parse("https://adobe.com?a.deeplink.id=121212")); break; case 53: // "acquisitionCampaignStartForApp" ThreadPool.QueueUserWorkItem(o => doCampaignStartForApp()); break; case 54: // "targetLoadRequestWithRequestLocation" IDictionary <string, Java.Lang.Object> mboxData2 = new Dictionary <string, Java.Lang.Object>(); mboxData2.Add("mboxkey", "val"); IDictionary <string, Java.Lang.Object> orderData2 = new Dictionary <string, Java.Lang.Object>(); orderData2.Add("orderkey", "val"); IDictionary <string, Java.Lang.Object> profileData2 = new Dictionary <string, Java.Lang.Object>(); profileData2.Add("profilekey", "val"); IDictionary <string, Java.Lang.Object> requestLocationData = new Dictionary <string, Java.Lang.Object>(); requestLocationData.Add("key", "val"); Target.LoadRequest("someMbox", "defaultContent", mboxData2, orderData2, profileData2, requestLocationData, this); break; case 55: // "targetThirdPartyId" Android.Widget.Toast.MakeText(this, Target.ThirdPartyID, Android.Widget.ToastLength.Short).Show(); break; case 56: // "targetSetThirdPartyId" Target.ThirdPartyID = "testThirdPartyId"; break; case 57: // "targetPcID" Toast.MakeText(this, Target.PcID, Android.Widget.ToastLength.Short).Show(); break; case 58: // "targetSessionID" Toast.MakeText(this, Target.SessionID, Android.Widget.ToastLength.Short).Show(); break; case 59: // "visitorSyncIdentifiers" Visitor.SyncIdentifier("idType", "identifier0", VisitorID.VisitorIDAuthenticationState.VisitorIdAuthenticationStateAuthenticated); break; case 60: // "visitorSyncIdentifiersAuthState" IDictionary <string, string> visitorData = new Dictionary <string, string>(); visitorData.Add("key", "val"); Visitor.SyncIdentifiers(visitorData); break; case 61: // "visitorSyncIdentifierWithTypeAuthState" IDictionary <string, string> visitorData2 = new Dictionary <string, string>(); visitorData2.Add("key2", "val2"); Visitor.SyncIdentifiers(visitorData2, VisitorID.VisitorIDAuthenticationState.VisitorIdAuthenticationStateUnknown); break; case 62: // "visitorGetIDs" if (Visitor.Identifiers != null) { Toast.MakeText(this, Visitor.Identifiers.ToString(), ToastLength.Long).Show(); } break; case 63: // "visitorAppendToURL" Toast.MakeText(this, Visitor.AppendToURL("https://adobe.com"), ToastLength.Long).Show(); break; } }
/// <summary> /// Imports the specified XML. /// </summary> /// <param name="xml">The XML.</param> /// <param name="context">The context.</param> /// <param name="deleteExisting">if set to <c>true</c> [delete existing].</param> /// <param name="compile">if set to <c>true</c> [compile].</param> /// <param name="mapFile">The map file.</param> internal static void Import(string xml, SPServiceContext context, bool deleteExisting, bool compile, string mapFile) { AudienceManager manager = new AudienceManager(context); XmlDocument audiencesDoc = new XmlDocument(); audiencesDoc.LoadXml(xml); XmlNodeList audienceElements = audiencesDoc.SelectNodes("//Audience"); if (audienceElements == null) { throw new ArgumentException("The input file does not contain any audience elements."); } StringBuilder sb = new StringBuilder(); XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb)); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteStartElement("Replacements"); Dictionary <Guid, string> ids = new Dictionary <Guid, string>(); if (deleteExisting) { Logger.Write("Progrss: Deleting existing audiences."); foreach (Audience au in manager.Audiences) { ids.Add(au.AudienceID, au.AudienceName); } foreach (Guid id in ids.Keys) { if (id == Guid.Empty) { continue; } string name = manager.Audiences[id].AudienceName; manager.Audiences.Remove(id); } } foreach (XmlElement audienceElement in audienceElements) { string audienceName = audienceElement.GetAttribute("AudienceName"); string audienceDesc = audienceElement.GetAttribute("AudienceDescription"); Audience audience; bool updatedAudience = false; if (manager.Audiences.AudienceExist(audienceName)) { Logger.Write("Progress: Updating audience {0}.", audienceName); audience = manager.Audiences[audienceName]; audience.AudienceDescription = audienceDesc ?? ""; updatedAudience = true; } else { // IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null. Logger.Write("Progress: Creating audience {0}.", audienceName); audience = manager.Audiences.Create(audienceName, audienceDesc ?? ""); } audience.GroupOperation = (AudienceGroupOperation)Enum.Parse(typeof(AudienceGroupOperation), audienceElement.GetAttribute("GroupOperation")); audience.OwnerAccountName = audienceElement.GetAttribute("OwnerAccountName"); audience.Commit(); if (updatedAudience && audience.AudienceID != Guid.Empty) { // We've updated an existing audience. xmlWriter.WriteStartElement("Replacement"); xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", (new Guid(audienceElement.GetAttribute("AudienceID")).ToString().ToUpper()))); xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper()); xmlWriter.WriteEndElement(); // Replacement } else if (!updatedAudience && audience.AudienceID != Guid.Empty && ids.ContainsValue(audience.AudienceName)) { // We've added a new audience which we just previously deleted. xmlWriter.WriteStartElement("Replacement"); foreach (Guid id in ids.Keys) { if (ids[id] == audience.AudienceName) { xmlWriter.WriteElementString("SearchString", string.Format("(?i:{0})", id.ToString().ToUpper())); break; } } xmlWriter.WriteElementString("ReplaceString", audience.AudienceID.ToString().ToUpper()); xmlWriter.WriteEndElement(); // Replacement } XmlElement rulesElement = (XmlElement)audienceElement.SelectSingleNode("rules"); if (rulesElement == null || rulesElement.ChildNodes.Count == 0) { audience.AudienceRules = new ArrayList(); audience.Commit(); continue; } string rules = rulesElement.OuterXml; Logger.Write("Progress: Adding rules to audience {0}.", audienceName); AddAudienceRule.AddRules(context, audienceName, rules, true, compile, false, AppendOp.AND); } xmlWriter.WriteEndElement(); // Replacements if (!string.IsNullOrEmpty(mapFile)) { xmlWriter.Flush(); File.WriteAllText(mapFile, sb.ToString()); } }
/// <summary> /// Create all your controls here for rendering. /// Try to avoid using the RenderWebPart() method. /// </summary> protected override void CreateChildControls() { // Create ASPMenu control. ChromeType = PartChromeType.None; /*string MenuID = _MenuList + "CustomTopNavWebPart";*/ AspMenu _spMenu = new AspMenu { UseSimpleRendering = true, UseSeparateCSS = false, Orientation = Orientation.Horizontal, MaximumDynamicDisplayLevels = 5, CssClass = "s4-tn" }; SPWeb thisWeb = null; try { //Set some defaults if (Set_TopNavigationMenu.ToLower() != "yes" && Set_TopNavigationMenu.ToLower() != "no") { Set_TopNavigationMenu = "yes"; } if (Set_TopNavigationMenu.ToLower() == "yes") { Set_MenuName = "TopNavigationMenu"; Set_MenuOrientation = "horizontal"; } //Set the controls look and feel //For some reason the ID of the Menu matters when using this as a Top Menu, the name must be TopNavigationMenu or the dropdowns are blank. _spMenu.ID = Set_MenuName; _spMenu.EnableViewState = false; SPSite thisSite = null; try { if (string.IsNullOrEmpty(Set_ServerURL)) { //Try to get the ServerURl from the web config Set_ServerURL = ConfigurationManager.AppSettings["topNavWebAppURL"]; if (string.IsNullOrEmpty(Set_ServerURL)) { //If cannot get from web config then set to the current web application Set_ServerURL = SPContext.Current.Site.WebApplication.GetResponseUri(SPContext.Current.Site.Zone).AbsoluteUri; } thisSite = new SPSite(Set_ServerURL); } else { thisSite = new SPSite(Set_ServerURL); } if (Set_WebSite == "" || Set_WebSite == null) { thisWeb = thisSite.OpenWeb("/"); } else { thisWeb = thisSite.OpenWeb(Set_WebSite); } } finally { if (thisSite != null) { thisSite.Dispose(); } } AudienceManager audMgr = new AudienceManager(SPServiceContext.GetContext(thisSite)); AudienceCollection audiences = audMgr.Audiences; AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader(); string target = ""; SPList _spListMenu = thisWeb.Lists[Set_MenuList]; _NewWindowFieldExists = _spListMenu.Fields.ContainsField("OpenNewWindow"); SPQuery _spQuery = new SPQuery(); MenuItem _spMenuItem = new MenuItem(); _spQuery.Query = "<OrderBy><FieldRef Name='LinkOrder' Ascending='True' /><FieldRef Name='Title' Ascending='True' /></OrderBy><Where><And><IsNull><FieldRef Name='ParentMenu' /></IsNull><Eq><FieldRef Name='ShowMenuItem' /><Value Type='Choice'>Yes</Value></Eq></And></Where>"; SPListItemCollection _spListItems = _spListMenu.GetItems(_spQuery); foreach (SPListItem item in _spListItems) { string audienceFieldValue = (string)item["CanBeSeenBy"]; if (string.IsNullOrEmpty(audienceFieldValue) || AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false)) { if (item["Link URL"] == null) { _spMenuItem = new MenuItem(item["Title"].ToString()); } else { if (_NewWindowFieldExists && item["OpenNewWindow"] != null && (Boolean)item["OpenNewWindow"] == true) { target = "_blank"; } _spMenuItem = new MenuItem(item["Title"].ToString(), "", "", SetServerURL(item["LinkURL"].ToString()), target); } GetListItems(item["ID"].ToString(), _spMenuItem, _spListMenu, thisSite); if (Page.Request.Url.AbsoluteUri == item["Link URL"].ToString()) { _spMenuItem.Selected = true; } _spMenu.Items.Add(_spMenuItem); } } Controls.Add(_spMenu); } catch (Exception ex) { ULSLoggingService myULS = new ULSLoggingService("TopNavProvider", SPContext.Current.Site.WebApplication.Farm); if (myULS != null) { SPDiagnosticsCategory cat = new SPDiagnosticsCategory("CreateChildControls", TraceSeverity.High, EventSeverity.Verbose); cat = myULS[CategoryId.WebPart]; myULS.WriteTrace(1, cat, TraceSeverity.Verbose, String.Format("{0};{1}", ex.Message, ex.StackTrace), myULS.TypeName); } Controls.Add(new LiteralControl(String.Format("An error has occured with this web part. Please contact your system administrator and relay this error message: {0} sub:CreateChildControls ", ex.Message))); } finally { if (thisWeb != null) { thisWeb.Dispose(); } } }
void Awake () { instance = this; }
/// <summary> /// Adds the rules. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="rules">The rules.</param> /// <param name="clearExistingRules">if set to <c>true</c> [clear existing rules].</param> /// <param name="compile">if set to <c>true</c> [compile].</param> /// <param name="groupExisting">if set to <c>true</c> [group existing].</param> /// <param name="appendOp">The append op.</param> /// <returns></returns> internal static ArrayList AddRules(SPServiceContext context, string audienceName, string rules, bool clearExistingRules, bool compile, bool groupExisting, AppendOp appendOp) { AudienceManager manager = new AudienceManager(context); if (!manager.Audiences.AudienceExist(audienceName)) { throw new SPException("Audience name does not exist"); } Audience audience = manager.Audiences[audienceName]; /* Operator Need left and right operands (not a group operator) = Yes > Yes >= Yes < Yes <= Yes Contains Yes Reports Under Yes (Left operand must be 'Everyone') <> Yes Not contains Yes AND No OR No ( No ) No Member Of Yes (Left operand must be 'DL') */ XmlDocument rulesDoc = new XmlDocument(); rulesDoc.LoadXml(rules); ArrayList audienceRules = audience.AudienceRules; bool ruleListNotEmpty = false; if (audienceRules == null || clearExistingRules) audienceRules = new ArrayList(); else ruleListNotEmpty = true; //if the rule is not emply, start with a group operator 'AND' to append if (ruleListNotEmpty) { if (groupExisting) { audienceRules.Insert(0, new AudienceRuleComponent(null, "(", null)); audienceRules.Add(new AudienceRuleComponent(null, ")", null)); } audienceRules.Add(new AudienceRuleComponent(null, appendOp.ToString(), null)); } if (rulesDoc.SelectNodes("//rule") == null || rulesDoc.SelectNodes("//rule").Count == 0) throw new ArgumentException("No rules were supplied."); foreach (XmlElement rule in rulesDoc.SelectNodes("//rule")) { string op = rule.GetAttribute("op").ToLowerInvariant(); string field = null; string val = null; bool valIsRequired = true; bool fieldIsRequired = false; switch (op) { case "=": case ">": case ">=": case "<": case "<=": case "contains": case "<>": case "not contains": field = rule.GetAttribute("field"); val = rule.GetAttribute("value"); fieldIsRequired = true; break; case "reports under": field = "Everyone"; val = rule.GetAttribute("value"); break; case "member of": field = "DL"; val = rule.GetAttribute("value"); break; case "and": case "or": case "(": case ")": valIsRequired = false; break; default: throw new ArgumentException(string.Format("Rule operator is invalid: {0}", rule.GetAttribute("op"))); } if (valIsRequired && string.IsNullOrEmpty(val)) throw new ArgumentNullException(string.Format("Rule value attribute is missing or invalid: {0}", rule.GetAttribute("value"))); if (fieldIsRequired && string.IsNullOrEmpty(field)) throw new ArgumentNullException(string.Format("Rule field attribute is missing or invalid: {0}", rule.GetAttribute("field"))); AudienceRuleComponent r0 = new AudienceRuleComponent(field, op, val); audienceRules.Add(r0); } audience.AudienceRules = audienceRules; audience.Commit(); if (compile) { SPServiceApplication svcApp = Utilities.GetUserProfileServiceApplication(context); if (svcApp != null) CompileAudience(svcApp.Id, audience.AudienceName); } return audienceRules; }
/// <summary> /// Creates the specified audience. /// </summary> /// <param name="context">The context.</param> /// <param name="audienceName">Name of the audience.</param> /// <param name="description">The description.</param> /// <param name="rule">The rule.</param> /// <param name="owner">The owner.</param> /// <param name="update">if set to <c>true</c> [update].</param> /// <returns></returns> internal static Audience Create(SPServiceContext context, string audienceName, string description, RuleEnum?rule, string owner, bool update) { AudienceManager manager = new AudienceManager(context); AudienceCollection auds = manager.Audiences; Audience audience; if (auds.AudienceExist(audienceName)) { if (update) { audience = auds[audienceName]; audience.AudienceDescription = description ?? ""; } else { throw new SPException("Audience name already exists"); } } else { audience = auds.Create(audienceName, description ?? "");// IMPORTANT: the create method does not do a null check but the methods that load the resultant collection assume not null. } if (update && rule.HasValue && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { if (rule.Value == RuleEnum.Any && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_OR_OPERATION) { audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; } else if (rule.Value == RuleEnum.All && audience.GroupOperation != AudienceGroupOperation.AUDIENCE_AND_OPERATION) { audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION; } } else { if (audience.GroupOperation != AudienceGroupOperation.AUDIENCE_MIX_OPERATION) { if (rule.HasValue) { if (rule == RuleEnum.Any) { audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; } else if (rule == RuleEnum.All) { audience.GroupOperation = AudienceGroupOperation.AUDIENCE_AND_OPERATION; } } else { audience.GroupOperation = AudienceGroupOperation.AUDIENCE_OR_OPERATION; } } } if (!string.IsNullOrEmpty(owner)) { audience.OwnerAccountName = owner; } else { audience.OwnerAccountName = string.Empty; } audience.Commit(); return(audience); }
public Functions() { UserPriority = new Dictionary <string, int>(); _notificationManager = new AudienceManager(); }
public SiteViewModelManager() { _audienceManager = new AudienceManager(); }