I am using Enterprise library 4.1 logging. I am getting compile error at 'EnterpriseLibraryContainer'. EnterpriseLibraryContainer doesn't work for 4.1 version?
public LogWriter defaultWriter;
public Logging()
{
// Resolve the default LogWriter object from the container.
// The actual concrete type is determined by the configuration settings.
defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
}
[Description("Logging to EverViewer and RollingFile with Write method of a LogWriter")]
public void LogWriter(string message, string title, EventLogEntryType eventType)
{
// Check if logging is enabled before creating log entries.
if (defaultWriter.IsLoggingEnabled())
{
// Create a string array (or List<>) containing the categories.
string[] logCategories = new string[] { "General" };
LogEntry logEntry = new LogEntry();
logEntry.Message = message;
logEntry.Categories = logCategories;
logEntry.Priority = 10;
logEntry.EventId = 9005;
logEntry.Severity = ConvertEventType(eventType);
logEntry.Title = title;
defaultWriter.Write(logEntry);
}
}
EnterpriseLibraryContainer was introduced with Enterprise Library 5 so is not available with Enterprise Library 4.1.
Try replacing that code with the following to get the default writer:
public Logging()
{
// Resolve the default LogWriter object from the container.
// The actual concrete type is determined by the configuration settings.
defaultWriter = new LogWriterFactory().Create();
}
Are you by any chance targeting the .NET 4 Client Profile instead of the full .NET 4?
Related
I'm using ASP.NET Core 6 and have a reference to App Metrics.
With the following code, I'm adding a new counter-metrics on the API and it is working properly when I'm looking at /metrics-text endpoint.
public static class MetricsRegistry
{
public static CounterOptions SampleValue => new CounterOptions
{
Name = "SampleValue",
Context = "Application",
MeasurementUnit = Unit.Requests
};
}
Then the increment the Metrics:
_metrics.Measure.Counter.Increment(MetricsRegistry.SampleValue);
But I would to have access to that metrics on runtime. I tried to use Snapshot but it is not working.
var value = _metrics.Snapshot.GetCounterValue("Application", MetricsRegistry.SampleValue.Name);
Is there any way to get the value on runtime?
Microsoft Dynamics CRM 2015.
I test Asp.Net Core controller's action. When I create new Lead record some plugin generates new Guid for lead.new_master_id field (it's type is string). Therefore after creating I retrive the record to get it's generated new_master_id value. How can I emulate this plugin behaviour through Fake Xrm Easy?
var fakedContext = new XrmFakedContext();
fakedContext.ProxyTypesAssembly = typeof(Lead).Assembly;
var entities = new Entity[]
{
// is empty array
};
fakedContext.Initialize(entities);
var orgService = fakedContext.GetOrganizationService();
var lead = new Lead { FirstName = "James", LastName = "Bond" };
var leadId = orgService.Create(lead);
var masterId = orgService.Retrieve(Lead.EntityLogicalName, leadId,
new Microsoft.Xrm.Sdk.Query.ColumnSet(Lead.Fields.new_master_id))
.ToEntity<Lead>().new_master_id;
In v1.x of FakeXrmEasy you'll need to enable PipelineSimulation and register the plugin steps you would like to be fired on Create manually by registering their steps.
fakedContext.UsePipelineSimulation = true;
Once enabled, you'll need to enable the necessary steps via calling RegisterPluginStep. In your example you'll need to at least register something along the lines of:
fakedContext.RegisterPluginStep<LeadPlugin>("Create", ProcessingStepStage.Preoperation);
Where LeadPlugin would be the name of your plugin that generates the new_master_id property.
Keep in mind v1.x is limited in that it supports pipeline simulation for basic CRUD requests only.
Later versions (2.x and/or 3.x) come with a brand new middleware implementation allowing registering plugin steps for any message. Soon we'll be implementing automatic registration of plugin steps based on an actual environment and/or custom attributes.
Here's an example using the new middleware
public class FakeXrmEasyTestsBase
{
protected readonly IXrmFakedContext _context;
protected readonly IOrganizationServiceAsync2 _service;
public FakeXrmEasyTestsBase()
{
_context = MiddlewareBuilder
.New()
.AddCrud()
.AddFakeMessageExecutors()
.AddPipelineSimulation()
.UsePipelineSimulation()
.UseCrud()
.UseMessages()
.Build();
_service = _context.GetAsyncOrganizationService2();
}
}
You can find more info on the QuickStart guide here
Disclaimer: I'm the author of FakeXrmEasy :)
I am trying to enable sampling with my AppInsightsHelper class which starts Depedancy operations to track performance.
This is how I am initializing my TelematryClient:
public ApplicationInsightsHelper(string key)
{
var config = TelemetryConfiguration.CreateDefault();
config.InstrumentationKey = key;
config.DefaultTelemetrySink.TelemetryProcessorChainBuilder.UseAdaptiveSampling(maxTelemetryItemsPerSecond: 1);
_telemetryClient = new TelemetryClient(config);
}
and then Starting and Stopping the operation:
IOperationHolder<DependencyTelemetry> operation = null;
operation = _telemetryClient.StartOperation<DependencyTelemetry>(friendlyName);
operation.Telemetry.Name = friendlyName;
operation.Telemetry.Type = type;
operation.Telemetry.Timestamp = DateTime.UtcNow;
operation.Telemetry.Duration = DateTime.UtcNow - operation.Telemetry.Timestamp;
_telemetryClient.StopOperation(operation);
The issue is that the above code seems to ignore the Sampling setting and all operations are traced. I have also included : excludedTypes: "Dependency" within the UseAdaptiveSampling to see if anything happens and as expected the Dependencies are not ignored.
If it's an azure function, you can set sampling via host.json, see here and here for details. An example as below:
{
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"maxTelemetryItemsPerSecond" : 1
}
}
}
}
And if you want to use TelemetryClient with the settings, you should follow this article. In the constructor of the azure function, use code like below:
/// Using dependency injection will guarantee that you use the same configuration for telemetry collected automatically and manually.
public HttpTrigger2(TelemetryConfiguration telemetryConfiguration)
{
this.telemetryClient = new TelemetryClient(telemetryConfiguration);
}
But as of now, there is an issue by using telemetryConfiguration.
This has been worked for me for ASP.NET web application. I have added below configuration and specifically added my 'MaksingTelemetryInitializer'.
public void StartApplicationInsights(string logType)
{
string appInsightsComponentId = string.Empty;
try
{
telemetryClient = new TelemetryClient();
TelemetryConfiguration.Active.InstrumentationKey = GetConfigvalue("AppInsightsAppId"); ;
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MaskingTelemetryInitializer());
}
catch (Exception exception)
{
// Log Exception to WadLog if logging to Wadlog is enabled
if (logType != LoggingType.Both) return;
WadLogWriter.LogToWadLogs(Logger.BuildErrorString(exception), EventLevel.Error);
}
}
Here I wanted mask PII data email id, it is working.
I have an application that manage IIS Application instances so I am looking for a kind of GIUD to identify each applications. This GUID must be created when the application is deployed in IIS and must be persistent to IIS/Windows updates/restarts.
I did not need the use of Microsoft.Web.Administration: I want a simple way, for each IIS application, it returns its unique ID (by a method called within it).
Here is an example of what I'm looking for and I'd like to have an unique id returned by this.????? :
public class MvcApplication : System.Web.HttpApplication
{
string myUniqueID {
get { return this.?????; }
}
}
Thanks for help.
HostingEnvironment.ApplicationID
https://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationid(v=vs.110).aspx
I had to do something similar.
Read the web.config file for a HostId setting. Preferably split your configuration file into two, with one config file that is local to the install, and doesn't get replaced upon upgrading to a new version of the website.
If the HostId value doesn't exist in the web.config, call Guid.NewGuid() to generate a new value.
Save the new value to the web config, preferably in the local section/file.
Return the value.
Here is some psuedo-code:
public Guid HostId
{
get
{
var result = GetSetting(ConfigFileLocalSettingList.HostId).TryToGuid();
if (result == null)
{
result = Guid.NewGuid();
SetSetting(ConfigFileLocalSettingList.HostId, result.ToString());
Save();
}
return result.Value;
}
}
You can use the assembly GUID for this purpose: In AssemblyInfo.cs, you can find
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("307E39B9-2C41-40CF-B29F-84C8BBCD6519")]
To read this value, you can use:
public static string AssemblyGUID
{
get {
var assembly = Assembly.GetExecutingAssembly();
var attribute = (System.Runtime.InteropServices.GuidAttribute)assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), true)[0];
var GUID = attribute.Value;
return GUID;
}
}
which is taken from another SO answer (you can find it here).
And if it is required, Visual Studio allows you to create a new GUID via menu Tools -> Create GUID - if you need a different one.
Or in C# you simply use
var newGuid=(Guid.NewGuid()).ToString();
Console.WriteLine(newGuid);
to create a new GUID.
I'm using fluent migrator to manage my database migrations, but what I'd like to do is have the migrations run at app start. The closest I have managed is this:
public static void MigrateToLatest(string connectionString)
{
using (var announcer = new TextWriterAnnouncer(Console.Out)
{
ShowElapsedTime = true,
ShowSql = true
})
{
var assembly = typeof(Runner).Assembly.GetName().Name;
var migrationContext = new RunnerContext(announcer)
{
Connection = connectionString,
Database = "SqlServer2008",
Target = assembly
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
}
I'm sure I had this working, but I've not looked at it for sometime (hobby project) and it's now throwing null reference exceptions when it gets to the Execute line. Sadly there are no docs for this and I've been banging my head on it for ages.
Has anyone managed to get this kind of thing working with FluentMigrator?
PM> Install-Package FluentMigrator.Tools
Manually add a reference to:
packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.
public static class Runner
{
public class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public string ProviderSwitches { get; set; }
public int Timeout { get; set; }
}
public static void MigrateToLatest(string connectionString)
{
// var announcer = new NullAnnouncer();
var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
var assembly = Assembly.GetExecutingAssembly();
var migrationContext = new RunnerContext(announcer)
{
Namespace = "MyApp.Sql.Migrations"
};
var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
var factory =
new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
using (var processor = factory.Create(connectionString, announcer, options))
{
var runner = new MigrationRunner(assembly, migrationContext, processor);
runner.MigrateUp(true);
}
}
}
Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.
I have actually accomplished running migrations in the application_start however it is hard to tell from that code what could be wrong... Since it is open source I would just grab the code and pull it into your solution and build it to find out what the Execute method is complaining about. I found that the source code for Fluent Migrator is organized pretty well.
One thing that you might have to be concerned about if this is a web app is making sure that no one uses the database while you are migrating. I used a strategy of establishing a connection, setting the database to single user mode, running the migrations, setting the database to multi user mode, then closing the connection. This also handles the scenario of a load balanced web application on multiple servers so 2 servers don't try to run migrations against the same database.