Why cant I access .TrimSafe? - c#

Copied some code from one controller to another. Both files have the same using statements but it wont 'resolve' this issue for me.
On my first file address.Name.Value = source.Name.TrimSafe();
is fine however on my second file. .TrimSafe flags up as does not exist
From the telescense i can choose trim, trimEnd or trimStart where has trimSafe gone to and why cant I use it?

TrimSafe() is not a standard .NET method. This would suggest that TrimSafe() exists as a method in your first file, but never got copied over to the second, and it's a either a private function or non-static function.
I would clean & rebuild your project as well.

It sounds like a namespace issue to me.
Consider this:
// In some file somewhere
namespace firstNamespace
{
Class MyString : String
{
public static TrimSafe() {}
}
}
// The first file you copied from
namespace firstNamespace
{
public void foo() { TrimSafe(); } // Works!
}
namespace secondNamespace
{
public void fee() { TrimSafe(); } // Nope :(
}
To fix the last one, you need to add using firstNamespace; at the top with the other using statements. The reason would be that the first file you're copying from is in the same namespace as where TrimSafe is defined.
In C++ you typically #include all of the referenced .h files for each class that you use.
In C#, you don't add using statements for classes, but instead for namespaces. You only need to be using the namespace, and everything inside of that namespace comes along with it. Anything defined in namespace xyz sees everything else defined in namespace xyz without having to have a using for each class.
Your second file is in a different namespace, and so it has no idea what is in the first namespace, and so it doesn't see TrimSafe.
That's my guess anyways.

Looks familiar, I guess you're doing the Orchard Webshop tutorials as well :)
You need to add a folder in your project called Helpers, and it should have this class in it:
public static class StringExtensions {
public static string TrimSafe(this string s) {
return s == null ? string.Empty : s.Trim();
}
}
Just include the namespace where your method is needed.

Related

System.Console resolving to incorrect namespace

I have a simple console app with the namespace of
something.service.console
The problem is when I try to use
Console.WriteLine("something");
I get compile error: The Type or namespace name "WriteLine" dos not exist in the namespace something.service.console.
So unless I use
System.Console.WriteLine("something");
The C# compiler is trying to resolve the method WriteLine to the incorrect namespace ("something.service.console").
In this scenario is it possible to force the compiler to resolve the Console.WriteLine to the correct namespace "System" (instead of renaming my namespace :))?
Thank you.
The compiler will find the namespace something.service before it finds the namespace System so it will assume that
Console.WriteLine("something");
actually means
something.serviceConsole.WriteLine("something");
and hence your error.
Two possible solutions are to either fully qualify the namespace when you have issues like this:
System.Console.WriteLine("something");
or change the name of your namespace so it's not something.service.console but something.service.somethinglese.
You could "force" it like this:
using SysConsole = System.Console;
Now whenever you use Console in is refering to System.Console
public class Console
{
private void Test()
{
SysConsole.WriteLine("something");
}
}
Note: There really is nothing bad about using:
System.Console.WriteLine()
and you should avoid using classnames that already exist in the .NET Framework.
Using a C# 6 feature "using static" you can change the code to in order to avoid the ambiguous name Console without cluttering the code.
This would make sense, if a lot of System.Console.WriteLine calls occur in the code.
using static System.Console;
namespace SomeNamespace.Console
{
public class SomeClass
{
public void SomeMethod()
{
WriteLine("abc");
}
}
}

In WPF how do I reference and use a cs file from MainWindow.xaml.cs [duplicate]

