Tag Archives: App_Code

[RESOLVED]how can i use url.action in @helper method ?

Hi dear ,

 I create a @helper method and use @Url.Action helper in it.(in App_Code Folder)

@helper GetNews(int CategoryID, int Rows)
         <div class="@Style" id="@CategoryID">
                  <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>

after run i get an error :

Compilation Error 
  Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

 Compiler Error Message: CS0103: The name 'Url' does not exist in the current context

Source Error:


Line 193:                                </table>*@
Line 194:
Line 195:                                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
Line 196:                                &nbsp;
Line 197:                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>

I had
to have
a class named ExtensionMethodHelper
for create external helpers and use it ( in Model folder ).but i
can not call
external helpers on the page(.cshtml) that
I’ve created
App_Code folder.

in fact after write @Html.  i dont find my favorite external helper (in ExtensionMethod class in Model folder).

for e.g : Html.PersianDate made in ExtensionMethodHelper in Model Folder

   <span class="date">@Html.ToPersianDate(item.DateToShow)</span>

in :

below helper create in App_Code

@helper GetNews(int CategoryID, int Rows)
       <div class="@Style" id="@CategoryID">
                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                   <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>

 how can i solve it

please help me


I use the "UrlHelper" class to do this.  Here’s a helper I always used in my projects (prior to bundles).  Use it as an example to expand on your own:

// file name is "Content.cs" stored in App_Code folder

@using System.Web.Mvc; @helper Script(string scriptName, UrlHelper url) { <script type="text/javascript" src="@url.Content("~/Scripts/" + scriptName)"></script> }

the helper in my View then looks like:

@Content.Script("jquery-1.10.1.min.js", Url)

You can see that I pass the "Url" to the helper.  Your helper would then look like…

@helper GetNews(int CategoryID, int Rows, UrlHelper url)

  <a href="@url.Action("Rss", "Home", ...)">


the "url" is lowercase fyi.  Don’t confuse it with Url

[RESOLVED]How can i get resolution os visitor?

Hi dear ,

I want get resolution of user and set it in a session but i dont any result

my code in _layout.cshtml is :

