How to read the value from web config in AngularJs Controller - asp.net

<configuration>
<appSettings>
<add key="var1" value="SomeValue"/>
</appSettings>
<configuration>
I want to read this var1 in angularJS controller
Like this...
function ReadConfigurationSettings()
{
var k = '<%=ConfigurationManager.AppSettings["var1"].ToString() %>'
alert(k);
}
but its not working..

You cannot get a value from web config directly. One option is to put the value into a meta tag in your index html for example like this:
<meta name="var1" content="#ConfigurationManager.AppSettings["var1"]" />
Then you can get that value from angular like this:
var var1 = angular.element(document).find('meta[name=var1]').prop("content");

Related

Get UserId in MVC to use in View

I have the following problem in my MVC 5 web app. I used database first approach and the entity framwork to create a table [accountlist] that has a foreign key relationship on [UserId] to the [Id] column from [AspNetUsers]. Right now the pertaining accountlist.cshtml contains a dropdown menu. I also tried #Html.HiddenFor(model => model.UserId, new { #Value = HttpContext.Current.User.Identity.Name}) but the problem is how that I need the correct userid and not the username (I don't want the [UserName] from [AspNetUsers] to be an primary key).
Unfortunately, HttpContext.Current.User.Identity.GetUserId() as suggested in this solution says that Identity contains no definition for GetUserId().
Does anyone has solution?
Thanks in advance!
#stephen.vakil is correct. You need to import the namespace. Specifically, you need to add:
#using Microsoft.AspNet.Identity
#model Namespace.To.Foo
Alternatively, if you want to do this more often or just don't want to include the namespace in the view, you can edit the Web.config in the Views folder of your project and add it there instead:
<?xml version="1.0"?>
<configuration>
...
<system.web.webPages.razor>
...
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="Microsoft.AspNet.Identity" />
Any namespaces there are available to every view automatically.
this is the best Article for asp.net mvc authentication from ben foster. It helped me last time.
It works even if you are not going for entity framework
SigIn Like this
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Sid, userID)
},
"ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
Create New Class
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public int ID
{
get
{
return this.FindFirst(ClaimTypes.Sid).Value;
}
}
}
Let's create a custom base view page for our Razor views that provides access to our AppUser principal:
public abstract class AppViewPage<TModel> : WebViewPage<TModel>
{
protected AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
public abstract class AppViewPage : AppViewPage<dynamic>
{
}
Open up /views/web.config and the set the pageBaseType:
<system.web.webPages.razor>
<pages pageBaseType="NakedIdentity.Mvc.AppViewPage">
Rebuild the project and update the Index.cshtml view:
<p>
User ID: #CurrentUser.ID?
</p>
If you are using SimpleMemberShip provider, then
int UserId = WebSecurity.CurrentUserId;
and add attribute [InitializeSimpleMembership] on the top of controller method.
add this line to your controller constructor:
user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
then you will have user.Id in all you methods inside your controller. And for security purpose, never keep your user id inside view as hidden!.

With Glimpse How To Turn It Off Without Disabling?

I love Glimpse but only when I' interested in what it has to tell me. I have a glimpse role that I can turn on and off to make glimpse go away (see code below) but what I really want is to be able to turn it on and off while it is enabled in my global.asax. I've tried going to site.com/glimpse.axd and set "turn glimpse off" but then on the next page refresh it is back.
What am I missing?
public class GlimpseSecurityPolicy : IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
var httpContext = policyContext.GetHttpContext();
if (!httpContext.User.IsInRole("GlimpseUser"))
{
return RuntimePolicy.Off;
}
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
get { return RuntimeEvent.EndRequest; }
}
}
In My Web.Config:
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<runtimePolicies>
<ignoredTypes>
<add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet" />
<add type="Glimpse.Core.Policy.ControlCookiePolicy, Glimpse.Core" />
</ignoredTypes>
</runtimePolicies>
Ok, the reason why clicking on the "Turn Glimpse Off" button has no effect is because the ControlCookiePolicy is disabled in the config, hence clicking that button will have no effect.
So you need to remove that entry from the config to make that work again:
<add type="Glimpse.Core.Policy.ControlCookiePolicy, Glimpse.Core" />
when you are saying that
The other code public class GlimpseSecurityPolicy" is in my global.asax
you mean that the GlimpseSecurityPolicy is basically defined as an inner class of the Mvc Application class?
Either way if you would enable logging for Glimpse in the config
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<logging level="Trace" />
<runtimePolicies>
<ignoredTypes>
<add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet" />
</ignoredTypes>
</runtimePolicies>
</glimpse>
then you should see a glimpse.log file appear in the root of your web application, and once the application is started, you should see an entry like this:
2014-06-13 09:48:25.8498 | DEBUG | Discovered IRuntimePolicy of type 'SOME NAMESPACE+GlimpseSecurityPolicy' and added it to collection. |
If that is the case then the policy is actually discovered.
You can put a breakpoint inside the Execute method to check whether a call is actually made and what the outcome is.

ASP.NET .cshtml razor file transform on Build

