AppMetrics how to set application name? - c#

I implemented App.Metrics into my wcf application (App.Metrics ver 3.1.0).
When I check url in which data is uploaded I found that app isn't filled:
Tried to figured out reason of this behavior I found manual:
https://www.app-metrics.io/getting-started/fundamentals/tagging-organizing/
It said that AssemblyName needs to be filled, but I double-checked it - csproj file contain next row:
<AssemblyName>MyWebService</AssemblyName>
How can I fill this app property in metrics?

startup.cs:
var metrics = MetricsProvider.Instance.Metrics;
SetMetricsAppTag(metrics, Assembly.GetExecutingAssembly().GetName().Name);
private static void SetMetricsAppTag(IMetricsRoot metricsRoot, string appTagValue)
{
if (!metricsRoot.Options.GlobalTags.ContainsKey("app"))
{
metricsRoot.Options.GlobalTags.Add("app", appTagValue);
}
else if (string.IsNullOrEmpty(metricsRoot.Options.GlobalTags["app"]) || metricsRoot.Options.GlobalTags["app"] == "unknown")
{
metricsRoot.Options.GlobalTags["app"] = appTagValue;
}
}

a better way will be to do in startup-
var metrics = AppMetrics.CreateDefaultBuilder().
Configuration.
Configure(options => options.AddAppTag(appName: "nexus"))
.Build();
services.AddMetrics(metrics);
services.AddMetricsTrackingMiddleware();
services.AddMetricsEndpoints(opt =>
{
opt.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter();
opt.MetricsEndpointOutputFormatter = new MetricsPrometheusProtobufOutputFormatter();
opt.EnvironmentInfoEndpointEnabled = false;
});

Related

Swashbuckle swagger.json larger than 4 mb net core

My api endpoint have grown too large and I need to minimize it or divide it to multiple swagger.json files.
I want to upload the swagger.json file to power automate but there are two rules. Max 4 Mb and Max 256 functions per file. I don´t meet these requirement.
I want to have a swagger file per controller/group this will minimize number of functions and decrease the size of file.
But I don't know how to configure(Swashbuckle) or should I do it with documentFilters?
I already use ApiVersioning to decrease a littel bit of functions and size, but it is not enough. And I can´t chnage the complete url endpoint. I just want multiple files more than just versions.
There are two options to make this possible. But I want to make it without changing any urls to the existing api.
In each controller you can add set the Apiversion [ApiVersion("2.0")] and then set the controllername i.e [ApiVersion("2.0.order")]. And there will be a version for each controller.
This solution will change the urls and are not approachable for an existing api.
Another solution is to create tags for each operation with a filter and now we can create a filter for each endpoint
public class ApplySwaggerOperationTags : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var tag = new OpenApiTag();
context.ApiDescription.ActionDescriptor.RouteValues.TryGetValue("controller",out string tagname);
tag.Name = tagname;
operation.Tags.Add(tag);
var tagGroupName = new OpenApiTag();
tagGroupName.Name = context.ApiDescription.GroupName;
operation.Tags.Add(tagGroupName);
}
}
And then apply a document filter
public class SwaggerDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// Key is read-only so make a copy of the Paths property
var pathsFiltered = new OpenApiPaths();
var array = context.DocumentName.Split("-");
string version = array[0];
string tag = string.Empty;
if (array.Count() > 1)
{
tag = array[1];
}
foreach (var path in swaggerDoc.Paths)
{
if (path.Value.Operations.Values.First().Tags.FirstOrDefault(c => c.Name == version) != null)
{
if (path.Value.Operations.Values.First().Tags.FirstOrDefault(c => c.Name.ToLower() == tag.ToLower()) != null ||
tag == string.Empty)
{
// Add the path to the filtered collection
pathsFiltered.Add(path.Key, path.Value);
}
}
}
swaggerDoc.Paths = pathsFiltered;
}
}
The key is to have c.SwaggerEndpoint(in UseSwaggerUI) and options.SwaggerDoc(in SwaggerGenOptions) that match
And a good example to check is https://github.com/cbruen1/SwaggerFilter.
Hope this helps anyone.

Unable to open App Store from app programmatically

