Hello I am new to asp.net. I am confused what is the difference between "using MyNameSpace;" and "namespace MyNameSpace". My demo code is as follow...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyNameSpace;
namespace MyNameSpace
{
public partial class DemoPage : System.Web.UI.Page
{
My code here
}
}
In the above code is there any difference between the two highlighted statements or not. If yes then what is it?
Thanks in advance...
Yes, they provide complementary services.
A using directive like this:
using MyNamespace;
Tells the compiler to look in the namespace MyNamespace when resolving simple names - so if you have a type called MyNamespace.Foo, you can just use Foo in your source to refer to it when you've got this using directive.
However, the namespace declaration effectively says, "Anything I declare within this block is in the given namespace". So to declare the MyNamespace.Foo type, you'd use:
namespace MyNamespace
{
public class Foo
{
...
}
}
Do you see? The using directive says that you want to use things in a particular namespace, whereas the namespace declaration is about putting things into a particular namespace.
using is used for creating a "shortcut" to typenames within that namespace. This is only needed when the code you write is within another namespace. namespace is used for defining a namespace:
Example
In file first.cs:
// define the namespace "SomeNamespace"
namespace SomeNamespace
{
// define a type within the namespace
class SomeClass { }
}
In file second.cs:
using SomeNamespace;
// define the namespace "OtherNamespace"
namespace OtherNamespace
{
class OtherClass
{
void SomeMethod()
{
// use the type "SomeClass", defined in the "SomeNamespace" namespace
// note that without the using directive above we would need to write
// SomeNamespace.SomeClass for this to work.
SomeClass temp = new SomeClass();
}
}
}
In the above code sample, the declaration of the temp variable does not need to include the namespace, since it is mentioned in a using directive.
Yes, there is a difference. The namespace statement is used to create a namespace, while the using statement is used to make the compiler regognise an already existing namespace.
In your code the using statement has no effect, as all your code is in that namespace so it already knows about it.
As you have using System.Web.UI, the System.Web.UI.Page identifier could be written as just Page as the compiler knows about the classes in that namespace. If you wouldn't have that using statement, you would need the fully qualified name for the compiler to know where to find the class.
Related
test2.xqy:
import module namespace myNS = "http://test.org/module1" at "./namespace.xqy";
element test
{
}
namespace.xqy:
module namespace myNS = "http://test.org/module1";
declare variable $myNS:srcDoc:="test2.xml";
declare variable $myNS:defaultXMLNS:="http://www.test.com#";
declare variable $myNS:defaultXMLBase:=$defaultXMLNS;
Command line:
$ basex test2.xqy
Stopped at /Users/jack/Documents/xqy/namespace.xqy, 5/53:
[XPST0008] Undefined variable $defaultXMLNS.
I didn't find doc about how to import vars and functions from external modules. So I try it in a intuitive way. The error says there is no definition for $defaultXMLNS. I did define it, but with a namespace prefix.
You forgot to define the namespace on the right-hand side of the assignment:
declare variable $myNS:defaultXMLBase:=$defaultXMLNS;
(: ^ no namespace defined :)
Thus, $defaultXMLNS is searched in the default namespace, where it is not registered. Apply the namespace instead:
declare variable $myNS:defaultXMLBase:=$myNS:defaultXMLNS;
If you do so, you can later access the value like this:
import module namespace myNS = "http://test.org/module1" at "./namespace.xqy";
element test
{
$myNS:srcDoc
}
Can anybody help me with explaining this error message please:
system.componentmodel.composition.changerejectedexception
The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error.
The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) No exports were found that match the constraint:
ContractName Itok.BusinessLogic.Interfaces.IFolderService
RequiredTypeIdentity Itok.BusinessLogic.Interfaces.IFolderService
Resulting in: Cannot set import 'Itok.Web.Photos.Presenters.DefaultPresenter._folderService (ContractName="Itok.BusinessLogic.Interfaces.IFolderService")' on part 'Itok.Web.Photos.Presenters.DefaultPresenter'.
Element: Itok.Web.Photos.Presenters.DefaultPresenter._folderService (ContractName="Itok.BusinessLogic.Interfaces.IFolderService") --> Itok.Web.Photos.Presenters.DefaultPresenter
Here is the IFolderService.cs:
using System;
using System.Collections.Generic;
using Itok.Entities;
namespace Itok.BusinessLogic.Interfaces
{
public interface IFolderService
{
List<Folder> GetFriendsFolders(Int32 AccountID);
void DeleteFolder(Folder folder);
List<Folder> GetFoldersByAccountID(Int32 AccountID);
Folder GetFolderByID(Int64 FolderID);
Int64 SaveFolder(Folder folder);
}
}
And this is the exporting class definition, FolderService.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Itok.BusinessLogic.Interfaces;
using System.ComponentModel.Composition;
using Itok.DataAccess.Interfaces;
using Itok.Common;
using Itok.DataAccess;
using Itok.Interfaces;
using Itok.Entities;
namespace Itok.BusinessLogic
{
[Export(typeof(IFolderService))]
[Export(typeof(ICache))]
public class FolderService : IFolderService
{
[Import]
private IFriendRepository _friendRepository;
[Import]
private IFolderRepository _folderRepository;
[Import]
private ICache _cacheService;
public FolderService()
{
MEFManager.Compose(this);
}
public List<Folder> GetFriendsFolders(Int32 AccountID)
{
List<Friend> friends = _friendRepository.GetFriendsByAccountID(AccountID);
List<Folder> folders = _folderRepository.GetFriendsFolders(friends);
folders.OrderBy(f => f.CreateDate).Reverse();
return folders;
}
public void DeleteFolder(Folder folder)
{
if (_cacheService.Exists(folder.AccountID.ToString()))
{
_cacheService.Delete(folder.AccountID.ToString());
}
_folderRepository.DeleteFolder(folder);
}
public List<Folder> GetFoldersByAccountID(int AccountID)
{
List<Folder> cachedFolders = _cacheService.Get(AccountID.ToString()) as List<Folder>;
if (cachedFolders != null)
{
return cachedFolders;
}
else
{
cachedFolders = _folderRepository.GetFoldersByAccountID(AccountID);
_cacheService.Set(AccountID.ToString(), cachedFolders);
return cachedFolders;
}
}
public Folder GetFolderByID(Int64 FolderID)
{
return _folderRepository.GetFolderByID(FolderID);
}
public Int64 SaveFolder(Folder folder)
{
return _folderRepository.SaveFolder(folder);
}
}
}
I thank you prior to any help for saving my time.
The error message means that MEF is looking for a class that is exported with the interface IFolderService but there isn't one in the container.
To investigate this, firstly check that there is a class that exports that interface and if there is, then look into whether that class being picked up by the container or not and thirdly, if neither of those resolve the issue, look into whether the class that is exported with the interface IFolderService has some other imports that can't be satisfied.
Finally, I found the Solution for the problem. It has got has nothing to do directly with IFolderService that MEF was pointing to. The App has dependencies on a component (FolderService) in the business logic, which in turn is dependent upon an interface ICache, and an implementation wrapper, Cache.cs. ICache, specified by a contract name Itok.Interfaces.ICache, had been exported FOUR times (on just one Import). This was left unnoticed while I was trying to scale the solution. MEF couldn't tell which Export to use. The real problem is that MEF was pointing to a class two levels upper the chain!
Thanks TomDoesCode for looking at the problem, and I hope this will help others who'll get a similar problem.
A long term solution for this problem would be if you have many Exports that will satisfy an Import, you'll probably have two options:
I) Change the [Import] with [ImportMany]. Then during runtime, decide which import to use for the contract. Ask yourself if just picking up the first available, or using one at a time in random.
II) Use [ImportMany] in conjunction with Metadata in order to decide which Import to use.
I created a website and would like to have a class to centralize all the code that I use frequently in the entire project, for instance, a method to connect to the database. Question: after I create this class, on the App_Code folder, how can I use it in the aspx.cs pages? I mean, should a reference it? Should I inform add a namespace?
Thanks!
Create the class file as public and you will be able to access the class file at any part of your project.
namespace applicationName
{
public class DataManager
{
public static DataTable GetData(StringBuilder sql)
{
}
}
}
you can access the DataManager from your code.
DataManager.GetData(SQL);
Yes, put your class in a namespace and consider making the class static if possible, that way it can be used in code throughout your project without instantiating the class. This is common for utility classes that pass in objects and do work with them, but do not need the actual utility method to be part of a class instance.
For example:
namespace My.Utilities
{
public class static ConnectionStringHelper
{
public static string GetConnectionString()
{
// Logic here to actually get connection string
return yourConnectionString;
}
}
}
Now, code in your project just needs to reference the My.Utilities namespace and then can use the GetConnectionString() method, like this:
using My.Utilities;
string connString = ConnectionStringHelper.GetConnectionString();
You can do it a number of ways. Technically you can drop the namespace completely and your code becomes a free for all (accessible from anywhere naturally). I prefer to use namespaces personally, but I have seem people just avoid them.
If your class Foo is in Some.Namespace, you can reference it as such:
Way one:
Some.Namespace.Foo foo = new Some.Namespace.Foo()
Way two: Use the "Use" command
If your class is inside of Some.Namespace and you don't want all the junk preceding your class name, you can add:
using Some.Namespace;
to the top of your file.
I may be miss understanding what you are saying. If you are talking about setup, you can make a centralized class that manages everything. This class can be a singliton. For instance:
class MyClass
{
public static MyClas Singliton;
static MyClass()
{
Singliton = new MyClass();
}
public void someFunction()
{
}
}
This will create and manage a single reference to your class so that everything is managed out of there (hence being called a "singleton"). As a result, you can access it by:
MyClass.Singliton.someFunction();
There are ways to protect your singliton instance from being overwritten, but this is the basic idea. If you want to manage stuff out of a single location without recreating classes, singletons are the way!
http://msdn.microsoft.com/en-us/library/ff650316.aspx
If the class is wrapped in a namespace, then yes, you'll need a using statement that matches your namespace. For instance, if your class is wrapped in a namespace like so:
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
then anywhere you want to use that class you'll need to add
using My.Namespace;
to the top of the files where you want to utilize the class(es) you've defined. Then you can use your class as you would expect:
Foo foo = new Foo(); //for a new instance
Foo.Bar(); //for a static method
This is, of course, assuming that the class is in the same assembly and you don't want to mess with adding it to the GAC.
Alternatively, if for some reason you don't to use a using statement you can use the fully qualified name of the class:
My.Namespace.Foo foo = new My.Namespace.Foo(); //for a new instance
My.Namespace.Foo.Bar(); //for a static method
This is most useful if you have namespaces that conflict, for instance if you had
namespace My.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere, and
namespace MyOther.Namespace
{
public class Foo
{
//Methods, properties, etc.
}
}
somewhere else, but needed to use them both in the same scope.
I've been exploring the System.Web.Routing namespace, playing with constraints and such, but I can't see a way to implement this.
I'm working on an ASP.NET website (non-WAP, non-MVC) using the WebPages/Razor framework.
I'm trying to implement a form of "nested routing", where a route can contain child routes that are only attempted if the parent matches; each child attempting to match the "remainder" of the URI. A "depth-first" route match search, if you will.
routes.Add(new ParentRoute("{foo}/{*remainder}", new[] {
new ParentRoute("{bar}/{*remainder}", new[] {
new Route("{baz}"),
new Route("{zip}"),
}),
new ParentRoute("{qux}/{*remainder}", new[] {
new Route("{baz}"),
new Route("{zip}"),
}),
));
I've excluded necessary constraints/handlers (among other parameters) for brevity.
In any case, each step descending through the tree would match the {*remainder} tail of the URI. If a branch fails, it moves up and on to the next, essentially testing something like:
foo
foo/bar
foo/bar/baz
foo/bar/zip
foo/qux
foo/qux/baz
foo/qux/zip
Now, I'm certainly not asking "please to write teh codez", but rather a gesture in the right direction.
Where would I want to be looking in the API in order to begin implementing such a feature? I can find countless tutorials and information on writing routes, constraints, etc., but not on extending the routing engine.
Addendum
I'll just keep adding as warrants
Please note, I am aware that URL generation from a "routing tree" such as this would be complicated; it is not something I intend to implement.
I just realized a sort of iterative route generation could suffice; so I guess I'll post that as a possible answer shortly. Nope, it wouldn't. Too many edge cases.
I have the following code but there is one point I am not sure how you want to handle it: do you know how many child can have a route at the maximum?
In the Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add(new Route("test/{path}", new RouteValueDictionary { { "path", string.Empty } }, new TestingRouteHandler()));
}
The TestingRoutHandler class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;
using System.Web.UI;
using System.Web.Compilation;
namespace WebApplication1
{
class TestingRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//This is where you should treat the request, test if the file exists and if not, use the parent part of the url
string aspxFileName = string.Format("~/{0}.aspx", requestContext.HttpContext.Request.Url.PathAndQuery.Replace("/", string.Empty));
return (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath(aspxFileName, typeof(Page)) as Page;
}
}
}
i am using asp.net framework 4 and i have created brand new project and below is the code and when i compile the proj i get this below errors... i have already spent good amount of time but not sure whats going on here...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace aspnet_membership_proj
{
public partial class SiteMaster : MyBaseMasterPage
{
public void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl myJs = new HtmlGenericControl();
myJs.TagName = "script";
myJs.Attributes.Add("type", "text/javascript");
myJs.Attributes.Add("language", "javascript"); //don't need it usually but for cross browser.
myJs.Attributes.Add("src", ResolveUrl("~/Scripts/JScript.js"));
this.Page.Header.Controls.Add(myJs);
}
}
}
errors:
The name 'ResolveUrl' does not exist in the current context
'aspnet_membership_proj.SiteMaster' does not contain a definition for 'Page' and no extension method 'Page' accepting a first argument of type 'aspnet_membership_proj.SiteMaster' could be found (are you missing a using directive or an assembly reference?)
Check your MyBaseMasterPage class. That is where the problem lies.
Also, Make sure that your MyBaseMasterPage class derives from System.Web.UI.MasterPage.