I'm trying to find a way to transform my index.cshtml file when building my project.
For instance make this:
<script src="app-dev.js"></script>
become this when Build mode is Release:
<script src="app-prod.js></script>
Ok, this will work.
Add an appsetting for it:
<add key="Environment" value="dev"/>
Then in your view add this:
<script src="app-#(System.Web.Configuration.WebConfigurationManager.AppSettings["Environment"]).js></script>
In your other environments simply use transforms to replace it i.e.
<appSettings>
<add key="Environment" value="prod" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
An alternative and I feel a better approach would be to abstract out the WebConfiguration manager as an interface and have the app setting set in a model instead.
If it is in a common layout and set everytime maybe create a base model and have it set in an OnActionExecuted in a base controller instead.
In our case the decision has to be made based on whether the build is debug build or release build. We created a mvc helper extension method as
public static MvcHtmlString CustomScriptTag(this HtmlHelper helper)
{
var scriptString = string.Format("<script type='text/javascript' src='{0}'></script>", VirtualPathUtility.ToAbsolute("~/app-prod.js"));
#if DEBUG
scriptString = string.Format("<script type='text/javascript' src='{0}'></script>", VirtualPathUtility.ToAbsolute("~/app-dev.js"));
#endif
return new MvcHtmlString(scriptString);
}
From your cshtml file you can call it like
#Html.CustomScriptTag()

Why is my HttpHandler not being fired?

I am trying to use a http hadler, so I created a class lirary project and added this code:
namespace MyProject.Handlers
{
public class Class1 : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("Hello from custom handler.");
}
}
}
Then I compiled it and it generated the MyProject.Handlers.dll file. I put it in my asp.net bin folder and added this to the asp.net
<system.webServer>
<handlers>
<add name="TutorialHandler" verb="*" path="*" type="MyProject.Handlers.Class1, MyProject.Handlers" modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="File" />
</handlers>
<modules runAllManagedModulesForAllRequests="true">
//some stuff I *think* it doesn't make a difference
</modules>
//some stuff I *think* it doesn't make a difference
</system.webServer>
and
<system.web>
<httpHandlers>
<add verb="*" path="*" type="MyProject.Handlers.Class1, MyProject.Handlers" />
</httpHandlers>
</system.web>
But it just doesn't get called!
I start the debugger, set the breakpoint, but it doesn't stop. If I check the output html in firebug, the sentence "Hello from custom handler" is not there.
What am I doing wrong?
Thanks,
Oscar
EDIT: I'm using framework 4.0, IIS7.
Could it be that I am using routes? (not calling directly index.aspx, but /home or something like this?)
For some reason it wasn't being called when it was at the end of the handlers list. I moved to the top and got a strange error regarding webresources.axd. The reson was the path="*".
I couldn't find a matching path because I am using routes.
At the end I found out that I was using the wrong tool: the modules were the right thing for me, not handlers, because I would like to add things to my output depending on the case. So I changed my approach to use modules instead and it now looks good.
Thanks to all that helped me with comments!

IIS 7 Force Fresh Images

How do I force IIS 7 to not cache images for a particular page?
I would have thought that it is your browser doing the caching.
In any case one way around this as long as your link is not statically declared in the html, is to append a random number on the end of the images url:
<img src="http://mywebsite/images/mypic.png?a=123456" />
the argument means nothing because you are doing nothing with it, but to the browser it looks like a new uncached link.
How you put that random number on the end is up to you:
<img src="javascript:getMyLink();" />
or from the code behind:
Image myImage = new Image();
myImage.Source = "myurl?a=" + Guid.NewGuid().ToString();
someOtherControl.Controls.Add(myImage);
(of course this is pseudo code, you need to check that the property names are correct).
In IIS7, you can do this either declaratively in your web.config, or programmatically.
<location path="YourPath">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
The programmatic solution requires a simple HttpModule that's registered to run for all requests in Integrated mode, where you look for the URLs that you're concerned about. Then call:
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
FWIW, you may want to consider disabling client-side caching only, while enabling server-side caching, by using HttpCacheability.ServerAndNoCache. Also, if you add a query string on the image names, you will prevent server-side caching by http.sys.
In case it helps, I cover techniques like these in detail in my book: Ultra-Fast ASP.NET.
I've had to deal with this a lot but i need to better understand your end goal as IIS7 will update it's cache if an image is changed on the server, so maybe what you are seeing is the browser cache, have you looked into etags?
The old fall back is to stick a random query string at the end of the image path which keeps the browser guessing.
One sure way to prevent it from caching is to make custom file handler for .gif, .jpg, .png extention (lookup iHttpHandler) (code below lifted from http://www.codeguru.com/csharp/csharp/cs_network/http/article.php/c12641/
using System.IO;
using System.Web;
using System.Globalization;
namespace MVPHacks
{
public class ImageHandler: IHttpHandler
{
public void ProcessRequest(System.Web.HttpContext ctx)
{
HttpRequest req = ctx.Request;
string path = req.PhysicalPath;
string extension = null;
string contentType = null;
extension = Path.GetExtension(path).ToLower();
switch (extension)
{
case ".gif":
contentType = "image/gif";
break;
case ".jpg":
contentType = "image/jpeg";
break;
case ".png":
contentType = "image/png";
break;
default:
throw new NotSupportedException("Unrecognized image type.");
} if (!File.Exists (path))
{
ctx.Response.Status = "Image not found";
ctx.Response.StatusCode = 404;
}
else
{
ctx.Response.StatusCode = 200;
ctx.Response.ContentType = contentType;
ctx.Response.WriteFile (path);
}
}
public bool IsReusable { get {return true; } }
}
}
And don't forget to remove the default image handlers and add your in both sections of the web.config
<httpHandlers>
<clear />
<add verb="*" path="*.jpg" type="MVPHacks.ImageHandler" />
<add verb="*" path="*.gif" type="MVPHacks.ImageHandler" />
<add verb="*" path="*.png" type="MVPHacks.ImageHandler" />
</httpHandlers>
<handlers>
<clear />
<add verb="*" path="*.png" type="MVPHacks.ImageHandler" name="png" />
<add verb="*" path="*.gif" type="MVPHacks.ImageHandler" name="gif" />
<add verb="*" path="*.jpg" type="MVPHacks.ImageHandler" name="jpg />
</handlers>

Resources