I have a mvc5 application where I want to enable both server and client side logging in application insights. Server side logging is working fine as expected but the issue is in the client side logging. In the layout page I've added the following script in "head" tag as mentioned here (https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript)
<script type="text/javascript">
!function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),l.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(k)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
instrumentationKey: "{InstrumentationKey}"
/* ...Other Configuration Options... */
}});
</script>
But the issue is it's not working. If I go to Performance tab in app insights and I go to Browser tab, it's empty. I am not sure what I am doing wrong here.
Here is my applicaiton insights config file
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
<InstrumentationKey>{InstrumentationKey}</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" />
<Add Type="Microsoft.ApplicationInsights.Web.AzureAppServiceRoleNameFromHostNameHeaderInitializer, 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.
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>
<IncludeDiagnosticSourceActivities>
<Add>Microsoft.Azure.EventHubs</Add>
<Add>Microsoft.Azure.ServiceBus</Add>
</IncludeDiagnosticSourceActivities>
</Add>
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryModule, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AppServicesHeartbeatTelemetryModule, Microsoft.AI.WindowsServer" />
<Add Type="Microsoft.ApplicationInsights.WindowsServer.AzureInstanceMetadataTelemetryModule, Microsoft.AI.WindowsServer">
<!--
Remove individual fields collected here by adding them to the ApplicationInsighs.HeartbeatProvider
with the following syntax:
<Add Type="Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights">
<ExcludedHeartbeatProperties>
<Add>osType</Add>
<Add>location</Add>
<Add>name</Add>
<Add>offer</Add>
<Add>platformFaultDomain</Add>
<Add>platformUpdateDomain</Add>
<Add>publisher</Add>
<Add>sku</Add>
<Add>version</Add>
<Add>vmId</Add>
<Add>vmSize</Add>
<Add>subscriptionId</Add>
<Add>resourceGroupName</Add>
<Add>placementGroupId</Add>
<Add>tags</Add>
<Add>vmScaleSetName</Add>
</ExcludedHeartbeatProperties>
</Add>
NOTE: exclusions will be lost upon upgrade.
-->
</Add>
<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>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>
<ApplicationIdProvider Type="Microsoft.ApplicationInsights.Extensibility.Implementation.ApplicationId.ApplicationInsightsApplicationIdProvider, Microsoft.ApplicationInsights" />
<TelemetrySinks>
<Add Name="default">
<TelemetryProcessors>
<Add Type="Motion.Kinetic.Infrastructure.Logging.AI.AzureStorageDependencyFilter, Infrastructure" />
<Add Type="Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector.QuickPulse.QuickPulseTelemetryProcessor, Microsoft.AI.PerfCounterCollector" />
<Add Type="Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor, Microsoft.ApplicationInsights" />
</TelemetryProcessors>
<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel" />
</Add>
</TelemetrySinks>
<!--
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.
-->
<!--
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.
-->
<!--
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>
Update:
I have also tried adding more config options like the following but still no luck.
cfg: { // Application Insights Configuration
instrumentationKey: "{InstrumentationKey}",
enableDebug: true,
verboseLogging: true,
disableFetchTracking: false,
enableCorsCorrelation: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true
}
Also in the Network tab, I can see a track call to "https://dc.services.visualstudio.com/v2/track" with the following response:
{"itemsReceived":2,"itemsAccepted":0,"errors":[{"index":0,"statusCode":206,"message":"Telemetry sampled out."},{"index":1,"statusCode":206,"message":"Telemetry sampled out."}],"appId":"my-app-id"}
I am following the doc to implement application insights in asp.net mvc applicaition.
You have already added the Application insights Instrumentation key in under Views\Shared\_Layout.cshtml & appinsights.config
If not please follow the below steps:
Open Views\Shared_Layout.cshtml
This file is the outer-most template for HTML pages rendered by this application. Application Insights has inserted initialization code inside the head tag so that you can immediately start using the JavaScript API to instrument the client-side portion of the application. Add your Application Insights key in instrumentationKey: "Your key here" this portion.
< script type="text/javascript">
!function(T,l,y){var S=T.location,k="script",D="instrumentationKey",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+":"+t(e.getUTCMinutes())+":"+t(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),iKey:e,name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!0,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a<n.length;a++){var i=n[a].split("=");2===i.length&&(e[i[0][b]()]=i[1])}if(!e[C]){var r=e.endpointsuffix,o=r?e.location:null;e[C]="https://"+(o?o+".":"")+"dc."+(r||"services.visualstudio.com")}return e}(),c=s[D]||d[D]||"",u=s[C],p=u?u+"/v2/track":d.endpointUrl,(l=[]).push((n="SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)",a=t,i=p,(o=(r=v(c,"Exception")).data).baseType="ExceptionData",o.baseData.exceptions=[{typeName:"SDKLoadFailed",message:n.replace(/\./g,"-"),hasFullStack:!1,stack:n+"\nSnippet failed to load ["+a+"] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: "+(S&&S.pathname||"_unknown_")+"\nEndpoint: "+i,parsedStack:[]}],r)),l.push(function(e,t,n,a){var i=v(c,"Message"),r=i.data;r.baseType="MessageData";var o=r.baseData;return o.message='AI (Internal): 99 message:"'+("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) ("+n+")").replace(/\"/g,"")+'"',o.properties={endpoint:a},i}(0,0,t,p)),function(e,t){if(JSON){var n=T.fetch;if(n&&!y.useXhr)n(t,{method:N,body:JSON.stringify(e),mode:"cors"});else if(XMLHttpRequest){var a=new XMLHttpRequest;a.open(N,t),a.setRequestHeader("Content-type","application/json"),a.send(JSON.stringify(e))}}}(l,p))}function i(e,t){f||setTimeout(function(){!t&&m.core||a()},500)}var e=function(){var n=l.createElement(k);n.src=h;var e=y[w];return!e&&""!==e||"undefined"==n[w]||(n[w]=e),n.onload=i,n.onerror=a,n.onreadystatechange=function(e,t){"loaded"!==n.readyState&&"complete"!==n.readyState||i(0,t)},n}();y.ld<0?l.getElementsByTagName("head")[0].appendChild(e):setTimeout(function(){l.getElementsByTagName(k)[0].parentNode.appendChild(e)},y.ld||0)}try{m.cookie=l.cookie}catch(p){}function t(e){for(;e.length;)!function(t){m[t]=function(){var e=arguments;g||m.queue.push(function(){m[t].apply(m,e)})}}(e.pop())}var n="track",r="TrackPage",o="TrackEvent";t([n+"Event",n+"PageView",n+"Exception",n+"Trace",n+"DependencyData",n+"Metric",n+"PageViewPerformance","start"+r,"stop"+r,"start"+o,"stop"+o,"addTelemetryInitializer","setAuthenticatedUserContext","clearAuthenticatedUserContext","flush"]),m.SeverityLevel={Verbose:0,Information:1,Warning:2,Error:3,Critical:4};var s=(d.extensionConfig||{}).ApplicationInsightsAnalytics||{};if(!0!==d[I]&&!0!==s[I]){var c="onerror";t(["_"+c]);var u=T[c];T[c]=function(e,t,n,a,i){var r=u&&u(e,t,n,a,i);return!0!==r&&m["_"+c]({message:e,url:t,lineNumber:n,columnNumber:a,error:i}),r},d.autoExceptionInstrumented=!0}return m}(y.cfg);function a(){y.onInit&&y.onInit(n)}(T[t]=n).queue&&0===n.queue.length?(n.queue.push(a),n.trackPageView({})):a()}(window,document,{
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
instrumentationKey: "Your key here"
/* ...Other Configuration Options... */
}});
< /script>
Open ApplicationInsights.config file and check your application insights tag / connectionString tag which contains the application insights instrumentation key.
If not you need to configure Azure application insights by right clicking the project and configure your application insights local/Azure.
By default it added your application Insights connection string tag in ApplicationInsights.config file
< ConnectionString> Your app insights connection string < /ConnectionString>
If not you can add the Instrumentation key tag
< InstrumentationKey> Your instrumentation key < /InstrumentationKey>
After run your application and see the results in application Insights
Performance tab
If you added application insights Local see the results in application insights button in VS
Related
I'm creating a web application using the latest version of ASP.NET MVC 5.2.3. I just concern in XSS attack. I figure out in ASP.NET Core is perfectly working protecting from this attack the XSS and this framework totally amazing but it lacked third party I need to my project. Here's my concern. I already enabled the custom error too but I disabled it currently for testing.
But I want to make sure this will catch also.
Input Validation is passed. To avoid this exception or error.
A potentially dangerous Request.Form value was detected from the client (Name="").
using, the [AllowHtml] attribute this is fine or using the AntiXss library.
But, from the URL. Example URLs,
http://localhost:54642/Employees/
http://localhost:54642/Employees/?a=<script>
link or url
this error should like,
A potentially dangerous Request.Path value was detected from the client (<).
So my solution is enabling this from Web.config then it works!
But Troy Hunt said from his tutorial this is not a good or better practice for this error. So I decided to look the best solution from this XSS attack.
In my form I normally add this anti-forgery token
#Html.AntiForgeryToken()
then on my controller I made sure validate the token
[ValidateAntiForgeryToken]
also when passing the variable or data, I always declare correct variable. Anyways if its member area page you can always restrict access to correct member roles example like
[Authorize] // for registered user
or more filtered
[Authorize(Roles = "SUBSCRIBER.VIEW")]
Below is only applicable for .net 4.5 and above
// web.config
<system.Web>
<httpRuntime targetFramework="4.5" />
</system.Web>
// enabling anti-xss
<httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder,System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
Request validation Lazy validation was introduced in ASP.NET 4.5, I
just did some testing on it and it seems that lazy validation is the
enabled regardless of how you set the "requestValidationMode", after
you've installed the 4.5 framework.
Check out OWASP site. Here is the common ones I add in system.web in web.config file of a webapi app.
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
<remove name="X-Frame-Options" />
<remove name="X-XSS-Protection" />
<remove name="X-Content-Type-Options" />
<remove name="Cache-Control" />
<remove name="Pragma" />
<remove name="Expires" />
<remove name="Content-Security-Policy"/>
<clear />
<add name="X-Frame-Options" value="DENY" />
<add name="X-XSS-Protection" value="1; mode=block"/>
<add name="X-Content-Type-Options" value="nosniff" />
<add name="Cache-Control" value="no-cache, no-store" />
<add name="Pragma" value="no-cache" />
<add name="Expires" value="Sun, 1 Jan 2017 00:00:00 UTC" />
<add name="Content-Security-Policy" value="default-src 'self' 'unsafe-inline' data; img-src https://*;"/>
</customHeaders>
</httpProtocol>
I have a requirement where I need to write few information which will be changed frequently after the application gets deployed on server. Is there any way I can keep those information on some files of my asp.net application which when required can be updated and accessed in the application.
I tried to add the information in Web.config as that can be updated after deployment.Here is the code
<QueryConstants>
<add name ="SColumnName" value="UserId,First Name,Last Name,Description" />
<add name ="IColumnName" value="Company Name,Account Active Status" />
</QueryConstants>
but I am not able to access by the values from the keys.
How to achieve it ?
use app settings section as below in your web.config
<appSettings>
<add name ="SColumnName" value="UserId,First Name,Last Name,Description" />
<add name ="IColumnName" value="Company Name,Account Active Status" />
</appSettings>
then you can read as below
var sColumnName= ConfigurationManager.AppSettings["SColumnName"];
var iColumnName= ConfigurationManager.AppSettings["IColumnName"];
also check How do you modify the web.config appSettings at runtime?
I have consolidated the connection string information for a number of C# .NET solutions that are in my possession. Previously, each project was storing its connection string in its own format, requiring me to modify several files for each installation of the software.
Only one remaining solution is giving me trouble. This particular solution uses Castle Windsor 2.0, ActiveRecord 2.0 and NHibernate 2.1. The code reads its configuration from an XML file. I wish to remove the connection string from the config file and set it programmatically in the code.
Here is the relevant section of code that initiates Windsor:
windsorContainer = new WindsorContainer(new XmlInterpreter(xmlFileName));
windsorContainer.Resolve<IWindsorConfigurator>().Configure(windsorContainer);
logger = windsorContainer.Resolve<ILogger>();
Here are the contents of the XML file:
<?xml version="1.0"?>
<configuration>
<properties>
<connectionString>Server=*****;Database=*****;User Id=*****;Password=*****</connectionString>
</properties>
<facilities>
<facility id="logging" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" configFile="Configs/log4net.config" />
<facility id="atm" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" />
<facility id="arfacility" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration" isDebug="false" isWeb="false">
<!-- Configure the namespaces for the models using Active Record Integration -->
<assemblies>
<item>ChronoSteril.Application</item>
</assemblies>
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="connection.connection_string" value="#{connectionString}" />
<add key="hibernate.cache.provider_class" value="NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache" />
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
<add key="hibernate.expiration" value="60" />
</config>
</facility>
</facilities>
<components>
<component id="windsorConfigurator" service="ChronoSteril.Application.IWindsorConfigurator, ChronoSteril.Application" type="ChronoSteril.WinApp.ClarionIntegrationWindsorConfigurator, ChronoSteril.WinApp" />
</components>
I am not familiar with Windsor. During my Google tour, I did see some code that adds facilities programmatically, but those examples were not valid for my version of Windsor (I assume).
Question: Can anyone guide me in removing the connection string information from the XML file and allow me to set it in the code?
Thank you!
I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.)
Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here.
My XML file remains the same, except that I use bogus values for the connection string information. I will never need to modify these, and they do not reveal any valid connection information. This was my intention. I still have not discovered how to successfully remove the ActiveRecord configuration from the XML file and configure using code.
I now call a method that contains the following code:
ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
NHibernate.Cfg.Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));
connectionString = ReadConnectionString();
configuration.SetProperty("connection.connection_string", connectionString);
This works for me. I hope that it can also help someone else who is in the same position as I was.
I am trying to access the google DFA API in my .Net web application.i have supplied all the important information in web.config file.
that is
`
https://code.google.com/p/google-api-dfa-dotnet/wiki/HowToUseADfaUser
for details.
You can refer to
https://code.google.com/p/google-api-dfa-dotnet/wiki/UnderstandingAppConfig
for detailed explanation of each configuration key.
-->
<!-- Settings related to SOAP logging. -->
<!--
This section contains the settings specific to the Google's DoubleClick
for Advertisers API DotNet Client Library. You can use the App.config /
Web.config for quickly configuring and running a simple application.
However, it is not mandatory to provide your settings in the config file,
you may also set or override these settings at runtime. See
https://code.google.com/p/google-api-dfa-dotnet/wiki/HowToUseADfaUser
for details.
You can refer to
https://code.google.com/p/google-api-dfa-dotnet/wiki/UnderstandingAppConfig
for detailed explanation of each configuration key.
--><!-- Settings related to SOAP logging. --><add key="LogPath" value="C:\Logs\Dfa\" />
<add key="LogToFile" value="false" />
<add key="MaskCredentials" value="true" />
<add key="LogErrorsOnly" value="true" />
<!-- Settings related to general library behaviour. -->
<!-- Use this key to automatically retry a call that failed due to a
recoverable error like expired credentials. -->
<!-- Settings related to general library behaviour. --><!-- Use this key to automatically retry a call that failed due to a
recoverable error like expired credentials. --><add key="RetryCount" value="1" />
<!-- Set the service timeout in milliseconds. -->
<!-- <add key="Timeout" value="100000"/> -->
<!-- Use this key to enable or disable gzip compression in SOAP requests.-->
<!-- Set the service timeout in milliseconds. --><!-- <add key="Timeout" value="100000"/> --><!-- Use this key to enable or disable gzip compression in SOAP requests.--><add key="EnableGzipCompression" value="true" />
<!-- Proxy settings for library. -->
<!-- Proxy settings for library. --><add key="ProxyServer" value="" />
<add key="ProxyUser" value="" />
<add key="ProxyPassword" value="" />
<add key="ProxyDomain" value="" />
<!-- Settings specific to DFA API. -->
<!-- Set a friendly name to identify your application. -->
<!-- Settings specific to DFA API. --><!-- Set a friendly name to identify your application. --><add key="ApplicationName" value="My App" />
<!--Uncomment this key if you want to use DFA test environment.-->
<add key="DfaApi.Server" value="https://advertisersapitest.doubleclick.net"/>
<!-- Uncomment this key if you want to use DFA beta environment. -->
<!-- <add key="DfaApi.Server" value="http://betaadvertisersapi.doubleclick.net"/> -->
<!-- Set the Authorization method to be used with the client library. -->
<!-- To use LoginService as authentication mechanism, uncomment the following
section and comment the OAuth2 section below. -->
<!--<add key="AuthorizationMethod" value="LoginService" />
<add key="DfaUserName" value="" />
<add key="DfaPassword" value="" />-->
<!-- Uncomment this key if you want to reuse an authToken returned by
LoginRemoteService multiple times. -->
<!-- <add key="DfaAuthToken" value="ENTER_YOUR_DFA_AUTH_TOKEN_HERE"/> -->
<!-- Settings specific to use OAuth2 as authentication mechanism. You could
run Common\Util\OAuth2TokenGenerator.cs to generate this section of the
config file.
-->
<!-- Uncomment this key if you want to use DFA test environment. --> <!--<add key="DfaApi.Server" value="https://advertisersapitest.doubleclick.net"/>--> <!-- Uncomment this key if you want to use DFA beta environment. --><!-- <add key="DfaApi.Server" value="http://betaadvertisersapi.doubleclick.net"/> --><!-- Set the Authorization method to be used with the client library. --><!-- To use LoginService as authentication mechanism, uncomment the following
section and comment the OAuth2 section below. --><!--<add key="AuthorizationMethod" value="OAuth2" />-->
<!-- Provide the OAuth2 client ID and secret. You can create one from
https://code.google.com/apis/console/. See
https://code.google.com/p/google-api-dfp-dotnet/wiki/UsingOAuth
for more details.
-->
<add key="AuthorizationMethod" value="OAuth2" />
<add key="OAuth2Mode" value="APPLICATION" />
<add key="OAuth2ClientId" value="741571964664-m4kpcsris5s0g6meufb4jofria0fm6s2.apps.googleusercontent.com" />
<add key="OAuth2ClientSecret" value="xqYh16LPvixcdk-BS3M9gZLw" />
<add key="DfaAuthToken" value="AIzaSyDjLEiomKRThlJExMDra-Ck7qvZWJNK-3M"/>
<add key="OAuth2RefreshToken" value="1/fKT0ObQy19dmZA51zVJDMtv2IeaGCGaS9rlTkCDPfeA" />
<add key="OAuth2RedirectUri" value="https://developers.google.com/oauthplayground" />
<add key="DfaUserName" value="My_DFA_UserName" />
<add key="DfaPassword" value="My_DFA_Password" />
<!-- The following OAuth2 settings are optional. -->
<!-- Provide a different OAuth2 scope if required. Multiple scopes should be
separated by spaces. -->
<!-- <add key="OAuth2Scope" value="INSERT_OAUTH2_SCOPE_HERE" /> -->
<!-- Use the following keys if you want to use Web / Installed application
OAuth flow.-->
<!-- <add key="OAuth2Mode" value="APPLICATION" /> -->
<!-- If you have only a single sount, then you can run
OAuth2TokenGenerator.cs to generate a RefreshToken for that account and
set this key in your application's App.config / Web.config. If you are
making calls to multiple accounts, then you need to implement OAuth2
flow in your account and set this key at runtime. See OAuth folder
under Examples folder for a web and a console application example.
-->
<!-- <add key="OAuth2RefreshToken" value="INSERT_OAUTH2_REFRESH_TOKEN_HERE" /> -->
<!-- Optional: Specify an OAuth2 redirect url if you are building a
web application and implementing OAuth2 web flow in your application.
-->
<!-- <add key="OAuth2RedirectUri" value="" /> -->
<!-- Use the following keys if you want to use OAuth2 service account flow.
You should comment out all the keys for Web / Installed application
OAuth flow above. See
https://developers.google.com/doubleclick-publishers/docs/service_accounts
and https://code.google.com/p/google-api-dfp-dotnet/wiki/UsingOAuth
for more details.
-->
<!--
<add key="OAuth2Mode" value="SERVICE_ACCOUNT" />
<add key="OAuth2ServiceAccountEmail"
value="INSERT_OAUTH2_SERVICE_ACCOUNT_EMAIL_HERE" />
<add key="OAuth2PrnEmail" value="INSERT_OAUTH2_USER_EMAIL_HERE" />
<add key="OAuth2JwtCertificatePath"
value="INSERT_OAUTH2_JWT_CERTIFICATE_PATH_HERE" />
<add key="OAuth2JwtCertificatePassword"
value="INSERT_OAUTH2_JWT_CERTIFICATE_PASSWORD_HERE" />
-->
<!--<add key="AuthorizationMethod" value="LoginService " /><add key="DfaUserName" value="" /><add key="DfaPassword" value="" />--><!-- Uncomment this key if you want to reuse an authToken returned by
LoginRemoteService multiple times. --> <!--<add key="DfaAuthToken" value="AIzaSyDjLEiomKRThlJExMDra-Ck7qvZWJNK-3M"/>--> <!-- Settings specific to use OAuth2 as authentication mechanism. You could
run Common\Util\OAuth2TokenGenerator.cs to generate this section of the
config file.
--> <!--<add key="AuthorizationMethod" value="OAuth2" />--> <!-- Provide the OAuth2 client ID and secret. You can create one from
https://code.google.com/apis/console/. See
https://code.google.com/p/google-api-dfp-dotnet/wiki/UsingOAuth
for more details.
-->
<!--<add key="OAuth2ClientId" value="741571964664.apps.googleusercontent.com" />
<add key="OAuth2ClientSecret" value="mSU3WGHlwGkDn9IVvGVf-3R0" />-->
<!-- The following OAuth2 settings are optional. --><!-- Provide a different OAuth2 scope if required. Multiple scopes should be
separated by spaces. --><!-- <add key="OAuth2Scope" value="INSERT_OAUTH2_SCOPE_HERE" /> --><!-- Use the following keys if you want to use Web / Installed application
OAuth flow.--><!-- <add key="OAuth2Mode" value="APPLICATION" /> --><!-- If you have only a single account, then you can run
OAuth2TokenGenerator.cs to generate a RefreshToken for that account and
set this key in your application's App.config / Web.config. If you are
making calls to multiple accounts, then you need to implement OAuth2
flow in your account and set this key at runtime. See OAuth folder
under Examples folder for a web and a console application example.
--> <!-- Optional: Specify an OAuth2 redirect url if you are building a
web application and implementing OAuth2 web flow in your application.
--><!-- <add key="OAuth2RedirectUri" value="" /> --><!-- Use the following keys if you want to use OAuth2 service account flow.
You should comment out all the keys for Web / Installed application
OAuth flow above. See
https://developers.google.com/doubleclick-publishers/docs/service_accounts
and https://code.google.com/p/google-api-dfp-dotnet/wiki/UsingOAuth
for more details.
--><!--
<add key="OAuth2Mode" value="SERVICE_ACCOUNT" />
<add key="OAuth2ServiceAccountEmail"
value="INSERT_OAUTH2_SERVICE_ACCOUNT_EMAIL_HERE" />
<add key="OAuth2PrnEmail" value="INSERT_OAUTH2_USER_EMAIL_HERE" />
<add key="OAuth2JwtCertificatePath"
value="INSERT_OAUTH2_JWT_CERTIFICATE_PATH_HERE" />
<add key="OAuth2JwtCertificatePassword"
value="INSERT_OAUTH2_JWT_CERTIFICATE_PASSWORD_HERE" />
--></DfaApi>
<system.web>
<webServices>
<soapExtensionTypes>
<add type="Google.Api.Ads.Common.Lib.SoapListenerExtension, Google.Ads.Common" priority="1" group="0" />
</soapExtensionTypes>
</webServices>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.net>
<settings>
<httpWebRequest maximumErrorResponseLength="-1" />
</settings>
</system.net>
<system.diagnostics><sources><source name="AdsClientLibs.DeprecationMessages" switchName="AdsClientLibs.DeprecationMessages" switchType="System.Diagnostics.SourceSwitch"><listeners><add name="myListener" type="System.Diagnostics.EventLogTraceListener" initializeData="Application" /></listeners></source></sources><switches><!-- Use this trace switch to control the deprecation trace messages
written by Ads* .NET libraries. The default is level is set to
Warning. To disable all messages, set this value to Off. See
http://msdn.microsoft.com/en-us/library/system.diagnostics.sourcelevels.aspx
for all possible values this key can take. --><add name="AdsClientLibs.DeprecationMessages" value="Warning" /></switches></system.diagnostics></configuration>
`
and my code snippet is `
public override AdvertiserRecordSet Run(DfaUser user)
{
// Create AdvertiserRemoteService instance.
AdvertiserRemoteService service = (AdvertiserRemoteService)user.GetService(DfaService.v1_19.AdvertiserRemoteService);
String searchString = _T("");
// Create advertiser search criteria structure.
AdvertiserSearchCriteria advSearchCriteria = new AdvertiserSearchCriteria();
advSearchCriteria.pageSize = 10;
advSearchCriteria.searchString = searchString;
string str = service.RequestHeader.TargetNamespace.ToString();
try
{
// Get advertiser record set.
AdvertiserRecordSet recordSet = service.getAdvertisers(advSearchCriteria);
// Display advertiser names, ids and spotlight configuration ids.
if (recordSet.records != null)
{
foreach (Advertiser result in recordSet.records)
{
//Console.WriteLine("Advertiser with name \"{0}\", id \"{1}\", and spotlight " +
// "configuration id \"{2}\" was found.", result.name, result.id, result.spotId);
}
return recordSet;
}
else
{
Console.WriteLine("No advertisers found for your criteria.");
}
}
catch (Exception ex)
{
// Console.WriteLine("Failed to retrieve advertisers. Exception says \"{0}\"", ex.Message);
}
return null;
}
`
I am stuck here.Please help to find out the solution.
Regards.
I'm doing some work in Visual Studio 2012 Express Edition. I have added an App.config XML file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
The first thing that happens is a warning comes up that says "The 'configuration' element is not declared". Does anyone know why this is happening? It looks like elements can not be declared inside of until this is resolved.
Thanks!
This is the entire XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="Version" value="779" />
<add key="TimeOut" value="60000" />
<add key="LogFileName" value="Log.txt" />
<!-- your Developer Id with eBay -->
<add key="Environment.DevId" value="" />
<!-- your Application Id with eBay -->
<add key="Environment.AppId" value="" />
<!-- your Application Certificate with eBay -->
<add key="Environment.CertId" value="" />
<!-- API Server URL -->
<!-- For production site use: https://api.ebay.com/wsapi -->
<!-- For Sandbox use: https://api.sandbox.ebay.com/wsapi -->
<add key="Environment.ApiServerUrl" value="https://api.sandbox.ebay.com/wsapi" />
<!-- EPS Server URL -->
<!-- For production site use: https://api.ebay.com/ws/api.dll"/-->
<add key="Environment.EpsServerUrl" value="https://api.sandbox.ebay.com/ws/api.dll" />
<!-- eBay Signin URL -->
<!-- For production site use: https://signin.ebay.com/ws/eBayISAPI.dll?SignIn -->
<!-- https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn -->
<add key="Environment.SignInUrl" value="https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn" />
<!-- ViewItem URL -->
<!-- For production site use: http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item={0} -->
<add key="Environment.ViewItemUrl" value="http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&item={0}" />
<!-- token is for both API server and EPS server -->
<add key="UserAccount.ApiToken" value="" />
<!-- eBay site ID -->
<add key="UserAccount.eBayUserSiteId" value="0" />
<add key="logexception" value="true"/>
<add key="logmessages" value="true"/>
<add key="logsdkmessages" value="true"/>
<add key="logsdk" value="true"/>
<add key="logfile" value="Log.txt"/>
<!-- Rule Name-->
<add key="RuName" value=""/>
<!-- Set this if you access eBay API server behind a proxy server-->
<add key="Proxy.Host" value =""/>
<add key="Proxy.Port" value =""/>
<!-- set proxy server username/password if necessary-->
<add key="Proxy.Username" value=""/>
<add key="Proxy.Password" value=""/>
Go to XML menu (visual studio top menu item) choose schemas and find for DotNetConfig.xsd and choose Use this schema.
Your problem will resolve for sure
<configuration xmlns="schema URL">
<!-- configuration settings -->
</configuration>
do changes,like above & try
I had the same issue. It is not an error, it is simply a warning; so your application should still compile. I used the following simple config file and the warning is still produced.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime
version="v4.0"sku=".NETFramework,
Version=v4.5"/>
</startup>
</configuration>
It is an issue that has been raised on the MSDN website, but it does not seem to have been satisfactorily resolved. See link below:
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/18a1074f-668f-4fe3-a8d9-4440db797439
I had to
-> Go to XML menu (visual studio top menu item) choose schemas and select DotNetConfig.xsd AND RazorCustomSchema.xsd AND EntityFrameworkConfig_6_1_0.xsd
I just had this warning popup inside an autogenerated xml file while working on a xaml project.
Using Debug->Clean Solution and Debug->Rebuild Solution fixed it. Might want to try that before getting fancy with the schemas.
Visual Studio 2013 Express Edition is missing the DotNetConfig.xsd (https://connect.microsoft.com/VisualStudio/feedback/details/817322/dotnetconfig-xsd-files-not-present-in-vs-2013-express-for-desktop).
So to get rid of the warning in VS 2013 Express:
get a copy of DotNetConfig.xsd from another system or from the web (I used https://gist.github.com/eed3si9n/5dd7dd98ad2b3f668928b23477de35a3)
download to C:\Program Files (x86)\Microsoft Visual Studio 12.0\Xml\Schemas
add the schema following Ramakrishna's answer
The warning should be gone.
Choose use this schema. DotNetConfig.xsd
XLM Menu..... Visual Studio
Works perfectly.
I was having less space on my drive which might have resulted in incomplete loading of my application solution. This "the-configuration-element-is-not-declared" problem got solved after i created some space on my drive.
I also got the same warning. After thinking about for some time I realized my error working with SQL (MS SQL).
Warning: the 'configuration' element is not declared
Using C#
App.Config code:
<connectionStrings>
<add name="dbx" connectionString="Data Source=ServerNameHere;Initial Catalog=DatabaseNameHere;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
*this calls out the database name in the connectionStrings, when I plugged in my SQL code as a practice I always use the database name, schema, then table. This practice didn't carry over well in Visual Studio as I am a beginner. I removed the db name from my SQL syntax and only called from the schema, data table. This resolved the issue for me.
Form.CS:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [DatabaseName].[Schema].[TableName] WHERE [MEPeriod] = '2020-06-01'", con))
Updated to:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM [Schema].[TableName] WHERE [MEPeriod] = '2020-06-01'", con))
This worked for me, I hope this is found as useful.