Normally we all do use using System.Linq; and using System.Data.Linq; for example on the code-behind and expect we can reach the members of these namespaces from Source Code like <%= Something.First()%> but when I wrote it, asp.net said it couldn't find First() in the context and I had to add <%# Import Namespace="System.Linq" which looked very weird to me but it worked out. Since they are targeting at the same class why they both need separate namespace importing.
Code-behind :
using System;
using System.Data.Linq;
using System.Linq;
using System.Text
namespace Something
{
class Items : System.Web.UI
{
//...
}
}
but also I need to add the same Linq namespace on the Html Source part
<%#Import Namespace="System.Linq"%>
Do I know something wrong or this is some kind of bug in asp.net. I thought when the page is compiling, asp.net combines these two classes and converts html source code into cs class and indicates the control in Control c= new Control(); hierarchy.
Thanks in advance.
P.s : I am trying to reach for example First() in Items.aspx and everything I mentioned about an asp.net page which is Items.aspx
You must specify your namespaces in both places. It's normal behavior. That's needed by the compiler in order to pre-compile the aspx page and the code-behind page separately, before merging them into one class and doing the actual compilation.
By default, a few common namespaces are already included in the aspx page, so you don't need to import them. But in your case you need to import Linq.
EDIT: And as Joel Coehoorn said, you can add to that list of default namespaces in Web.config, should you not want to manually add them in the aspx pages.
Check your web.config file for a namespaces section and make sure System.Linq is listed there.
Documentation:
http://msdn.microsoft.com/en-us/library/ms164642.aspx
I would not use First in markup, if you still want to do it , make a wrapper in your code behind , like SomeMethod or SomeProperty and access it from markup as <%=SomeProperty %>
First is not a method on the class, but an extension method defined in the System.Linq namespace. Even though you may also use this extension method within the code behind, this doesn't mean that the ASP.NET compiler can find the extension method without a hint - hence the <%# Imports ... %> directive.
Note that the ASP.NET compilation (i.e. of the aspx) is separate from the compilation of the code behind. The latter runs when you build the project; the former runs when you either access the page for the first time, or pre-compile it using "Publish..." or a web deployment project. Hence each compiler needs to be told where to find this extension method if you use it in both places.
Related
I have several internals object in an API.
I can access them from the code behind but I can't access them from the asp page like :
<% API.InternalObject.Method %>
Is there a way to set the namespace like namespace project {} but for the ASPx file ?
You can use [assembly: InternalsVisibleTo("Other.Assembly")] attribute.
But I would first think if you really need it.
I've used it in the past to make it possible to test internal classes in my test projects.
Is it possible to add a using declaration to a namespace globally?
For example, I want all of my classes under the "MyApp.Models" namespace to include the namespace System.Linq.Dynamic.
In asp.net you can do this for view by adding the namespace in the web.config. Is there a way to do this for class files as well?
No. It is not possible to add a global using declaration to a C# project. You must specify the complete set of using in each .cs file
It's not possible to do what you want with obvious functionality but you could create a template that you generate your classes from and do that by namespace, the templates could include the using and this would give you the desired effect.
You could do this with basic T4 templates or something like resharper also has this functionality.
However it is a bit pointless, lots of productivity tools will bring in the using statements you need given code you write, resharper and others do this, so it is not neccessary to have a template that does this as you may end up in each namespace not using the declaration then find yourself having to delete it !
Theres not really an issue with having using statements that are unused by the way its just messy.
Ooh just in case you aren't sure what t4 templating is here is a quick link
I don't believe this is possible out of the box, but you could certainly automate with a Visual Studio plugin or a plugin for a tool like Code Rush.
What is the equivalent command to PHP's include() in C# ?
For example, PHP's include is used as so : include("ex.php");
Can I do the same in C#?
If you mean in ASP.Net using C# you can create a user control (.ascx) and add it in your .aspx page.
If you are doing MVC you can create a partial view.
The closest thing I can think of would be after creating an ascx user control named "MyUserControl"
in your page_load or pre_render :
MyUserControl cont = new MyUserControl();
this.Controls.Add(cont);
There is no such thing in C#. It's not a scripting language, so including a block of script wouldn't make sense.
What are you trying to accomplish? There are ways to do similar things in C#.
There is no direct equivalent. You use references to "link" with other CLR assemblies (access their type information), and the using directive to import namespaces.
For example, the FontCollection class is in the System.Drawing.dll assembly, and the System.Drawing.Text namespace. So you would add System.Drawing as a reference, and add the line:
using System.Drawing.Text;
I'm not sure, if this is what you want to do. But just for the case, maybe you have a look at:
<%
Response.WriteFile( "YourFile.whatever" )
%>
In addition to previous answers mentioning the using Directive and adding references to assemblies to your project (or at command line when compiling) there is a way to load other compiled .NET assemblies at runtime.
Assembly.Load will load an assembly (compiled c# file/.dll) into memory, allowing you to find and use types within that assembly. This can be used when building a plugin architecture. You publish an assembly with an interface for a plugin contract. Plugin makers can link to that that assembly and implement your interface. Your application can then load plugin assemblies, check for any types implementing your plugin interface and load and use those types into your application.
The only thing comparable in C# is using, which imports namespaces defined in assemblies referenced from the project. You cannot "include" a file in the sense that you dump the content right into your code.
For example, if your project references the System.Xml assembly, then the following code would allow you to access all of the classes in that namespace without fully qualifying their names:
using System.Xml;
This will let you use the type System.Xml.XmlDocument, for example, by specifying it as XmlDocument instead of its full type name System.Xml.XmlDocument.
There is no such thing in C#.
You're going to want to create an instance of a C# class and use that to invoke methods/attributes from other 'packages' (C# classes).
You can also use a using direction to be able to references assemblies from other projects.
Using is vaguely similar. It references another class that can then be used from that file, but it doesn't include the contents of that file directly inline.
using system;
(right at the beginning of a file)
Use this for c#
#RenderPage("header.cshtml")
This is taken from here:
http://www.w3schools.com/aspnet/showfile_c.asp?filename=try_webpages_cs_002
Although I know this post is old, but people stubming to this post can refer to it.
Well, here is what I did ... not sure if this is the right way, but it works...
In the .ascx File, specify a div as container to received the contents of included file.
<div id="containerForSomeMarkup" runat="server"></div>
In the .ascx.cs file, initialise this in the onInit() method or other methods as required...
containerForSomeMarkup.InnerHtml = File.ReadAllText("Full path of file to be included");
Coming from PHP world, for me, this approach helps keep the markup organized and intelligble...
The using keyword is what you're looking for.
Ok, I have a c# project named BusinessLayer which produces an assembly called BusinessLayer and the namespace is BusinessLayer.
Inside of this project, I am using folders to store code. One folder is called FilterElements and it has folders called FilterKeyReversal, FilterRandom and FilterToday.
Let's take the example of the FilterRandom folder. It has a class called LessThan10DaysGreaterThan50A with a namespace of BusinessLayer.FilterElements.FilterRandom and a single public static method called RunFilter();
In the code behind page of the website that is consuming this method, I have the using statement, Using BusinessLayer. I also have another using statement, using BusinessLayer.FilterElements.
I would think that to expose the RunFilter() method of the LessThan10DaysGreaterThan50A class, I could use the following syntax: FilterRandom.LessThan10DaysGreaterThan50A.RunFilter(), however I get the following error: The name FilterRandom does not exist in the current context.
If I use the following syntax inline, the error goes away: BusinessLayer.FilterElements.FilterRandom.LessThan10DaysGreaterThan50A.RunFilter(), or if I use a using statement of: Using BusinessLayer.FilterElements.FilterRandom, the following syntax works: LessThan10DaysGreaterThan50A.RunFilter().
I would rather use FilterRandom.LessThan10DaysGreaterThan50A.RunFilter() as it seems to make code more readable. If I use an alias with the following syntax of using FilterRandom = BusinessLayer.FilterElements.FilterRandom, I can get what I want, but don't really like the idea of using an alias since it can lead to confusion down the line.
I thought that since my BusinessLayer namespace has nested namespaces, I'd be able to pick up the remaining namespace, but I can't seem to get it to work. Anybody know how to make this work without using an alias, or am I going to have to use the entire namespace name every time?
Thanks.
Nope, it doesn't. I know it's very irritating.
My first try at solving this issue (I had the same issue) was adding these usings:
using FilterRandom = BusinessLayer.FilterElements.FilterRandom;
The problem then becomes that you have to add one for every sub namespace you want to include, and that becomes a mess.
How I permanently solved this is by changing the namespaces in the project so that, in your example, FilterRandom would e.g. be in BusinessLayer.
The problem you are actually seeing is that you have too many namespaces. It isn't strange it happens. They are a great way of organizing your code and classes and it's not that hard to have it go out of hand. What I mean by changing the namespaces is that I merged many small namespaces into larger ones. This sometimes means renaming classes, but my opinion is that the class name on itself should be meaningful, without the namespace prefix.
This way, I permanently solved these issues in my project (60kloc) and it worked out great.
One thing I have noticed a lot of back and forth on is where using statements should be placed in a C# code file- whether its in the outermost scope or inside a namespace. I understand that the location of the using statement affects the scope of the references within that file, but what I don't understand is why, in most cases, someone would ever want their using statements inside their namespace.
In almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seems/(is?) useless. If one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense, yet I still see plenty of cases of this being done even in files with one namespace. Why?
using System;
namespace MyNamespace
{
using System.Text;
public class MyClass {
// ...
}
}
An example of this being done throughout a project seemingly unnecessarily is the ASP.NET MVC source.
Putting "using" at the top of the files is the default way of Visual Studio. However, the recommended approach is putting the "using" statements inside of the namespace. Even MS's stylecop catches this and says the default way of VS is wrong.
Both techniques work fine.
StyleCop Rule says:
Placing multiple namespace elements
within a single file is generally a
bad idea, but if and when this is
done, it is a good idea to place all
using directives within each of the
namespace elements, rather than
globally at the top of the file. This
will scope the namespaces tightly, and
will also help to avoid the kind of
behavior described above.
It is important to note that when code
has been written with using directives
placed outside of the namespace, care
should be taken when moving these
directives within the namespace, to
ensure that this is not changing the
semantics of the code. As explained
above, placing using-alias directives
within the namespace element allows
the compiler to choose between
conflicting types in ways that will
not happen when the directives are
placed outside of the namespace.
Here's some links for further review:
Should 'using' statements be inside or outside the namespace?
Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic?
http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx
http://blogs.msdn.com/sourceanalysis/pages/sa1200-usingdirectivesmustbeplacedwithinnamespace.aspx
I'd never even seen/heard of this practice until I started using StyleCop and would get flagged by rule SA1200, which I now just disable. It's odd that the .cs files that Visual Studio creates as part of a new project violate this rule by placing the using directives at the very beginning of the file, outside of the namespace.
edited, with my head hanging in shame
Ahh! The using statement you're refering to is used to import a namespace, not to wrap an IDisposable object!
Very different, ambiguous terms... you had me confused :-)
Personally I like them outside the namespace at the top of the file; but it's probably due to me switching between C# and VB.NET.
I like to organize my projects into 1-file-per-class, no inner (nested) classes, and only one class per namespace (per file) . In this situation the location of the using statement is irrelevant whether inside or outside the namespace.
The iDesign C# coding standard is a solid standard to follow (or to derive your own from). It recommends keeping the using statements outside the namespace as item #14. But it's all down to your company / project's convention