This question already has answers here:
Using a class file/reference it?
(4 answers)
Closed 6 years ago.
I am creating a WPF and I have also created a side menu for different processes I want to perform. Currently all my code resides in the mainwindoe.xaml.cs. I would like to break out my into seperate files. For example menuitem1 code in one file, menuitem2 code in another file, etc. I prefer this method as I feel it is cleaner and easier to maintain. However I have tried doing Project-->Add Page-->Class but I don't know how to reference the code in the new page. Any help would be greatly appreciated.
Thank you,
Kent
Well, in your class file you have the following:
namespace myNamespace
{
public class MyClass
{
public void MyMethod() { }
}
}
Let's assume that you have this in an assembly named MyDll.dll. You'd use it as follows:
You add a reference to MyDll.dll within the solution explorer
You include the namespace with using myNamespace;
Then you can use your class doing MyClass test = new MyClass();
If you don't add the namespace like Number 2., you'd use your class like:
myNamespace.MyClass test = new myNamespace.MyClass();
You can to put all files in the same or a abstraced namespace. And You have to work with classes in c#.
For example
yourapp.mainwindoe
yourapp.menuitem1
yourapp.menuitem2
Addionally You have to set the classes You Need to Access from another Namespace to at least internal security Setting.
namespace yourapp.mainwindoe
{
class YourClass
{
internal static YourMethod()
{
yourapp.menuitem1.YourOtherMethod();
}
}
namespace yourapp.menuitem1
{
class YourClassOther
{
internal static YourOtherMethod()
{
// do something here...
}
}

Using a VB class from the same ASP.NET web site project in a C# class

I have an ASP.NET web site project where I am using both VB.Net and C# class files. I have included separate sub folders in the App_Code directory for classes of each language.
However, while I can successfully make use of a C# class in a VB class, I cannot do the opposite: use a a VB class in a C# class.
So, to illustrate, I might have two classes such as this:
Public Class VBTestClass
Public Sub New()
End Sub
Public Function HelloWorld(ByVal Name As String) As String
Return Name
End Function
End Class
public class CSTestClass
{
public CSTestClass()
{
}
public string HelloWorld(string Name)
{
return Name;
}
}
I can make use of the CS class in my VB class, with the "Imports" statement. So this works well:
Imports CSTestClass
Public Class VBTestClass
Public Sub New()
End Sub
Public Function HelloWorld(ByVal Name As String) As String
Return Name
End Function
Private Sub test()
Dim CS As New CSTestClass
CS.HelloWorld("MyName")
End Sub
End Class
But making use of the VB class in my C#, with the "using" statement, does not work:
using VBTestClass;
public class CSTestClass
{
public CSTestClass()
{
}
public string HelloWorld(string Name)
{
return Name;
}
}
I get an error that "the type or namespace "VBTestClass" could not be found". What am I missing here?
The best way to look at using/Imports as a shortcut to skip fully qualifying namespaces. The behaviour is the same across vb and c#.
Consider the examples:
fully qualyfying:
void DoSomething()
{
var p = new Interfaces.CPDATA.DataHolders.Placement();
}
skip the namespaces:
using Interfaces.CPDATA.DataHolders;
void DoSomething()
{
var p = new Placement();
var t = new Trade();
}
and a little shortcut trick
using data = Interfaces.CPDATA.DataHolders;
void DoSomething()
{
var p = new data.Placement();
var t = new data.Trade();
}
and a replacement trick:
using t = Interfaces.CPDATA.DataHolders.Placement;
void DoSomething()
{
var p = new t(); // happy debagging
}
As for code files in different languages in ASP.NET App_Code folder: DO NOT USE IT. For:
they won't work when using Web Application project
they will not compile when using csc or vbc compiler in continuous integration project outside of Visual Studio
and they will generally give you a lot of pain on infrastructure side of things.
Best way is to create separate Class Library projects for respective language and use them.
On top of it there are a lot of interesting things going on when running such project from under visual studio and iis. If you're curious you can take a look at various files sitting in
\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\{project name}\{tempname}
it should give you a good idea how asp.net engine combines the code files for aspx pages.
Aimed with that useless information we can now tell that having a CSTestClass class in the same namespace statement "Imports CSTestClass" is not really useful. Good coding style would be to have all of them wrapped in a namespaces statements MyWebProject.VbCode and MyWebProject.CsCode for example. Then statements "using MyWebProject.VbCode" and "Imports MyWebProject.CsCode" would make more sense to the compiler.
I think I found the problem and seems without a reflection you can't do it as a cross reference.
The reason is pretty simple, depends how the orders you define your codeSubDirectories, I think you made it this way:
<codeSubDirectories>
<add directoryName="CSCode"/>
<add directoryName="VBCode"/>
</codeSubDirectories>
As we know each directory will be build to different assembly, and they will be build one by one from top to bottom based on your settings.
So as you have CSCode folder defined first, it will be built first, and then compiler start to build VBCode, so using the CS class is OK as it can find the assembly to reference.
But if you do it reversely, as you mentioned to reference VB code in CS, it firstly build CSCode folder and at that time the assembly of VBCode does not exist so it throw exceptions.
So for make it work with CS using VB, just simply change the folder setting order:
<codeSubDirectories>
<add directoryName="VBCode"/>
<add directoryName="CSCode"/>
</codeSubDirectories>
But then you will lose the ability to use any CS class in VB as this time VBCode compile first.
So my suggestion is go with reflection to load it at run time so that compiler can let you go.
Hope my explanation is clear enough.
Thanks
the using statement is for namespaces not class names, put the VBClass inside a namespace and then, use the "using" statement:
Namespace MyFoo
Public Class VBTestClass
Public Sub New()
End Sub
Public Function HelloWorld(ByVal Name As String) As String
Return Name
End Function
End Class
End Namespace
now in c#:
using MyFoo;
...
THe difference is in how the Imports keyword works compared to the using keyword.
The using keyword can only be used to specify namespaces, while the Imports keyword can also be used to specify classes.
So, Imports CSTestClass specifies that classes, interfaces and enums inside that class should be available, but the class doesn't contain any of those, so the Imports statement is not needed.
When you try to use using VBTestClass it won't work, as VBTestClass is not a namespace.
So, just remove the Imports and using statements, and it should work fine. As the classes are in the same assembly, they already know about each other.

Extension methods in a class library project

I've implemented some extension methods and put those in separate Class Library project.
Imagine I have a simple extension method like this in class library called MD.Utility:
namespace MD.Utility
{
public static class ExtenMethods
{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(#"^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}
}
But nowhere in the web app like the App_code folder or the WebFroms code-behind page can I use this extension method. If I do something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MD.Utility;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string email = "Someone#Somewhere.com";
if (email.IsValidEmailAddress())
{
//To do
}
}
}
The compiler doesn't recognize IsValidEmailAddress() and there's even no IntelliSense support.
While if I put my extension method in the App_Code folder, it's usable in another .cs files in the App_code folder or the WebForms code-behind pages.
Did you remember to add a reference to your class library in the web project ?
You will need that. Other than that, your code looks fine, and should work.
If changes are not getting recompiled when you do a solution rebuild, then it could be the type of reference you are using. If the MD.Utility project is in your web project solution, you should make the reference a "Project Reference." That will cause the build to consider that code as a dependency and therefore rebuild it when you change something. If you just include it as a DLL, then the DLL is considered external and the build will not consider it, even if it is in the same solution.
I was able to resolve it by making the extension module public.
This post may be helpful:
Extension methods in referenced assemblies?
In addition to adding the assembly to the references, what fixed it for me was to explicitly adding it to the file "using MD.Utility".
I've found that this can occur if the Assembly Name and Namespace of the consuming project are the same and the Common library has the same Namespace.
Seems that the compiler gets confused. Try changing them.
As noted elsewhere, you need to add the Common library to each consuming project. And the Module containing the Extension(s) in the Common library must be marked Public. Unlike Classes, Public isn't the default scope for Modules. No idea why.

C#.NET Namespace name does not exist in namespace error - only when using is outside local namespace directive - why?

Using .NET 2.0, C#, Windows Forms development, Enterprise Library 3.1.
We have a project namespace (call it Project). We also have several sub-namespaces inside of that project, for example Project.Namespace1, Project.Namespace2, etc.
In one class, we define enums and such to be used with the Enterprise Library Logging block, like this:
namespace Project.Logging
{
public static class Logging
{
public enum LogPriority
{
// enum values here
}
}
}
In another class, I use the enum values so I need to declare a using statement. Same project, so there is no assembly to reference, right?
If I declare the using inside of the local namespace, like this, it works fine:
namespace Project.SomeName
{
using Project.Logging;
// code referencing the Logging enum
}
However, if I put the using statement outside of the local namespace declaration, I get the "type or namespace name 'LogPriority' does not exist in the namespace 'Project.Logging'... Like this:
using Project.Logging;
namespace Project.SomeName
{
// code referencing the Logging.LogPriority.whatever
}
Why is this? Has anyone run across this before?
I have run into similar (though not exactly the same) problems before when using a class that has the same name as its namespace.
Oddly enough it seemed to compile ok on some developers pc's but not on others. In the end we made sure that no namespace contained a class of the same name.
namespace Project.Logging
{
public static class Logging // this is what caused the probems for me
{
}
}
I also had a wired error. I cannot find any namespace which is coming from different assemblies, but begins with executing assembly name.
Finally, I found out that I have set the target framework to .NET framework client profile.
Yes, most likely you have an unusual value set for the "Default Namespace" in your project properties. I would validate the project configuration.
We ran into this issue before and it all went down to ambiguous naming of the namespace and the class name.
When we tried to have our namespace as Services.Web.xxx and also add in a service reference as Services.Web.xxxx and ALSO add a references to an assembly that was named Services.Web.xxx you can only imagine the problems we ran into.
In the end to fix it we simply did a rename to make sure that there was only one instance of the Services prefix
Also you could do the following and create an alias to LogPriority to LogEnum:
using LogEnum= Project.Logging.Logging.LogPriority;
namespace Project.SomeName
{
internal class MyClass
{
public MyClass()
{
LogEnum enum1 = LogEnum.None;
}
}
}
namespace Project.Logging
{
public static class Logging
{
public enum LogPriority
{
None,
Default
}
}
}
It definitely can make a difference if you have usings inside or outside the namespace. There is a good discussion here, and it is likely to be related to your default namespace settings.

Categories

Resources