protected override void OnPreRender(EventArgs e) { SPMonitoredScope scope = new SPMonitoredScope(this.Title + " OnPreRender"); try { base.ShouldLogQuery = false; if (!this._isSrhdcError) { if (SPContext.Current.Web.UIVersion == 4) { CssRegistration.Register("Themable/search.css"); } else { CssRegistration.Register("portal.css"); } if (!this.Page.ClientScript.IsClientScriptBlockRegistered("resizeprofileimg_peoplesearch")) { this.Page.ClientScript.RegisterClientScriptBlock(base.GetType(), "resizeprofileimg_peoplesearch", "\r\n<script>\r\nfunction resizeProfileImageCore(objid, maxWidth, maxHeight) {\r\n var obj = document.getElementById(objid);\r\n var oldResize=obj.onresize;\r\n obj.onresize=null;\r\n if ((obj != null) && (obj.height > 0) && (obj.width > 0)) {\r\n try {\r\n var ratiomax = maxHeight/maxWidth;\r\n var ratioobj = obj.height/obj.width;\r\n\r\n if (ratiomax > ratioobj) { // too wide\r\n obj.width = maxWidth;\r\n }\r\n else { // too tall\r\n obj.height = maxHeight;\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n obj.onresize=oldResize;\r\n}\r\nfunction resizeProfileImage(objid) {\r\n resizeProfileImageCore(objid, 75, 75);\r\n}\r\n</script>\r\n"); } base.OnPreRender(e); } } finally { if (scope != null) { scope.Dispose(); } } }
public void InitView(ILastTasksByUserView view) { using (SPMonitoredScope monitoredScope = new SPMonitoredScope("LastTasksByUserPresenter -> InitView")) { _innerPresenter.InitView(view); } }
public void DeleteTaskByItemId(int itemId) { using (SPMonitoredScope monitoredScope = new SPMonitoredScope("LastTasksByUserPresenter -> DeleteTaskByItemId")) { _innerPresenter.DeleteTaskByItemId(itemId); } }
/// <summary> /// Initializes a new instance of the <see cref="SiteTaxonomyCache"/> class. /// </summary> /// <param name="site"> /// The site. /// </param> /// <param name="termStoreName"> /// The term store name. /// </param> /// <param name="taxonomyHelper">The taxonomy helper.</param> public SiteTaxonomyCache(SPSite site, string termStoreName, ITaxonomyHelper taxonomyHelper) { SPMonitoredScope monitor = null; this.taxonomyHelper = taxonomyHelper; try { monitor = new SPMonitoredScope("GSoft.Dynamite - Site taxonomy cache initialization"); } catch (TypeInitializationException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } catch (ArgumentNullException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } if (site == null) { throw new ArgumentNullException("site", "SPSite is currently null, please pass a valid site as argument."); } this.SiteId = site.ID; // Don't send in the updateCache=true setting - let the SharePoint inner Taxonomy cache refresh itself normally (every 10 seconds or so) this.TaxonomySession = new TaxonomySession(site); if (!string.IsNullOrEmpty(termStoreName)) { this.SiteCollectionGroup = this.TaxonomySession.TermStores[termStoreName].GetSiteCollectionGroup(site); } else { // Use default term store TermStore termStore = null; if (taxonomyHelper != null) { termStore = this.taxonomyHelper.GetDefaultSiteCollectionTermStore(this.TaxonomySession); } else { termStore = this.TaxonomySession.DefaultSiteCollectionTermStore; } if (termStore != null) { this.SiteCollectionGroup = termStore.GetSiteCollectionGroup(site); } } if (monitor != null) { monitor.Dispose(); } }
protected override void OnPreRender(EventArgs e) { //To log to the developer dashboard, set up a monitored scope using (SPMonitoredScope myScope = new SPMonitoredScope("Long Procedure")) { feedbackLabel.Text = longProcedure(); } base.OnPreRender(e); }
public SPMonitoredScopeInstance(ObjectInstance prototype, SPMonitoredScope monitoredScope) : this(prototype) { if (monitoredScope == null) { throw new ArgumentNullException("monitoredScope"); } m_monitoredScope = monitoredScope; }
protected void Page_Load(object sender, EventArgs e) { using (SPMonitoredScope scope = new SPMonitoredScope(this.GetType().Name)) { Button b = new Button(); b.Text = "Click me (Embedded Web Part)!"; Controls.Add(b); using (SPMonitoredScope scopeInner = new SPMonitoredScope("Inner Scope")) { System.Threading.Thread.Sleep(500); // lengthy operation } } }
public string GetSearchResult(string messageInput) { string k = GetSearchKeyWord(messageInput); string ret = string.Empty; using (SPMonitoredScope scope = new SPMonitoredScope("MyCustomMessageHandler.GetSearchResult")) { //KeywordQuery keywordquery = new KeywordQuery(SPContext.Current.Site); //keywordquery.ResultTypes = ResultType.RelevantResults; //keywordquery.QueryText = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True"); //keywordquery.SelectProperties.Add(WeChatResult); //keywordquery.TrimDuplicates = false; //keywordquery.RowsPerPage = 0; //keywordquery.RowLimit = 10; //keywordquery.Timeout = 5000; //SearchExecutor searchexecutor = new SearchExecutor(); //2013 foundation 里面的SearchExecutor这里没有 //ResultTableCollection resulttablecollection = searchexecutor.ExecuteQuery(keywordquery); //ResultTable resulttable = resulttablecollection.Filter("TableType", KnownTableTypes.RelevantResults).FirstOrDefault(); //https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ms493601(v=office.14) SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(SPContext.Current.Site)); KeywordQuery query = new KeywordQuery(proxy); query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default; query.QueryText = string.Concat("ContentSource=", contentSourceName, " ", AppearInWeChat, "=True"); query.ResultTypes |= ResultType.RelevantResults; ResultTableCollection searchResults = query.Execute(); if (searchResults.Exists(ResultType.RelevantResults)) { ResultTable searchResult = searchResults[ResultType.RelevantResults]; DataTable result = new DataTable(); result.TableName = "Result"; result.Load(searchResult, LoadOption.OverwriteChanges); StringBuilder sb = new StringBuilder(); foreach (DataRow r in result.Rows) { sb.Append(r[WeChatResult]); sb.Append(System.Environment.NewLine); } ret = sb.ToString(); } } return(ret); }
protected override void Render(System.Web.UI.HtmlTextWriter writer) { try { using (SPMonitoredScope ClaimsScope = new SPMonitoredScope("SharePointClaims.ClaimWP")) { //Look for the claims identity. IClaimsPrincipal cp = Page.User as IClaimsPrincipal; if (cp != null) { StringBuilder claimsInfo = new StringBuilder(2048); //Get the claims identity so we can enumerate claims. IClaimsIdentity ci = (IClaimsIdentity)cp.Identity; Table tb = new Table(); TableRow tr = new TableRow(); TableCell tc = GetCell("The following claims were found in this request:"); tc.ColumnSpan = 2; tc.Font.Bold = true; tr.Cells.Add(tc); tb.Rows.Add(tr); //Enumerate all claims. foreach (Claim c in ci.Claims) { tr = new TableRow(); tr.Cells.Add(GetCell(c.ClaimType)); tr.Cells.Add(GetCell(c.Value)); tb.Rows.Add(tr); } tb.RenderControl(writer); } } } catch (Exception ex) { writer.Write("<b>There was an error rendering claims: " + ex.Message + "</b>"); } }
private static void ensureBriefingProtected(SPWeb web, SPListItem briefingItem, bool isProtected) { using (var scope = new SPMonitoredScope("Ensure briefing is protected", TraceSeverity.Verbose, new SPSqlQueryCounter())) { if (isProtected) { if (!briefingItem.HasUniqueRoleAssignments) { web.AllowUnsafeUpdates = true; secureItem(web, briefingItem); secureFolder(web, briefingItem.Folder); } } else if (briefingItem.HasUniqueRoleAssignments) { web.AllowUnsafeUpdates = true; inheritItemPermissions(briefingItem); inheritFolderPermissions(briefingItem.Folder); } } }
protected void Page_Load(object sender, EventArgs e) { using (SPMonitoredScope m = new SPMonitoredScope("LoginForm1.Page_Load", 5000)) { string returnurl = System.Web.HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString["ReturnUrl"]); string absoluteReturnurl = SPUtility.ConcatUrls(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToString(), returnurl); using (SPSite sitecollection = new SPSite(absoluteReturnurl)) { if (sitecollection.Features.Cast <SPFeature>().FirstOrDefault(_ => _.DefinitionId.Equals(new Guid("a72382ee-7a69-4a59-aa8d-86d47ebc5fd0"))) == null) { //no wechat public account qrUrl = SPUtility.ConcatUrls(sitecollection.ServerRelativeUrl, "/_layouts/FBA/gg100.png"); //qrUrl = returnurl.Replace("/_layouts/authenticate.aspx", "/_layouts/FBA/gg100.png"); QR.Visible = false; } else { qrUrl = SPUtility.ConcatUrls(sitecollection.ServerRelativeUrl, "/Style%20Library/wechat100.png"); //qrUrl = returnurl.Replace("/_layouts/authenticate.aspx", "/Style%20Library/wechat100.png"); QR.Visible = true; } } //QR.Text = string.Concat("start-end(mm:ss:ff): ",string.Format("{0:mm:ss:ff}", m.GetMonitor<SPExecutionTimeCounter>().StartTime), "-", string.Format("{0:mm:ss:ff}", m.GetMonitor<SPExecutionTimeCounter>().EndTime),", duration(ms):", m.GetMonitor<SPExecutionTimeCounter>().Value); // QR.Visible = true; } //string atk = AccessTokenContainer.TryGetToken("wxee56a98aeb2690f4", "7f9dd19106d03102a57a4e05ede14f4d"); //if (string.IsNullOrEmpty(atk)) //{ // throw new Exception("Empty weixin AccessToken"); //} //int scenId = (new Guid()).GetHashCode(); //CreateQrCodeResult qr = QrCodeApi.Create(atk, 600, scenId); //WeixinQr.ImageUrl = QrCodeApi.GetShowQrCodeUrl(qr.ticket); }
public SPMonitoredScopeInstance BeginMonitoredScope(string name) { var monitoredScope = new SPMonitoredScope(name, 11000, new SPExecutionTimeCounter(), new SPCriticalTraceCounter()); return(new SPMonitoredScopeInstance(Engine.Object.Prototype, monitoredScope)); }
public void ProcessRequest(HttpContext context) { using (SPMonitoredScope m = new SPMonitoredScope("Weixin.ProcessRequest", 5000)) { MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, string.Concat(context.Request.HttpMethod, ":", context.Request.RawUrl)); string signature = context.Request["signature"]; string timestamp = context.Request["timestamp"]; string nonce = context.Request["nonce"]; string echostr = context.Request["echostr"]; string servicetoken = WeChatServiceToken; if (context.Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, servicetoken)) { context.Response.Output.Write(echostr); //返回随机字符串则表示验证通过 } else { string err = "failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, servicetoken) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"; context.Response.Output.Write(err); MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, err); } context.Response.End(); } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, servicetoken)) { string err = "参数错误!"; context.Response.Output.Write(err); MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, err); return; } //post method - 当有用户想公众账号发送消息时触发 var postModel = new PostModel() { Signature = context.Request.QueryString["signature"], Msg_Signature = context.Request.QueryString["msg_signature"], Timestamp = context.Request.QueryString["timestamp"], Nonce = context.Request.QueryString["nonce"], //以下保密信息不会(不应该)在网络上传播,请注意 //Token = Token, Token = servicetoken, EncodingAESKey = WeChatServiceEncodingAESKey,//根据自己后台的设置保持一致 //AppId = "wxee56a98aeb2690f4"//根据自己后台的设置保持一致 AppId = WeChatServiceAppID, }; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new MyCustomMessageHandler(context.Request.InputStream, postModel, maxRecordCount, context); try { messageHandler.OmitRepeatedMessage = true; //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 //messageHandler.RequestDocument.Save( // context.Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + // messageHandler.RequestMessage.FromUserName + ".txt")); string reqmsg = string.Concat(messageHandler.RequestMessage.FromUserName, "@@@@", messageHandler.RequestDocument.ToString()); MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Medium, string.Concat("RequestDoc:", reqmsg)); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 //messageHandler.ResponseDocument.Save( // context.Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + // messageHandler.ResponseMessage.ToUserName + ".txt")); if (messageHandler.ResponseMessage != null && messageHandler.SPFBAUser.Debug) { string debug = string.Concat("start-end(mm:ss:fff): ", string.Format("{0:mm:ss:fff}", m.GetMonitor <SPExecutionTimeCounter>().StartTime), "-", string.Format("{0:mm:ss:fff}", m.GetMonitor <SPExecutionTimeCounter>().EndTime), ", duration(ms):", Math.Round(Double.Parse(m.GetMonitor <SPExecutionTimeCounter>().Value.ToString())), System.Environment.NewLine, (messageHandler.SPFBAUserName.Equals("233173287") ? MyCustomMessageHandler.MessageLink("WOL", "20", "唤醒开发机") : string.Empty)); (messageHandler.ResponseMessage as ResponseMessageText).Content += string.Concat(System.Environment.NewLine, debug); } //if (messageHandler.ResponseDocument != null) context.Response.Output.Write(messageHandler.ResponseDocument.ToString()); if (messageHandler.ResponseDocument != null) { context.Response.Output.Write(messageHandler.FinalResponseDocument.ToString()); } return; } catch (Exception ex) { MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, string.Concat(ex.Message, ex.StackTrace)); if (ex.InnerException != null) { MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, string.Concat("InnerException:", ex.InnerException.Message, ex.InnerException.StackTrace)); } if (messageHandler.ResponseDocument != null) { MyFBADiagnosticsService.Local.WriteTrace(0, MyFBADiagnosticsService.FBADiagnosticsCategory.Weixin, Microsoft.SharePoint.Administration.TraceSeverity.Unexpected, string.Concat("RespondDoc:", messageHandler.ResponseDocument.ToString())); } } finally { context.Response.End(); } } } }
private static IContainer ScanGacForAutofacModulesAndCreateContainer(string appRootNamespace, Func<string, bool> assemblyFileNameMatchingPredicate) { SPMonitoredScope monitor = null; try { monitor = new SPMonitoredScope("Dynamite - Bootstrapping dependency injection container " + appRootNamespace + " and scanning GAC for Modules."); } catch (TypeInitializationException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } catch (NullReferenceException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } var containerBuilderForDynamiteComponents = new ContainerBuilder(); // Don't just scan the GAC modules, also prepare the Dynamite core utils (by passing the params in ourselves). // I.E. each container gets its own DynamiteRegistrationModule components. var dynamiteModule = new AutofacDynamiteRegistrationModule(appRootNamespace); containerBuilderForDynamiteComponents.RegisterModule(dynamiteModule); var matchingAssemblies = GacAssemblyLocator.GetAssemblies(new List<string> { AssemblyFolder }, assemblyFileNameMatchingPredicate); // Make sure we exclude all other GSoft.Dynamite DLLs (i.e. ignore other versions deployed to same GAC) // so that other AutofacDynamiteRegistrationModule instances don't get registered. var filteredMatchingAssemblies = matchingAssemblies.Where(x => !x.FullName.Contains("GSoft.Dynamite,")); // Now make sure all Dynamite component modules (i.e. all DLLs that start with GSoft.Dynamite.*) are registered BEFORE // any other modules. // This ensures that "client" modules will be able to override the Container registrations of GSoft.Dynamite.Components modules. var dynamiteComponentModuleAssemblies = filteredMatchingAssemblies.Where(assembly => assembly.FullName.StartsWith("GSoft.Dynamite.", StringComparison.OrdinalIgnoreCase)); var allTheRest = filteredMatchingAssemblies.Where(assembly => !assembly.FullName.StartsWith("GSoft.Dynamite.", StringComparison.OrdinalIgnoreCase)); // 1) Build the base container with only Dynamite-related components containerBuilderForDynamiteComponents.RegisterAssemblyModules(dynamiteComponentModuleAssemblies.ToArray()); var container = containerBuilderForDynamiteComponents.Build(); var logger = container.Resolve<ILogger>(); string dynamiteAssemblyNameEnumeration = string.Empty; dynamiteComponentModuleAssemblies.Cast<Assembly>().ToList().ForEach(a => dynamiteAssemblyNameEnumeration += a.FullName + ", "); logger.Info("Dependency injection module registration for container " + appRootNamespace + ". The following Dynamite component assemblies were scanned and any Autofac Module within was registered. The order of registrations was: " + dynamiteAssemblyNameEnumeration); // 2) Extend the original registrations with any remaining AddOns' registrations var containerBuilderForAddOns = new ContainerBuilder(); containerBuilderForAddOns.RegisterAssemblyModules(allTheRest.ToArray()); containerBuilderForAddOns.Update(container); string addOnAssemblyNameEnumeration = string.Empty; allTheRest.Cast<Assembly>().ToList().ForEach(a => addOnAssemblyNameEnumeration += a.FullName + ", "); logger.Info("Dependency injection module registration for container " + appRootNamespace + ". The following Add-On component assemblies (i.e. extensions to the core Dynamite components) were scanned and any Autofac Module within was registered. The order of registrations was: " + addOnAssemblyNameEnumeration); // Log the full component registry for easy debugging through ULS string componentRegistryAsString = string.Empty; var regAndServices = container.ComponentRegistry.Registrations.SelectMany(r => r.Services.OfType<IServiceWithType>(), (r, s) => new { r, s }); regAndServices.ToList().ForEach(regAndService => componentRegistryAsString += "[" + regAndService.s.ServiceType.FullName + "->" + regAndService.r.Activator.LimitType.FullName + "], "); logger.Info("Autofac component registry details for container " + appRootNamespace + ": " + componentRegistryAsString); if (monitor != null) { monitor.Dispose(); } return container; }
protected void AuthenticateEventHandler(object sender, AuthenticateEventArgs formAuthenticateEventArgs) { if (sender == null) { throw new ArgumentNullException("sender"); } if (formAuthenticateEventArgs == null) { throw new ArgumentNullException("formAuthenticateEventArgs"); } bool flag = false; Login login = sender as Login; SecurityToken securityToken = null; if (login == null) { throw new ArgumentException(null, "sender"); } using (SPMonitoredScope sPMonitoredScope = new SPMonitoredScope("ZimbraSignInPage.AuthenticateEventHandler: Retrieve security token and establish session.")) { securityToken = this.GetSecurityToken(login); if (securityToken != null) { try { this.EstablishSessionWithToken(securityToken, this.GetSessionTokenWriteType(login)); this.ExecuteRegisteredAsyncTasks(); flag = true; } catch { flag = false; } try { SPFederationAuthenticationModule federationAuthenticationModule = FederatedAuthentication.WSFederationAuthenticationModule as SPFederationAuthenticationModule; federationAuthenticationModule.SetPrincipalAndWriteSessionToken(securityToken, this.GetSessionTokenWriteType(login)); } catch (Exception ex) { ProviderLogging.LogError(ex); } } else { flag = false; } } formAuthenticateEventArgs.Authenticated = flag; if (flag) { EnsureVisitor(securityToken as GenericXmlSecurityToken); /* * try * { * Guid id = SPContext.Current.Site.ID; * SPSecurity.RunWithElevatedPrivileges(delegate() * { * using (SPWeb elevatedWeb = new SPSite(id).OpenWeb()) * { * elevatedWeb.AllowUnsafeUpdates = true; * * GenericXmlSecurityToken xmlToken = securityToken as GenericXmlSecurityToken; * XmlDocument xmlDoc = new XmlDocument(); * xmlDoc.LoadXml(xmlToken.TokenXml.OuterXml); * XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); * nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion"); * //string userid = xmlDoc.SelectSingleNode("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr).InnerText; * //string userlogonname = xmlDoc.SelectSingleNode("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr).InnerText; * //string emailaddress = xmlDoc.SelectSingleNode("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='emailaddress']/saml:AttributeValue", nsmgr).InnerText; * string name = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='name']/saml:AttributeValue", nsmgr)[1].InnerText; * string userlogonname = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr)[1].InnerText; * string userid = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr)[1].InnerText; * SPUser spUser = elevatedWeb.EnsureUser(name); * elevatedWeb.Update(); * elevatedWeb.AllowUnsafeUpdates = false; * } * }); * * } * catch (Exception ex) * { * ProviderLogging.LogError(ex); * } */ this.RedirectToSuccessUrl(); } }
private static IContainer ScanGacForAutofacModulesAndCreateContainer(string appRootNamespace, Func <string, bool> assemblyFileNameMatchingPredicate) { SPMonitoredScope monitor = null; try { monitor = new SPMonitoredScope("Dynamite - Bootstrapping dependency injection container " + appRootNamespace + " and scanning GAC for Modules."); } catch (TypeInitializationException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } catch (NullReferenceException) { // Failed to initialize local diagnostics service. Fail to log monitor trace. } var containerBuilderForDynamiteComponents = new ContainerBuilder(); // Don't just scan the GAC modules, also prepare the Dynamite core utils (by passing the params in ourselves). // I.E. each container gets its own DynamiteRegistrationModule components. var dynamiteModule = new AutofacDynamiteRegistrationModule(appRootNamespace); containerBuilderForDynamiteComponents.RegisterModule(dynamiteModule); var matchingAssemblies = GacAssemblyLocator.GetAssemblies(new List <string> { AssemblyFolder }, assemblyFileNameMatchingPredicate); // Make sure we exclude all other GSoft.Dynamite DLLs (i.e. ignore other versions deployed to same GAC) // so that other AutofacDynamiteRegistrationModule instances don't get registered. var filteredMatchingAssemblies = matchingAssemblies.Where(x => !x.FullName.Contains("GSoft.Dynamite,")); // Now make sure all Dynamite component modules (i.e. all DLLs that start with GSoft.Dynamite.*) are registered BEFORE // any other modules. // This ensures that "client" modules will be able to override the Container registrations of GSoft.Dynamite.Components modules. var dynamiteComponentModuleAssemblies = filteredMatchingAssemblies.Where(assembly => assembly.FullName.StartsWith("GSoft.Dynamite.", StringComparison.OrdinalIgnoreCase)); var allTheRest = filteredMatchingAssemblies.Where(assembly => !assembly.FullName.StartsWith("GSoft.Dynamite.", StringComparison.OrdinalIgnoreCase)); // 1) Build the base container with only Dynamite-related components containerBuilderForDynamiteComponents.RegisterAssemblyModules(dynamiteComponentModuleAssemblies.ToArray()); var container = containerBuilderForDynamiteComponents.Build(); var logger = container.Resolve <ILogger>(); string dynamiteAssemblyNameEnumeration = string.Empty; dynamiteComponentModuleAssemblies.Cast <Assembly>().ToList().ForEach(a => dynamiteAssemblyNameEnumeration += a.FullName + ", "); logger.Info("Dependency injection module registration for container " + appRootNamespace + ". The following Dynamite component assemblies were scanned and any Autofac Module within was registered. The order of registrations was: " + dynamiteAssemblyNameEnumeration); // 2) Extend the original registrations with any remaining AddOns' registrations var containerBuilderForAddOns = new ContainerBuilder(); containerBuilderForAddOns.RegisterAssemblyModules(allTheRest.ToArray()); containerBuilderForAddOns.Update(container); string addOnAssemblyNameEnumeration = string.Empty; allTheRest.Cast <Assembly>().ToList().ForEach(a => addOnAssemblyNameEnumeration += a.FullName + ", "); logger.Info("Dependency injection module registration for container " + appRootNamespace + ". The following Add-On component assemblies (i.e. extensions to the core Dynamite components) were scanned and any Autofac Module within was registered. The order of registrations was: " + addOnAssemblyNameEnumeration); // Log the full component registry for easy debugging through ULS string componentRegistryAsString = string.Empty; var regAndServices = container.ComponentRegistry.Registrations.SelectMany(r => r.Services.OfType <IServiceWithType>(), (r, s) => new { r, s }); regAndServices.ToList().ForEach(regAndService => componentRegistryAsString += "[" + regAndService.s.ServiceType.FullName + "->" + regAndService.r.Activator.LimitType.FullName + "], "); logger.Info("Autofac component registry details for container " + appRootNamespace + ": " + componentRegistryAsString); if (monitor != null) { monitor.Dispose(); } return(container); }