I had been trying to open/navigate App Store from my application when there is a version upgrade.
For that I have written customrender which works perfectly fine for android. But it's not working for iOS. Following is the code written for iOS customrenderer. I attached the screenshot of the code in an attachment.
public class OpenAppStore : UIViewController, ISKStoreProductViewControllerDelegate, IOpenStore
{
public void OpenStore()
{
bool isSimulator = Runtime.Arch == Arch.SIMULATOR;
if (!isSimulator)
{
var storeViewController = new SKStoreProductViewController();
storeViewController.Delegate = this;
var id = SKStoreProductParameterKey.ITunesItemIdentifier;
var productDictionaryKeys = new NSDictionary("SKStoreProductParameterITunesItemIdentifier", 1389696261);
var parameters = new StoreProductParameters(productDictionaryKeys);
storeViewController.LoadProduct(parameters, (bool loaded, NSError error) =>
{
if ((error == null) && loaded)
{
this.PresentViewController(storeViewController, true, () =>
{
Console.WriteLine("SKStoreProductViewController Completed");
});
}
if (error != null)
{
throw new NSErrorException(error);
}
});
}
else
{
var itunesLink = new NSUrl("https://itunes.apple.com/us/genre/ios/id36?mt=8");
UIApplication.SharedApplication.OpenUrl(itunesLink, new NSDictionary() { }, null);
}
}
}
Problem : It doesn't throw any error. PresentViewController is called but it doesn't navigate/open my app in the App Store.
Thank you
Firstly, you don't need a custom renderer for this. You should inject a simple helper class that will open the appropriate app store for each platform you support.
Secondly, the url you are using for the iOS App Store looks to be incorrect. Use something like:
var url = new NSUrl($"https://itunes.apple.com/us/app/apple-store/{myAppId}?mt=8");
The app store URL used above is from the Apple docs. You can then open that url.

Properties.Settings.Default.variableName = textboxt.Text

private void Enable(TextBox temp, String system)
{
if (File.Exists(temp.Text))
{
Properties.Settings.Default.system = temp.Text;
}
else
do something here;
}
Basically I'm trying to take a text box with some file path, check if it exists, if exists set the value of the Properties.Settings.Default.system to temp.text.
However I don't know how to use a variable name to reference the existing settings property.
Fairly new to this so any help is appreciated.
Thanks!
Credit to Mike Debela for the answer.... But if ran into a situation where you don't know the system, this code will help prevent some errors.
private void Enable(TextBox Temp, string system)
{
// check that the property even exists
bool propertyExists = Properties.Settings.Default.Properties.Cast<SettingsProperty>().Any(p => p.Name == system);
if (propertyExists)
{
Properties.Settings.Default[system] = Temp.Text;
}
else
{
// create a new property
var p = new SettingsProperty(system);
p.PropertyType = typeof(string);
p.DefaultValue = Temp.Text;
Properties.Settings.Default.Properties.Add(p);
}
Properties.Settings.Default.Save();
}

Get access to the URL's being used in System.Web.Optimization

