Archive

Archive for the ‘ASP.NET’ Category

Enabling Application Insights on ANY ASP.NET website

October 22, 2017 Leave a comment

1. Install DLL via Nuget

Install-Package Microsoft.ApplicationInsights.Web

2. Add items in bold to the relevant sections in web.config

<system.web>
<httpModules>
     <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
   </httpModules>

<system.webServer>
   <modules>
     <remove name="TelemetryCorrelationHttpModule"/>
     <add name="TelemetryCorrelationHttpModule"
       type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation"
       preCondition="integratedMode,managedHandler"/>
     < remove name="ApplicationInsightsWebTracking"/>
     <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
   </modules>

<system.diagnostics>
  <trace autoflush="true" indentsize="0">
    <listeners>
      <add name="myAppInsightsListener" type="Microsoft.ApplicationInsights.TraceListener.ApplicationInsightsTraceListener, Microsoft.ApplicationInsights.TraceListener" />
    </listeners>
  </trace>
< /system.diagnostics>

3. Create an ApplicationInsights.config file in /

<?xml version="1.0" encoding="utf-8"?>
< ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
 
  < InstrumentationKey>[Your Instrumentation Key]</InstrumentationKey>
  < TelemetryInitializers>
    <Add Type="Microsoft.ApplicationInsights.DependencyCollector.HttpDependenciesParsingTelemetryInitializer, Microsoft.AI.DependencyCollector"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureWebAppRoleEnvironmentTelemetryInitializer, Microsoft.AI.WindowsServer"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.BuildInfoConfigComponentVersionTelemetryInitializer, Microsoft.AI.WindowsServer"/>
    <Add Type="Microsoft.ApplicationInsights.Web.WebTestTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.SyntheticUserAgentTelemetryInitializer, Microsoft.AI.Web">
      <!– Extended list of bots:
             search|spider|crawl|Bot|Monitor|BrowserMob|BingPreview|PagePeeker|WebThumb|URL2PNG|ZooShot|GomezA|Google SketchUp|Read Later|KTXN|KHTE|Keynote|Pingdom|AlwaysOn|zao|borg|oegp|silk|Xenu|zeal|NING|htdig|lycos|slurp|teoma|voila|yahoo|Sogou|CiBra|Nutch|Java|JNLP|Daumoa|Genieo|ichiro|larbin|pompos|Scrapy|snappy|speedy|vortex|favicon|indexer|Riddler|scooter|scraper|scrubby|WhatWeb|WinHTTP|voyager|archiver|Icarus6j|mogimogi|Netvibes|altavista|charlotte|findlinks|Retreiver|TLSProber|WordPress|wsr-agent|http client|Python-urllib|AppEngine-Google|semanticdiscovery|facebookexternalhit|web/snippet|Google-HTTP-Java-Client–>
      <Filters>search|spider|crawl|Bot|Monitor|AlwaysOn</Filters>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.Web.ClientIpHeaderTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.OperationNameTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.OperationCorrelationTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.UserTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.AuthenticatedUserIdTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.AccountIdTelemetryInitializer, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.SessionTelemetryInitializer, Microsoft.AI.Web"/>
  </TelemetryInitializers>
  < TelemetryModules>
     <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
      < ExcludeComponentCorrelationHttpHeadersOnDomains>
         <!–
        Requests to the following hostnames will not be modified by adding correlation headers.
        This is only applicable if Profiler is installed via either StatusMonitor or Azure Extension.
        Add entries here to exclude additional hostnames.
        NOTE: this configuration will be lost upon NuGet upgrade.
        –>
        <Add>core.windows.net</Add>
         <Add>core.chinacloudapi.cn</Add>
        <Add>core.cloudapi.de</Add>
        <Add>core.usgovcloudapi.net</Add>
      </ExcludeComponentCorrelationHttpHeadersOnDomains>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.PerformanceCollectorModule, Microsoft.AI.PerfCounterCollector">
      <!–
      Use the following syntax here to collect additional performance counters:
     
      <Counters>
         <Add PerformanceCounter="\Process(??APP_WIN32_PROC??)\Handle Count" ReportAs="Process handle count" />
        …
      </Counters>
     
      PerformanceCounter must be either \CategoryName(InstanceName)\CounterName or \CategoryName\CounterName
      
      NOTE: performance counters configuration will be lost upon NuGet upgrade.
     
      The following placeholders are supported as InstanceName:
        ??APP_WIN32_PROC?? – instance name of the application process  for Win32 counters.
        ??APP_W3SVC_PROC?? – instance name of the application IIS worker process for IIS/ASP.NET counters.
        ??APP_CLR_PROC?? – instance name of the application CLR process for .NET counters.
       –>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.DeveloperModeWithDebuggerAttachedTelemetryModule, Microsoft.AI.WindowsServer"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnhandledExceptionTelemetryModule, Microsoft.AI.WindowsServer"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.UnobservedExceptionTelemetryModule, Microsoft.AI.WindowsServer">
      <!–</Add>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.FirstChanceExceptionStatisticsTelemetryModule, Microsoft.AI.WindowsServer">–>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
      <Handlers>
        <!–
        Add entries here to filter out additional handlers:
       
        NOTE: handler configuration will be lost upon NuGet upgrade.
        –>
        <Add>System.Web.Handlers.TransferRequestHandler</Add>
        <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
        <Add>System.Web.StaticFileHandler</Add>
        <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
         <Add>System.Web.Optimization.BundleHandler</Add>
        <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
         <Add>System.Web.Handlers.TraceHandler</Add>
        <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
        <Add>System.Web.HttpDebugHandler</Add>
      </Handlers>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.Web.ExceptionTrackingTelemetryModule, Microsoft.AI.Web"/>
    <Add Type="Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule, Microsoft.AI.Web"/>
  </TelemetryModules>
  < TelemetryProcessors>
     <Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector"/>
    <Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights"/>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
      < MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
      < ExcludedTypes>Event</ExcludedTypes>
    </Add>
    <Add Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor, Microsoft.AI.ServerTelemetryChannel">
      <MaxTelemetryItemsPerSecond>5</MaxTelemetryItemsPerSecond>
       <IncludedTypes>Event</IncludedTypes>
    </Add>
  </TelemetryProcessors>
  < TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel"/>