<body dir="rtl">
    <script type="text/javascript">

        $(document).ready(function () {
            PageMethods.setResolution(window.innerWidth, window.innerHeight);



and basepage.cs in App_Code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.Services;
using System.Web.Script.Services;

/// <summary>
/// Summary description for basepage
/// </summary>
public class basepage : System.Web.UI.Page
	public basepage()
		// TODO: Add constructor logic here

    public static Size ScreenResolution
            return (Size)HttpContext.Current.Session["ScreenResolution"];


    [WebMethod, ScriptMethod]
    public static void setResolution(int width, int height)
        ScreenResolution = new Size(width, height);

after run project HttpContext.Current.Session["ScreenResolution"] is empty .why?

please help me


To avoid any confusion, you aren’t going to actually be able to retrieve the "resolution" of the users monitor, but you can access the size of their current window. You’ll just need to make a request and hit your WebMethod when the page loads via AJAX. Since
you already have jQuery included, it should be fairly trivial as seen below.

Within your Web Form, you would create a method that looks like the following :

public static void SetResolution(int height, int width)
       HttpContext.Current.Session["Resolution"] = new Size(width, height);

Notice the all important EnableSession attribute set to true. This will allow you to set the Session within a WebMethod. Next when your Page loads, you would make an AJAX call to set these values through jQuery using the following code :

<!-- Script to set resolution -->
<script type="text/javascript">
        $(function () {
            // When the page loads, store the resolution in the Session
                type: "POST",
                url: "Example.aspx/SetResolution",
                data: '{ width: ' + $('window').width() + ', height: ' + $('window').height() + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    // Do something to indicate your values were set

This is just an example of an approach of handling this, however could you elaborate on why you are storing the users resolution or window size within your server-side code? Basically all information related to the browser should be handled within the client.

You may want to consider taking a look at 51Degree’s "Foundation" project (also called the 51Degrees.Mobi project) , which greatly enhances the Mobile detection features available in .NET and is actually recommended by ASP.net as it provides better
detection for more recent devices.

You can read more about the Foundation project and download it here.

Hi Rion William ,

Thank you very much for your solution and suggestion

[RESOLVED]Calling APX page from .cshtml


I have an MVC application with some aspx pages in it.

One of the .cshtml file make calls to .aspx page, using the line below and this .cshtml file resides in App_code.

a href="@Href("~/a/b/c/MyPage.aspx?param1=" + @Id + "&param2=" +   @SomeId)">@Name</a>

This needs to be there because it has to be re-used as a partial class. So obviously since this .cshtm file is in app_code, it doesn’t have reference to HtmlHelper.

So when I make an Href call from there, the site.master is throwing null reference error on the below line, because @Html is null.

<li>@Html.ActionLink("Home", "Index", "Home"); </li>

The same master page works on other scenarios.

Can anyone suggest a work around.


Put your partial view in shared views. or do not use Helper methods. instead use

<li><a href="HomeIndex">Home</a></li>

If I move the partial view to Shared view. How do I access the method in the Partial View.

For example I have a method in partial view. Now this partial view is in the Views/Shared folder

like this.

Partial View name is Customer


@helper Render()



How can I access this method from another .cshtml.

When the partial view was in AppCode I could access it by saying @Customer. Now I cannot.

So the question is

How to make a call to a method is the partial view from another View.


I misunderstood your requirement.. Now I got it

check this link if it can helper


You can pass Html as parameter.

[RESOLVED]Razor Helpers in MVC?

Is it possible to use Razor syntax helpers (defined in .cshtml files) in ASP.NET MVC?

I’ve found no shortage of resources on how to create helpers in ASP.NET MVC, but they all define their helpers in .cs files and manually build html strings, rather than simply letting me use formatted html from a .cshtml file.

As a very minimal example of what I want to accomplish, here’s a couple of .cshtml files:


<h2>Page 1</h2>


@helper GetBackLink()
    @:@Html.ActionLink("Back", "Index")

Intellisense tells me in Page1 that "The name ‘MyHelper’ does not exist in the current context," so it’s possible this is just a matter of putting the right @using directive in Page1.cshtml, but I don’t know what namespace my helper methods live in.  Any

Yes you can. however to share it with multiple views, you will have to put MyHelper.cshtml in the App_Code folder.

and access it as @MyHelper.GetBackLink()

very good example by Scottgu for the same scenario can be found at,




*Please mark it as answer if appropriate*

if the MyHelper is a class, then in the view page you can use like:


var helper = new MyHelper();

var testResult = helper.GetBackLink();

This simple will store the return value from the getBackLink into testResult and you can use the variable in the viewpage anywhere, 


hope this helps.


Thanks, Chintan.  One side effect of moving my helper into ~/App_Code/ was that that the standard Html helper stopped working.  For posterity, there’s a workaround in a StackOverflow post (http://stackoverflow.com/questions/4710853/using-mvc-htmlhelper-extensions-from-razor-declarative-views)
linked to in the footnote of Scott’s post.

[RESOLVED]Migrate from Web Matrix to Visual Studio 2013

SQL programmer just getting into web-based development.

Wrote a basic CRUD web app using Web Matrix with the understanding that it would run under Visual Studio.

Launched Visual Studio & got numerous error messages when I tried to run the app – mostly of the type "… Are you missing a reference?".

Read a post here that seemed to imply that I might need to manually add "Using …" statements to include libraries that Web Matrix automatically includes, but that VS doesn’t.

As one of my errors was on a line that included a String.IsNullorEmpty() call, I tried adding "@using System.String;" to the top of my code page.

This resulted in the addition of 6 warnings of the type " … has dependencies on a version of .Net Framework that is higher than the target…"

My question: is there documentation somewhere that details the steps needed to accomplish a successful migration from Web Matrix 3 into VS 2013 for Web?

WebMatrix runs under Visual Studion, without a hiccup.

There are some benefits of having both WM and VS working together, for instance in a multiple monitor environment. My suggestion is to figure out what went wrong.

Created a new site from the WM startersite template and create a test environment.  Open it in VS from WM.


is there documentation somewhere that details the steps needed to accomplish a successful migration from Web Matrix 3 into VS 2013 for Web?

You should just use the File » Open » Web Site option in Visual Studio, navigate to your WebMatrix app and Bob’s your uncle. From what you describe, you must have taken a different approach to cause so many issues.

Hi Mike,

Well Robert would appear to be my father’s least-liked brother, as he’s giving me all kinds of trouble.

A screenshot or image attachment would be better, but here’s a mockup up of the problem as it appears while in VS 2013.

code from my cshtml file:

            { return Co.CO_Name; }

error message in VS 2013 reads as follows:

"One or more types required to compile a dynamic expression cannot be found. Are you missing a reference?"

This same message appears when I hover the cursor over the keyword ‘String’ in the code above. When I click on ‘Goto Definition (F12)’ in the right-click menu, it shows me namespace System in mscorlib.dll. Do I have to somehow manually include this dll for
my app to compile?

Just not familiar enough with the process to know what to do next.


Since you’re saying, you’re a SQL developer and getting into the web-development. Let me tell you, ASP.NET is based on C# (VB.NET version is also allowed, Visual C++ might also be an option, since .NET framework can be programmed using Visual C++; but is
very rare). So, these evers are generally coming out from the C#. 

A reference in C# is a declaration to include the Assembly file. As you’re saying the posts tell you to include the files, using a "Using" statement they’re right! Then you get into another problem. So, I would ask you to stop here! And go to the MSDN documentations
for the C#. Since ASP.NET is based on C# (sorry for saying this sentence again), you can learn the C# itself and then ASP.NET won’t cause any trouble to you.

However, the basic assemblies, are automatically included in the .cshtml files and you don’t have to write the using statements for the commonly used namespaces. There is no tough rule in that file. The one you use in WebMatrix (as found in StarterSite template).
But still you can use that line. But since the Visual Studio has an option for Web Forms, MVC etc, the application you might use, would either be an aspx file or a .cs file where you’re required to stick to the plans and the rules. So these applications might
give you a tough time. 

Going into them would require you to have basic understanding of the C# itself. 

http://msdn.microsoft.com/en-us/library/618ayhy6.aspx (C# Reference)

http://msdn.microsoft.com/en-us/library/aa288436(v=vs.71).aspx (C# Tutorials)

Good luck!

It looks like Co.CO_Abbrev_Name is a dynamic type. Try casting it to a string before attempting any string methods on it:

            { return null; }

Hi Mike,

Keep in mind that all this code worked as expected in the Web Matrix environment. Do I need to do explicit typecasting when working with the same code in VS?

If so that sure limits the portability of the code & makes me wonder what the point of supporting Web Pages in VS might be.

Next – is there a way to attach screenshots to these messages? A screenshot of the VS window would sure provide more (hopefully helpful) info than my manual synopsis, and might make obvious what the problem actually is.

Thanks again to you and the other responders.

Yes, just attach the images from the editor. It is alongwith the Big Yellow smiley. That would be a good thing to share. You might need to upload your image on some image storage service provider and then post the link to that image too. 

Hi Afzaal,

Thanks for your replies. I have some familiarity with C# (and some with Java, which works similarly) but would still consider myself something of a novice with C#.

I took you advice & signed up with an image hosting service & so have provided a screenshot of code & error messages. This code builds & works fine in the Web Matrix environment. I don’t remember if I checked to see what the return type was when I wrote
it, but the function works so I’m assuming that the type is string.

Note that the last error message was based on my wild guess that I needed to add an ‘include System.String’ directive. That has been removed now.

Any comments or input based on what you can see?

 Screenshot of Web Matrix Project in VS 2013 Express for Web environment

edit: hmm – I see the image description, but not the actual image.

2nd edit: change from image to link – at least you can see the screenie now.

Does the code still work in WebMatrix?

Yes it does – just fired it up & ran it.

To address your earlier comment more directly – I launched VS by clicking the ‘Launch’ button on the Home ribbon of WM.

When I tried opening the project using File – Open Web Site, VS says (paraphrased) " the site localhost:44861 is using a newer version of .Net (4.0). The project is targeting ASP.NET2.0; if not configured some features may make incorrect assumptions …. 
Would you like the site to be configured for use with ASP.NET 2.0?"

I answered ‘No’ and am now getting additional error messages like this:

Error    4    Feature ‘implicitly typed local variable’ cannot be used because it is not part of the ISO-2 C# language specification    c:UsersEvanDesktopDDC_Inc_WebformApp_CodeDDCHelpers.cshtml    54    9    DDC_Inc_Webform

In WM, under Site-Settings – Select .Net Framework Version – it says .Net 4 (Integrated), & under ASP.Net Web Pages it says: 2.0.30506.0 Version is up to date.

Is this a problem?

Can you clarify what version of VS you are using?

Installed this in approx. June 2014 (ie, a couple of months ago)

From the ‘About’ dialog:

Microsoft Visual Studio Express 2013 for Web
Version 12.0.30501.00 Update 2
Microsoft .NET Framework
Version 4.5.50938

Installed Version: WD Express

Team Explorer for Visual Studio 2013   06156-004-0437007-02394
Microsoft Team Explorer for Visual Studio 2013

Visual Basic 2013   06156-004-0437007-02394
Microsoft Visual Basic 2013

Visual C# 2013   06156-004-0437007-02394
Microsoft Visual C# 2013

ASP.NET and Web Tools   2013.2.50425
Microsoft Web Developer Tools contains the following components:
Support for creating and opening ASP.NET web projects
Browser Link: A communication channel between Visual Studio and browsers
Editor extensions for HTML, CSS, and JavaScript
Page Inspector: Inspection tool for ASP.NET web projects
Scaffolding: A framework for building and running code generators
Server Explorer extensions for Windows Azure Web Sites
Web publishing: Extensions for publishing ASP.NET web projects to hosting providers, on-premises servers, or Windows Azure

ASP.NET Web Frameworks and Tools 2012.2   4.1.21001.0
For additional information, visit http://go.microsoft.com/fwlink/?LinkID=309563

ASP.NET Web Frameworks and Tools 2013   5.1.20409.0
For additional information, visit http://www.asp.net/

Common Azure Tools   1.1
Provides common services for use by Azure Mobile Services and Windows Azure Tools.

NuGet Package Manager   2.8.50313.46
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

SQL Server Data Tools   12.0.30919.1
Microsoft SQL Server Data Tools

What I would do under the circumstances is to create a new site using the Empty Site template, and then keep only the web.config file (and anything in the bin folder). Then copy across all of your existing code. You can use File Explorer to copy the existing
files across. Make sure it runs in WM then try opening that directly from within VS.

Alright – will give that a try

Thanks Mike – that, in typical "roll it up the hill & see if does it again" fashion, worked.

Created a new empty site, re-connected my databases, added in js, css, images, shared & index pages, testing as I went, then finally said screw it & dumped all remaining pages in due to the tediousness.

Built on first try & ran! Nice part was that, in VS, I found a couple of unrelated errors.

Thanks much & thanks also for your web site, which I have referred to, & got good info from, several times while working on this project.

Best Regards

[RESOLVED]razor @functions in a separate file not working – debugger can't see file

When I put @Functions block in a separate vbhtml file in the App_Code directory using visual studio express for web 2013, the debugger doesn’t recognize the file so can’t see it. The @functions block is fine when in the same file from which I call it. I’ve
tried building the website using the debugger but that makes no difference – still can’t see it.

What am I missing? Is there some special syntax I need in the separate vbhtml file? I created a separate helpers file and that was fine but I seem to have a problem with functions. The IDE says its using Razor v2, if that’s of any relevance.

Any help greatly appreciated


I’m not clear what you mean by "can’t see file". If you place your functions or helpers file in App_Code, you have to prefix the helper or function with the name of the file – minus the extension – when you reference the function or helper in another file.
So if you create a function called Print() and you put it in a file called Functions.vbhtml and then place that in App_Code, you will call it in another vbhtml file like this:


Many thanks for your reply

I have the function in the file test78.vbhtnl in the App_Code directory. Calling a function in the @Functions code block elicits the following error:

Error 26 ‘test78′ is not declared. It may be inaccessible due to its protection level.

It doesn’t seem to recognize the file as far as I can see…..I have now run the file and the function is called correctly but I still get the same debug error if I build the website. Weirdly if I create a new empty vbhtml file and copy the functions into
it, I get no error. The only possible diffference is that the original file that is causing the error may have originally been created as a helper file (when selecting a new file option from the menu). I just got rid of the @Helpers code and replaced it with
the @Functions. Seeing these are just text files, I thought it wouldn’t make any difference. Maybe visual studio keeps a record of the types created somewhere?

Intellisense can be a little peculiar with VB sometimes. As to the different file types, there is no difference. They are both .vbhtml files, but are generated from a different template. However, I have been able to replicate the error you reported. I suspect
that’s an issue with the VB compiler/VS combination.

Good to know I not going completely mad! I guess it’s good to have this error documented out there somewhere. A little less hair may get pulled out as a result. Thanks for giving it your attention


[RESOLVED]after update model from database in VS2013 ==> can not resolve symbol "—–"

after "Update Model from Database…" :

rebuilding & unload/reload project can not resolve it!

If you are using designer to update your model try this:

Right click on YourDatabaseModel.Context.tt, YourDatabaseModel.Designer, YourDatabaseModel.tt and Click on Run Custom Tool. (All these are in App_Code folder)

What is the exact error? And what EF do you use?

Right click on …. YourDatabaseModel.tt and Click on Run Custom Tool….. :

! Okeyyyy! resolved . . . :) thanks

• What is the exact error? And what EF do you use? :

! EF5.0 / not exist any error! but
when I move the mouse
over it
, this
message will
as tooltip! (can not resolve symbol "—–")

[RESOLVED]How to display the response from an HTTPHandler on a cshtml page


I have a cshtml page that has a form which sends data to an HTTPHandler. If I run into some kind of error I want to respond with an error message and display it in the same cshtml page. How can I do this? Here is my handler

public void ProcessRequest(HttpContext context)
    var mode = context.Request.Form["mode"];
    var title = context.Request.Form["postTitle"];
    var content = context.Request.Form["postContent"];
    var slug = context.Request.Form["postSlug"];
    var id = context.Request.Form["postId"];
    var datePublished = context.Request.Form["postDatePublished"];

    if (string.IsNullOrWhiteSpace(slug))
        slug = CreateSlug(title);

    if (mode == "edit")
        EditPost(Convert.ToInt32(id), title, content, slug, datePublished, 1);
    else if (mode == "new")
        CreatePost(title, content, slug, datePublished, 1);


private static void CreatePost(string title, string content, 
    string slug, string datePublished, int authorId)
    var result = PostRepository.Get(slug);
    DateTime? published = null;

    if (result != null)
        throw new HttpException(409, "Slug is already in use.");

    if (!string.IsNullOrWhiteSpace(datePublished))
        published = DateTime.Parse(datePublished);

    PostRepository.Add(title, content, slug, published, authorId);

private static void EditPost(int id, string title, string content,
    string slug, string datePublished, int authorId)
    var result = PostRepository.Get(id);
    DateTime? published = null;

    if (result == null)
        throw new HttpException(404, "Post does not exist.");

    if (!string.IsNullOrWhiteSpace(datePublished))
        published = DateTime.Parse(datePublished);

    PostRepository.Edit(id, title, content, slug, published, authorId);

private static string CreateSlug(string title)
    title = title.ToLowerInvariant().Replace(" ", "-");
    title = Regex.Replace(title, @"[^0-9a-z-]", string.Empty);

    return title;

And here is the form in the cshtml file

var post = Post.Current;

    <form name="post" method="post" action="~/admin/post.ashx">
        <input type="hidden" name="mode" value="@mode" />
        <input type="hidden" name="postId" value="@post.Id" />
        <p>Title: <input type="text" name="postTitle" value="@post.Title" /></p>
        <p>Content: <textarea name="postContent">@post.Content</textarea></p>
        <p>Slug: <input type="text" name="postSlug" value="@post.Slug" /></p>
        <p>Date Published: <input type="text" name="postDatePublished" value="@post.DatePublished" /></p>

        <p><input type="submit" name="postSubmit" value="Submit" /></p>


For example: Right now I’m throwing an exception if the post slug already exists. How would I send an error message that says "Slug is already in use" and then display it on the cshtml page preferably right on top of the form? Thanks.

The problem you always have when posting to a different end point is preserving form values. One way to circumvent that issue is to use AJAX to detect if the slug is already in use and prevent form submission.

Hi Mike,

Thanks for the reply. I’m very new to ASP.NET. In fact, I just recently finished reading your book and now I’m trying to build a simple CMS following some other tutorials. Are there any resources you can point me to that would teach me how to do what you

If you are only just starting, I would suggest not using HttpHandlers for processing the form. You should post the form to the same page and process it in a code block at the top. There is no reason why you cannot put your methods into classes in App_Code
and call them from the code block at the top of the page. At least that way, the posted values are still available for re-display if there are validation errors.

For your specific requirement, you can add a separate cshtml file with this in it:

Json.Write(PostRepository.Get(Request["postSlug"]) != null);

Then you can call that via AJAX (using jQuery):

$('#postSlug').on('change', function () {
    $.getJSON('/CheckSlug?name=' + $(this).val(), function (data) {
        if (data) {
            // the slug exists

I use something similar in my CMS: https://webpagescms.codeplex.com/SourceControl/latest#WebPagesCMS/Admin/Widgets/AddHtmlWidget.cshtml

[RESOLVED]compilation error – CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level (EDITED)

I am querying the Bing Maps api through a rest service, based on information from a
MSDN tutorial.

Originally I started out with a test project in Visual Studio, and the code works there as designed.

Now I have copied the 3 files involved to where it is going to live as part of my site, and I get the error message above.

C:Windowssystem32> "C:WindowsMicrosoft.NETFrameworkv4.0.30319csc.exe" /t:library /utf8output /R:"C:WindowsassemblyGAC_MSILSystem.Data.SqlServerCe4.0.0.0__89845dcd8080cc91System.Data.SqlServerCe.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ComponentModel.DataAnnotationsv4.0_4.0.0.0__31bf3856ad364e35System.ComponentModel.DataAnnotations.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.WorkflowServicesv4.0_4.0.0.0__31bf3856ad364e35System.WorkflowServices.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl35e9a55a448f4a257_d715ce01RestSharp.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl33ff72591d8ce7474_b735cf01zxing.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Helpersv4.0_2.0.0.0__31bf3856ad364e35System.Web.Helpers.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.Entityv4.0_4.0.0.0__b77a5c561934e089System.Data.Entity.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Activitiesv4.0_4.0.0.0__31bf3856ad364e35System.Activities.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl332bcbe5a68a37e57_d715ce01Newtonsoft.Json.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3ec6e8f6888e94967_d715ce01iTextSharp.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Drawingv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Drawing.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPagesv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl38cf09cbd58f686f8_d615ce01DotNetOpenAuth.OAuth.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.CSharpv4.0_4.0.0.0__b03f5f7f11d50a3aMicrosoft.CSharp.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Net.Httpv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Net.Http.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xml.Linqv4.0_4.0.0.0__b77a5c561934e089System.Xml.Linq.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILWebMatrix.WebDatav4.0_2.0.0.0__31bf3856ad364e35WebMatrix.WebData.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl39ac13ad668708ef8_d615ce01DotNetOpenAuth.AspNet.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Code.5dgnjctq.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.DynamicDatav4.0_4.0.0.0__31bf3856ad364e35System.Web.DynamicData.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3a8d694dd8b946f8_d615ce01DotNetOpenAuth.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILNuGet.Corev4.0_1.6.30117.9648__31bf3856ad364e35NuGet.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Configurationv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Configuration.dll" /R:"C:WindowsMicrosoft.NETFrameworkv4.0.30319mscorlib.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3846e796b478fff65_726cce01EntityFramework.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystemv4.0_4.0.0.0__b77a5c561934e089System.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Administrationv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Administration.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Runtime.Serializationv4.0_4.0.0.0__b77a5c561934e089System.Runtime.Serialization.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Corev4.0_4.0.0.0__b77a5c561934e089System.Core.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILWebMatrix.Datav4.0_2.0.0.0__31bf3856ad364e35WebMatrix.Data.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Extensionsv4.0_4.0.0.0__31bf3856ad364e35System.Web.Extensions.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3eae21eaa2cb2997_a018cf01Microsoft.Web.Helpers.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Webv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Web.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3f3f60bfd50c835fc_66e2cf01Twilio.WebMatrix.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.Datav4.0_4.0.0.0__b77a5c561934e089System.Data.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModelv4.0_4.0.0.0__b77a5c561934e089System.ServiceModel.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.DataSetExtensionsv4.0_4.0.0.0__b77a5c561934e089System.Data.DataSetExtensions.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Data.Entity.Designv4.0_4.0.0.0__b77a5c561934e089System.Data.Entity.Design.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Activationv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Activation.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Razorv4.0_2.0.0.0__31bf3856ad364e35System.Web.Razor.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Securityv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Security.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Deploymentv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Deployment.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.Servicesv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Web.Services.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.ServiceModel.Activitiesv4.0_4.0.0.0__31bf3856ad364e35System.ServiceModel.Activities.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.ApplicationServicesv4.0_4.0.0.0__31bf3856ad364e35System.Web.ApplicationServices.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Net.Http.WebRequestv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Net.Http.WebRequest.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Web.WebPages.Razorv4.0_2.0.0.0__31bf3856ad364e35System.Web.WebPages.Razor.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.EnterpriseServicesv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.EnterpriseServices.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl31608e86e58aa69f8_d615ce01DotNetOpenAuth.OpenId.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.Web.Infrastructurev4.0_1.0.0.0__31bf3856ad364e35Microsoft.Web.Infrastructure.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl311ca539da81379f8_d615ce01DotNetOpenAuth.OpenId.RelyingParty.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl3c7951ba8b447574_b735cf01zxing.presentation.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl34daf8edb69ddff65_726cce01EntityFramework.SqlServer.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_32System.Webv4.0_4.0.0.0__b03f5f7f11d50a3aSystem.Web.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILMicrosoft.VisualStudio.Web.PageInspector.Loaderv4.0_1.0.0.0__b03f5f7f11d50a3aMicrosoft.VisualStudio.Web.PageInspector.Loader.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.Xmlv4.0_4.0.0.0__b77a5c561934e089System.Xml.dll" /R:"C:WindowsMicrosoft.NetassemblyGAC_MSILSystem.IdentityModelv4.0_4.0.0.0__b77a5c561934e089System.IdentityModel.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl39de30ca2e4929c02_d615ce01Microsoft.Web.WebPages.OAuth.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl38b2c05e5517e33fc_66e2cf01Twilio.Api.dll" /R:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51assemblydl33c4ebd20c8788af8_d615ce01DotNetOpenAuth.OAuth.Consumer.dll" /out:"C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.dll" /D:DEBUG /debug+ /optimize- /w:4 /nowarn:1659;1699;1701;612;618 /warnaserror-  "C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.0.cs" "C:UsersrobertAppDataLocalTempTemporary ASP.NET Filesroota4e278a519f17d51App_Web_testdistance.cshtml.cdcab7d2.s-jejj60.1.cs"

Microsoft (R) Visual C# Compiler version 4.0.30319.18408

for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(3,31): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(4,5): error CS0118: 'System.Web.WebPages.WebPageRenderingBase.Response' is a 'property' but is used like a 'type'
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(4,34): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level
c:UsersrobertDocumentsMy Web Sitesbetestdistance.cshtml(5,14): error CS0122: 'mapdistance.DistHandler' is inaccessible due to its protection level

Googling "Is inaccessessible due to its protection level" does not result in anything useful to me at least.

I am wondering what scenario would cause file to work in one application but not in the other?

testdistance is the razor C code that calls DistHandler class file

mapdistance is the name space inside DistHandler

@using mapdistance;
    string locationsRequest = DistHandler.CreateRequest("Pasedena, MD", "Sparks, MD", "&avoid=minimizeTolls");
    Response locationsResponse = DistHandler.MakeRequest(locationsRequest);
    var rt = DistHandler.ProcessResponse2(locationsResponse);


And DistHandler.cs, at least the first few lines:

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using BingMapsRESTService.Common.JSON;

namespace mapdistance
    static class DistHandler
        static string BingMapsKey = "blahblah";

        public static string CreateRequest(string queryString1, string queryString2, string options)
            string UrlRequest = "http://dev.virtualearth.net/REST/v1/Routes/Driving" +
             "?wp.0=" + queryString1 +
             "&wp.1=" + queryString2 +
             options +
             "&output=json" +
             " &key=" + BingMapsKey;
            return (UrlRequest);

        public static Response MakeRequest(string requestUrl)
                HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    if (response.StatusCode != HttpStatusCode.OK)
                        throw new Exception(String.Format(
                        "Server error (HTTP {0}: {1}).",
                    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
                    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                    Response jsonResponse = objResponse as Response;
                    return jsonResponse;
            catch (Exception e)
                return null;

        static public Route ProcessResponse2(Response locationsResponse)
            int locNum = locationsResponse.ResourceSets[0].Resources.Length;

            Route location = (Route)locationsResponse.ResourceSets[0].Resources[0];
            return location;

            //for (int i = 0; i < locNum; i++)
            //    Route location = (Route)locationsResponse.ResourceSets[0].Resources[i];
            //    var x = location.TravelDistance;


EDIT: I am adding the main program that calls DistHandler in the VS application (which works)

using System;
using System.Net;
using System.Runtime.Serialization.Json;
using BingMapsRESTService.Common.JSON;
using mapdistance;

    class Program
        static void Main(string[] args)
                string locationsRequest = DistHandler.CreateRequest("Hunt Valley, MD", "Pasedena, MD", "&avoid=minimizeTolls");
                Response locationsResponse = DistHandler.MakeRequest(locationsRequest);
                var rt =DistHandler.ProcessResponse2(locationsResponse);
                Console.WriteLine(rt.TravelDistance.ToString() + " " + rt.TravelDuration.ToString());
            catch (Exception e)

You’re right. This problem is because by default the accessibility to the classes in .NET are set to be private. This class that you’re showing doesn’t have anything set to it, so the default properties would be applied. 

static class DistHandler

If you can, you can edit it and make it public. Like this

public static class DistHandler

then you will be able to use it. 

Yes, that did it.

Thank you very much!