Background: I'm using the HTML 5 Offline App Cache and dynamically building the manifest file. Basically, the manifest file needs to list each of the static files that your page will request. Works great when the files are actually static, but I'm using Bundling and Minification in System.Web.Optimization, so my files are not static.
When in the DEBUG symbol is loaded (i.e. debugging in VS) then the actual physical files are called from the MVC View. However, when in Release mode, it calls a virtual file that could look something like this: /bundles/scripts/jquery?v=FVs3ACwOLIVInrAl5sdzR2jrCDmVOWFbZMY6g6Q0ulE1
So my question: How can I get that URL in the code to add it to the offline app manifest?
I've tried:
var paths = new List<string>()
{
"~/bundles/styles/common",
"~/bundles/styles/common1024",
"~/bundles/styles/common768",
"~/bundles/styles/common480",
"~/bundles/styles/frontend",
"~/bundles/scripts/jquery",
"~/bundles/scripts/common",
"~/bundles/scripts/frontend"
};
var bundleTable = BundleTable.Bundles;
foreach (var bundle in bundleTable.Where(b => paths.Contains(b.Path)))
{
var bundleContext = new BundleContext(this.HttpContext, bundleTable, bundle.Path);
IEnumerable<BundleFile> files = bundle.GenerateBundleResponse(bundleContext).Files;
foreach (var file in files)
{
var filePath = file.IncludedVirtualPath.TrimStart(new[] { '~' });
sb.AppendFormat(formatFullDomain, filePath);
}
}
As well as replacing GenerateBundleResponse() with EnumerateFiles(), but it just always returns the original file paths.
I'm open to alternative implementation suggestions as well. Thanks.
UPDATE: (7/7/14 13:45)
As well as the answer below I also added this Bundles Registry class to keep a list of the required static files so that it works in debug mode in all browsers. (See comments below)
public class Registry
{
public bool Debug = false;
public Registry()
{
SetDebug();
}
[Conditional("DEBUG")]
private void SetDebug()
{
Debug = true;
}
public IEnumerable<string> CommonScripts
{
get
{
if (Debug)
{
return new string[]{
"/scripts/common/jquery.validate.js",
"/scripts/common/jquery.validate.unobtrusive.js",
"/scripts/common/knockout-3.1.0.debug.js",
"/scripts/common/jquery.timepicker.js",
"/scripts/common/datepicker.js",
"/scripts/common/utils.js",
"/scripts/common/jquery.minicolors.js",
"/scripts/common/chosen.jquery.custom.js"
};
}
else
{
return new string[]{
"/scripts/common/commonbundle.js"
};
}
}
}
}
I'm by no means happy with this solution. Please make suggestions if you can improve on this.
I can suggest an alternative from this blog post create your own token.
In summary the author suggests using web essentials to create the bundled file and then creating a razor helper to generate the token, in this case based on the last changed date and time.
public static class StaticFile
{
public static string Version(string rootRelativePath)
{
if (HttpRuntime.Cache[rootRelativePath] == null)
{
var absolutePath = HostingEnvironment.MapPath(rootRelativePath);
var lastChangedDateTime = File.GetLastWriteTime(absolutePath);
if (rootRelativePath.StartsWith("~"))
{
rootRelativePath = rootRelativePath.Substring(1);
}
var versionedUrl = rootRelativePath + "?v=" + lastChangedDateTime.Ticks;
HttpRuntime.Cache.Insert(rootRelativePath, versionedUrl, new CacheDependency(absolutePath));
}
return HttpRuntime.Cache[rootRelativePath] as string;
}
}
Then you can reference the bundled file like so...
#section scripts {
<script src="#StaticFile.Version("~/Scripts/app/myAppBundle.min.js")"></script>}
Then you have control of the token and can do what you want with it.

Get current ClickOnce's application publisher name?

Is it possible to read the publisher name of the currently running ClickOnce application (the one you set at Project Properties -> Publish -> Options -> Publisher name in Visual Studio)?
The reason why I need it is to run another instance of the currently running application as described in this article and pass parameters to it.
Of course I do know my application's publisher name, but if I hard code it and later on I decide to change my publisher's name I will most likely forget to update this piece of code.
Here is another option. Note that it will only get the publisher name for the currently running application, which is all I need.
I'm not sure if this is the safest way to parse the XML.
public static string GetPublisher()
{
XDocument xDocument;
using (MemoryStream memoryStream = new MemoryStream(AppDomain.CurrentDomain.ActivationContext.DeploymentManifestBytes))
using (XmlTextReader xmlTextReader = new XmlTextReader(memoryStream))
{
xDocument = XDocument.Load(xmlTextReader);
}
var description = xDocument.Root.Elements().Where(e => e.Name.LocalName == "description").First();
var publisher = description.Attributes().Where(a => a.Name.LocalName == "publisher").First();
return publisher.Value;
}
You would think this would be trivial, but I don't see anything in the framework that gives you this info.
If you want a hack, you can get the publisher from the registry.
Disclaimer - Code is ugly and untested...
...
var publisher = GetPublisher("My App Name");
...
public static string GetPublisher(string application)
{
using (var key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall"))
{
var appKey = key.GetSubKeyNames().FirstOrDefault(x => GetValue(key, x, "DisplayName") == application);
if (appKey == null) { return null; }
return GetValue(key, appKey, "Publisher");
}
}
private static string GetValue(RegistryKey key, string app, string value)
{
using (var subKey = key.OpenSubKey(app))
{
if (!subKey.GetValueNames().Contains(value)) { return null; }
return subKey.GetValue(value).ToString();
}
}
If you find a better solution, please follow-up.
I dont know about ClickOnce, but normally, you can read the assembly-info using the System.Reflection framework:
public string AssemblyCompany
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
Unfortunately, theres no "publisher" custom-attribute, just throwing this out as a possible work-around

Categories

Resources