< !–
    Learn more about Application Insights configuration with ApplicationInsights.config here:
    http://go.microsoft.com/fwlink/?LinkID=513840
   
    Note: If not present, please add <InstrumentationKey>Your Key</InstrumentationKey> to the top of this file.
  –></ApplicationInsights>

Advertisements
Categories: ASP.NET, Azure

Enabling CI for .net core using TFS Build

October 10, 2016 Leave a comment

At the moment there is no easy way to implement CI for .net core projects. Ideally it should be published and deployed to individual instances of nano servers, but that might be something beyond the capability of TFS Build.

Should you wish to implement CI for .net core projects on TFS 2015, here are the build steps and scripts that you need.

  1. Step 1: Install .net core
    Download https://docs.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-install-script and either place it inside TFS or else in a central location. This will install and setup the .net Core CLI Runtime for the service account that is used by the build servers
    image
  2. Step 2: Run dotnet restore and dotnet publish
    Download and modify the powershell script found at http://pastebin.com/yyjbGDW9. It assumes that each folder is an individual .net core project that needs to be published. Modify accordingly to your environment

    It is important to add in the OutputDir argument as that defines where the published project goes
    image

    As this builds all the projects, you may also want to check “Continue on error”
    image

  3. Step 3: Deploy to the servers
    You can find the script I use at http://pastebin.com/8jBHz3Zf. Important thing to note is that you need to first stop IIS on the target server before copying the files over as running net core on IIS locks the dll files
    image

.net Core RC2–EntityFramework Database First

June 1, 2016 Leave a comment

This is the updated version using RC2 for https://jefferytay.wordpress.com/2016/02/02/asp-net-vnext-entityframework-7-0-database-first-rc1/

You can refer to the full documentation at https://docs.efproject.net/en/latest/miscellaneous/configuring-dbcontext.html

Step by step guide:

  1. Starting with a blank project, add the following dependencies inside project.json

    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview1-final",

    image
    If you are upgrading from RC1, I would suggest you create a brand new project and migrate the files rather than attempt to migrate the entire project

  2. Add the following inside tools
    "Microsoft.EntityFrameworkCore.Tools": {
         "version": "1.0.0-preview1-final",
         "imports": [
           "portable-net45+win8+dnxcore50",
           "portable-net45+win8"
         ]
       }
    image
  3. ef command now no longer exists, you need to use dotnet ef

dotnet ef dbcontext scaffold -c UserDbContext -o Models -f "Data Source=.; Initial Catalog=user;User ID=user;Password=password" Microsoft.EntityFrameworkCore.SqlServer

Usage: dotnet ef dbcontext scaffold [arguments] [options]
Arguments:
  [connection]  The connection string of the database
  [provider]    The provider to use. For example, EntityFramework.MicrosoftSqlServer
Options:
  -a|–data-annotations           Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API.
  -c|–context <name>             Name of the generated DbContext class.
  -f|–force                      Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten.
  -o|–output-dir <path>          Directory of the project where the classes should be output. If omitted, the top-level project directory is used.
  –schema <schema>               Selects a schema for which to generate classes.
  -t|–table <schema.table>       Selects a table for which to generate classes.
  -e|–environment <environment>  The environment to use. If omitted, "Development" is used.
  -h|–help                       Show help information
  -v|–verbose                    Enable verbose output

