My web app is a solution built on top of another solution. The base solution is meant to be a platform for multiple products. For the most part, this works fine, but weird things happen when I create product specific views.
I am using ViewUserControl<SomeViewModel> for my code behind class. In my code behind, I have access to this.Model and all the other goodies I'd expect from this class. But in my ascx file, I get red squiggley lines when I try to access this.Model or other properties defined in ViewUserControl. I also get red squiggley lines when I try to access properties defined directly in my code behind.
What's more interesting is, I don't get any real errors from this. The view renders just fine at run time and does not give me any build errors. But my ascx file thinks there will be errors. If I create the exact same view in the platform namespaces, it works fine. No red squiggles.
I find this to be really annoying. It's not a show stopper by any means, but if I'm going to be using an IDE with intellisense and all that jazz, I'd sure like it to work properly, and pick up the properties that are supposed to be there.
Has anyone else run into this? Do you know of a way to fix this?
Thanks!
Edit
It was requested that I post some code. Here's the code behind:
namespace MyProject.MyProduct.Web.Views
{
public class EditSearch : ViewUserControl<SearchResultsViewModel>
{
public bool IsSearchTypeA()
{
...............
}
public bool IsSearchTypeB()
{
...............
}
}
}
And here's my ascx:
<%
if (!this.IsSearchTypeB())
{
string categoryPageTitle = this.Model.SearchWidgetParameters.Search.CategoryPageTitle;
string categoryPageUrl = this.Model.SearchWidgetParameters.Search.Filters.CategoryPageUrl;
if (!string.IsNullOrEmpty(categoryPageUrl))
{
%> <div id="coid_website_backtoCategoryPageLink"> <%
string tocGuid = this.Model.SearchWidgetParameters.Search.Filters.TocGuid;
if (!string.IsNullOrEmpty(tocGuid))
{
categoryPageUrl += "?guid=" + tocGuid;
}
var backToLink = new HyperLink();
if (this.IsSearchTypeA())
{
backToLink.Text = "Edit Search";
}
else
{
backToLink.Text = "Back to " + TranslatedHtmlTextWriter.Translate(categoryPageTitle);
}
backToLink.NavigateUrl = TransactionOperations.AddContextToUrl(categoryPageUrl.StartsWith("/Browse/") ? categoryPageUrl : "/Browse/" + categoryPageUrl,
WebsiteTransitionType.Default, // Requested: CategoryPage
TransactionOperations.DefaultContextData);
backToLink.RenderControl(this.Writer);
%>
</div>
<%
}
}
%>
Edit
For those of you who are telling me that ASP.NET MVC cannot or does not use code behind, I'm sorry but this is horse hockey. This project has existed for years and there is a widely used product that runs on it. My product is only just recently jumping onto the Platform. The Platform solution uses code behind all over the place, and it works fine. In fact, it works fine at runtime in my product's solution as well, I just have the problem that my ascx file doesn't seem to know about my code behind. Furthermore, ViewUserControl is a System.Web.MVC class. Are you still going to tell me that code behind isn't used in ASP.NET MVC?
Since you are developing MVC you cannot use code behind. Instead, what do you think about adding this at the top of your .acsx file:
<%# Import Namespace="Namespace.Model" %>
Then you can access everything you have in there without so much complication.
ASP.NET MVC does not use code behind. It sounds like you are mixing ASP.NET MVC and ASP.NET WebForm pages.
I suggest you take a look at http://www.asp.net/mvc. It has some great tutorials on getting started with MVC and how it works.
Related
I have an aspx page using only inline C# without a codebehind.
Running from Visual Studio it works, however adding the aspx file to the wwwroot of my local machine gives the message
Compiler Error Message: CS1513: } expected
If I rearrange the code to have the method above the code the message is instead
CS1519: Invalid token 'try' in class, struct, or interface member declaration
I expect it is something to do with server configuration, though I don't really know where to start.
The issue only occurs if there is methods, removing method1 from the below results in correct running.
This is the minimum entire file I was able to cause the error with
html
<%# Page Language="C#" %>
<%
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
string method1(string source)
{
return source;
}
%>
If you're embedding code directly on the aspx page, that code still has to go in a method. Ex:
<%# Page Language="C#" %>
<%
void Page_Load(Object sender, EventArgs e)
{
try
{
string message = "Text";
Response.Write(method1(message));
}
catch
{
Response.Write("Err");
}
}
string method1(string source)
{
return source;
}
%>
By the way - we don't typically put C# code directly in the .aspx file. That's what the code behind system is for.
And we don't typically write directly to the response. It's hard to control where the markup will end up. In Web Forms, it's better to declare a control on the page and then add markup to that (or show/hide controls). Of course if we're going to talk about doing things well - then don't use Web Forms in the first place. It's a dead technology.
I have messed around with the Visual Studio project, running on an earlier version of .NET/C# yields the following error, It seems possible that this is the actual problem I have had
Error CS8059 Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater.
I am unsure why it thinks method1 is a local function and details are hard to come by.
Edit: To solve my problem I put the method in script tags instead of embedded code blocks. The methods then could be used from the embedded blocks and the script tag.
<script runat="server">
string method1(string source)
{
return source;
}
<script>
In order to work on my website on a second computer, I put the project on an usb key and opened it.
The initial project is building correctly, but whenever I try to open it on the second machine, I have a circular reference issue on every single page and can't figure out why.
For each aspx page, I've got:
Circular file references are not allowed. MyPage.aspx. Line 1.
For instance, here's the first line of "Profile.aspx":
<%# Page Title="" Language="C#" MasterPageFile="~/Game/Site.master" AutoEventWireup="true" CodeFile="Profile.aspx.cs" Inherits="Profile" %>
Site.master is actually in the same folder "Game" as all the other pages, and moving this master page in another folder seems to do the trick. However, this doesn't make sens since this is working correctly elsewhere...
Another odd thing: If I keep the project on the usb key (not working if I move the folder) and comment those lines, there is no circular references anymore:
public static class Database
{
private static string conxString = "";
static Database()
{
/*System.IO.StreamReader dataBaseFile = new System.IO.StreamReader("~/Files/DataBase.txt");
conxString = dataBaseFile.ReadToEnd();
dataBaseFile.Close();*/
}
}
Where database.txt contains the local database connection string.
If anyone has any idea please feel free, I really don't know how to address this matter.
*Please note that this is not for a web based application, it's windows based.
I'm building an application where I will need the user to submit simple javascripts that will be run by the application.
The scripts will call functions that are part of the c# build.
An example:
C# code:
public void helloWorld()
{
Debug.WriteLine("hello world");
}
Javascript submitted by user:
helloWorld();
The JavaScript would be parsed by the application at runtime and then call the required functions in my C# code.
Why?..
My app will be used by people with very little programming experience, they enter very simple JavaScripts and the app will attempt to automate a few tasks on the users computer. So my reason for using JavaScript is because it's simple and very easy to learn for someone with little experience.
It sounds like you want a JavaScript parser for your application. To be honest, I dont think what you're doing is possible, considering the context of the script and your code is different. However, this project seems to be doing something that may get you to the right place:
http://javascriptdotnet.codeplex.com/
Personally, I would think making some kind of XML format would be useful (like how UrlRewriter.net makes rewriting URLs easy):
<xml>
<commands>
<!-- Expose a Set of Condition Objects to Select From -->
<if condition="YourApplication.Conditions.RightClickOnDesktop">
<print text="HelloWorld" />
</if>
</commands>
Here is an example running a javascript code which, in turn, invokes a c# method
[System.Runtime.InteropServices.ComVisible(true)]
public class CSharpClass
{
public void MsgBox(string s)
{
MessageBox.Show(s);
}
}
-
Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));
dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "Javascript";
obj.AddObject("mywindow", new CSharpClass(), true);
var result = obj.Eval(
#"
function test(){
mywindow.MsgBox('hello');
}
test();
"
);
Why do you "need the user to submit simple javascripts"? What is your application and what do users need it to do? Why have you decided a scripting language is the way to do this? I'm not saying that is the wrong answer, but that you have not justified this conclusion.
If your app will be used by "people with very little programming experience" I do not recommend implementing a scripting language. Basic concepts like source code and variables are very difficult for non-programmers to understand.
I suggest first investigating macro recording for user scripting. For .NET there is UI Automation and the White automation framework.
This may be a long shot, but I'm using ComponentOne's Spellchecker control for Silverlight. I made a test project, added a plain textbox and a button to it, added the references to the C1.Silverlight and C1.Silverlight.SpellChecker bits, and added the dictionary file to my project.
In the code, I called up the spellchecker on button1's click event and it worked SPLENDIDLY. The spellchecker dialog shows up, and works exactly as it should.
Since that test was successful, I then tried to implement this into my existing project. I've had no success for absolutely NO reason that I can determine, since I used the EXACT SAME code.
Here's the code I use to call the component:
using C1.Silverlight;
using C1.Silverlight.SpellChecker;
using C1.Silverlight.Resources;
public partial class MainPage : UserControl
{
C1SpellChecker spellChecker = new C1SpellChecker();
public MainPage()
{
InitializeComponent();
spellChecker.MainDictionary.LoadAsync("C1Spell_en-US.dct");
}
private void btnSpelling_Click(object sender, RoutedEventArgs e)
{
var dlg = new C1SpellDialog();
spellChecker.CheckControlAsync(txtArticle, false, dlg);
}
The references to C1.Silverlight and C1.Silverlight.Spellchecker are added to this project as well, and the dictionary as been added in the same fashion as well. The issue seems to be that for whatever reason the dictionary is not loading, because the spellChecker.Enabled method returns whether or not the main dictionary has been loaded. If I call MessageBox.Show("SpellChecker Enabled = " + spellChecker.Enabled.ToString()); it shows false, even though the call to load the dictionary is there (as you can see).
What would cause the dictionary to not load? Have I added it to my project incorrectly somehow?
EDIT: I suspect that I have added the dictionary to the project incorrectly, because the ComponentOne reference states:
If C1SpellChecker cannot find the
spelling dictionary, it will not throw
any exceptions. The Enabled property
will be set to false and the component
will not be able to spell-check any
text.
I just don't know what's wrong though because it was added in the same way that it was in the test project (Right clicked on the project.web->Add->Existing Item)
As always, thank you!
-Sootah
You could add the dictionary to the Silverlight app as an embedded resource and then load it using this code:
public MainPage()
{
InitializeComponent();
// load C1SpellChecker dictionary from embedded resource
var asm = this.GetType().Assembly;
foreach (var res in asm.GetManifestResourceNames())
{
if (res.EndsWith(".dct"))
{
using (var s = asm.GetManifestResourceStream(res))
{
sc.MainDictionary.Load(s);
break;
}
}
}
}
I think this post is duplicated in our forum as well, but will answer first here. Please try this:
1) Try to access the .dct file using your browser. If you cannot see it, it's probably because your web server is not serving that type of files. You need ton configure the web server to allow it.
2) verify the URL you are using is correct.http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/86955/241328.aspx#241328
3) Check you are setting everything correctly: http://helpcentral.componentone.com/CS/silverlight_161/f/78/p/81924/227790.aspx#227790
Hope this helps!
We wrote a couple of controls using Microsoft AJAX (cs class + js class). Now I'm thinking about getting rid of it (just use jQuery), as it is bloated and we don't use UpdatePanel. My question is: how should I change my controls? Right now they implement IScriptControl, which uses Microsoft AJAX features (if I understand correctly, ScriptManager & ScriptControlDescriptor classes). What to use instead?
CLARIFICATION. I don't need some more JavaScript libraries - I'm already using jQuery and would like to minimize additional includes (unless they are really small). What I need is replacement for ScriptManager and IScriptControl interface. Things like:
Registering script references (and
not duplicating them).
Instantiating script class associated with control.
Binding my class to DOM element (what is the best way to do that using jQuery, btw?).
Initializing JS class fields.
On the other hand, you can try comet ajax approach, check these samples.
Ok, I finally finished it.
We ended up creating Page descendant with the some code in it to substitute for script manager (see below). We call to it from control's OnPreRender method using control's Page property. Thanks to guys from http://dj.codeplex.com/ for providing example of how to do it.
2, 3, 4. We used jQuery.data method to bind instances of script classes to DOM elements. We execute instantiation, initialization and binding code using jQuery.ready method. This code is added to control in its Render method using AddScript method (see below). Maybe later we would use JavaScriptSerializer for passing values from C# control to javascript classes, but at the moment we do it by hands, passing parameters to javascript class constructor.
HashSet<string> scriptReferences = new HashSet<string>();
HashSet<string> cssReferences = new HashSet<string>();
List<string> styles = new List<string>();
public void AddScriptReference(string url, bool resolve)
{
string realUrl = url;
if (resolve)
realUrl = ResolveClientUrl(url);
if (!scriptReferences.Contains(realUrl))
{
scriptReferences.Add(realUrl);
Header.Controls.Add(
new LiteralControl(
"<script type='text/javascript' src='" +
realUrl + "'></script>"));
}
}
public void AddCssReference(string url)
{
if (!cssReferences.Contains(url))
{
cssReferences.Add(url);
HtmlLink link = new HtmlLink();
//link.Href = ResolveClientUrl("~/jQuery-ui/css/ui-lightness/jquery-ui.css");
link.Href = url;
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Header.Controls.Add(link);
}
}
public void AddCssStyle(string style)
{
styles.Add(style);
}
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
Header.Controls.Add(
new LiteralControl(
"<style type='text/css'>" + styles.Join("\n") + "</style>"
)
);
}
public static void AddScript(HtmlTextWriter writer, string script,
bool executeWhenReady)
{
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
writer.RenderBeginTag(HtmlTextWriterTag.Script);
if (executeWhenReady)
{
writer.Write("$(function(){\n");
}
writer.Write(script);
if (executeWhenReady)
{
writer.Write("});\n");
}
writer.RenderEndTag();
}
jQuery and jQuery UI are very powerful. But you also have access to Moo Tools and Prototype. Which tools in MS AJAX are you using? There are pretty much something comparable in open source non-MS offerings across the board. They just require slightly more labor on your part to implement. You might also look at Telerik and Syncfusions controls. Telerik has a bunch of open source ajax offering for ASP.NET MVC which can be converted to ASP.NET Web Forms pretty easily.
You may be interested in the more lightweight conditional rendering feature in the upcoming release of .NET4 (along with Visual Studio 2010)
http://msdn.microsoft.com/en-us/magazine/ee335716.aspx
If you can wait, it might be a viable solution for you.
I'm not sure you need a replacement for IScriptControl and the Scriptmanager if you want to strictly use jQuery. I recommend you check out some http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html'>tutorials on creating jQuery plugins.