Universal SMS Archiver

May 13, 2016 Leave a comment

Users who have been using Android devices will swear by SMS Backup and Restore to backup their SMS, while iOS users have iTunes backup. While these works, one issue with such software is that you generally do not want to keep or transfer all of your old SMS into the new device.

Introducing Universal SMS Archiver!

  • It is a desktop app that runs on Windows, and has the ability to automatically import your SMS from iTunes and SMS Backup and Restore files.
  • You can also manage the entire list of SMS into a current as well as archived list.
  • It has the ability to export your current sms list into Excel for further processing

image

The latest executable can be downloaded at https://onedrive.live.com/redir?resid=895931B65435BB3D!30467&authkey=!AG-VaHLPBh10qLg&ithint=file%2czip

Source code can be found at https://github.com/kwanann/Hobbies/tree/master/Universal%20SMS%20Archiver

Dependency Injection in ASPNET VNext (RC1)

February 23, 2016 Leave a comment

This article will document how to do dependency injection for vNext

1. Create the class to be injected (https://gist.github.com/kwanann/a0363add23870a949334)

image

2. Configure startup.cs (https://gist.github.com/kwanann/7bced8e22fec229bd0be)

image

There are 4 methods of adding to services

AddTransient: It will create a new instance each time it is accessed. e.g when I call it from the MVC Controller and from frontend MVC code, I will get 2 independent instances

AddScoped: It will create a new instance for the particular request, e.g when I call it from MVC Controller and frontend MVC Code, it’s the same instance. However it does not survive across different OWIN middleware

AddSingleton: Creates a single instance for all requests

AddInstance: Creates a single instance for all requests, but the constructor is left to the developer

3. If you need to call it from within the MVC Controller (https://gist.github.com/kwanann/c987314e0eecdab20a7b)

image

Inject the interface you need into the constructor and then assign it to a local variable. You may then use it however you wish

Categories: 5.0, ASP.NET, vNext

Microsoft Team Foundation Server–Undoing checkout for a workspace that no longer exists

February 2, 2016 1 comment

Every once in a while, you get a request from your developer telling you that they have reformatted their machine and unfortunately there is still one or 2 files inside that workspace that they forgot to checkout

Visual studio comes with tools that allows you to undo checkout. Unfortunately it runs from the CLI

  1. Goto the visual studio folder
    cd “C:\Program Files (x86)\Microsoft Visual Studio 14.0”
  2. List workspaces of the user
    tf workspaces /collection:http://mytfsserver:8080/tfs/defaultcollection /owner:JohnDoe

    Collection: http://mytfsserver:8080/tfs/defaultcollection
    Workspace Owner          Computer  Comment
    ——— ————– ——— ————————————————————————————
    JD-PC JohnDoe JD-PC
    JD-PC2     JohnDoe JD-PC2
    JD-PC3    JohnDoe JD-PC3

  3. Figure out which workspace contains the file to undo and fire up the undo command

    tf undo /workspace:JD-PC2;JohnDoe /s:http://mytfsserver:8080/tfs $/Path/To/The/File.cs

if it works, you will get the following reply:

The operation completed successfully.  Because the workspace JD-PC2;JohnDoe is not on this computer, you must perform a separate get operation in that workspace to update it with the changes that have been made on the server.

Selenium WebDriver – Element is not clickable at point

February 2, 2016 Leave a comment

Selenium is a fantastic tool for website automation, you simply nuget it into your .NET project and you will be able to use it to automate testing using Firefox

Nuget link: https://www.nuget.org/packages/Selenium.WebDriver

 

However, if you are upgrading from versions < 2.48 to the latest version, you will realize that a lot of your codes will suddenly throw the following error

OpenQA.Selenium.WebDriverException: Unexpected error. Element is not clickable at point (x, y). Other element would receive the click:

at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)

 

This is due to the way Selenium handles Mouse Clicks from version 2.48 onwards, version 2.50 is the currently “safer” version to use

https://github.com/SeleniumHQ/selenium/issues/1202

image

 

Of course all of these does not fix the issues you have with the code, here are some possible ways to fix them

#1: Use SendKeys

SendKeys automatically focuses to the element that it needs to send keys to, however this is restricted to input elements

e.g Element.SendKeys(Keys.Escape)

 

#2 Use MoveToElement

MoveToElement is another way to move focus to the element.

e.g new OpenQA.Selenium.Interactions.Actions(driver).MoveToElement(elem).Perform();

#3 Use Javascript

Javascript allows you to pretty much do anything

e.g. ((IJavaScriptExecutor)driver).ExecuteScript("window.scrollTo(" + elem.Location.X + "," + elem.Location.Y + ")")

 

#4 Use ScrollIntoView

ScrollIntoView is another  possible javascript that you can use

((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);