Here is my Enums.cs file that exists in a CPSLibrary Class Library:
namespace CPSLibrary.CPSEnums
{
public enum GoalType
{
STRATEGIC = 1,
TACTICAL = 2
}
}
In a code behind file within a web application that references CPSLibrary, I'm doing the following:
using CPSLibrary;
/* ... farther down the page ... */
proj.Goal == CPSLibrary.CPSEnums.GoalType.STRATEGIC;
That will work, but if I try to just reference it like CPSEnums.GoalType.STRATEGIC it won't. Additionally, if I add "using CPSLibary.CPSEnums" I can then reference it simply as GoalType.STRATEGIC.
What do I need to do to get this to recognize CPSEnums.GoalType.STRATEGIC ?
Oddly enough, other classes with the CPSLibrary Class Library can reference it as CPSEnums.GoalType.STRATEGIC just fine.
Bonus Question: in this example, does "CPSEnums" have a technical term? "Container" or something like that? Or is it just a part of the Namespace with no separate terminology?
TIA
Try changing your using statement to this...
using CPSEnums = CPSLibrary.CPSEnums;
This should allow you to reference it the way you want...
/* ... farther down the page ... */
proj.Goal == CPSEnums.GoalType.STRATEGIC;
Because your namespace name is CPSLibrary.CPSEnums, so you can even write like:
using CPSLibrary.CPSEnums;
....
proj.Goal == GoalType.STRATEGIC; //NO NAMESPACE NAME
when you write using CPSLibrary, you refer to the "parent" namespace of your defined one. This is perfectly valid. But to access your enum type, you need specify its namepsace, and its namespace is: CPSLibrary.CPSEnums
Try this:
namespace CPSLibrary
{
public static class CPSEnums
{
public enum GoalType
{
STRATEGIC = 1,
TACTICAL = 2
}
}
}
var x = CPSEnums.GoalType.STRATEGIC;
Related
When making the file, I am thinking of selecting a console application. But which target framework do I choose? Is this incorrect? Also, I am having trouble figuring out how to make a method in the class Program that is able to be called in the Main method. Can someone give me some advice?
one thing you can do is using interface to keep your code clean; for example :
you create an interface like this:
public interface IQuestionSolving
{
public void Solution();
}
you create some question class :
public class Question1 : IQuestionSolving
{
public void Solution()
{
}
}
and you use it like this :
static void Main(string[] args)
{
IQuestionSolving solve = new Question1();
solve.Solution();
Console.ReadKey();
}
now each time you solve a question you need to change
IQuestionSolving solve = new Question1();
to
IQuestionSolving solve = new Question2(); // 2 3 4 .. etc
you can extract your project as template so you dont have to do this each time .
or you can just use one solution and many classes .
This will get you started with Visual Studio:
Create a new console project - use the latest version of C#, which is probably what VS will "suggest" to you. Currently that's .NET 6 or .NET 7
A modern (net 6 or later) console app lets you start writing code immediately. You could create a method and then call the method right in this little Program.cs file that you start out with. However, I would probably do the following instead:
a) Create a new class for your "problem"
b) In that class create a method that solves the problem.
c) In your Program.cs add a using statement to use the namespace that your new class uses
d) In your program.cs instantiate that class and call its method/test its method
Here is an example:
Program.cs
using LeetCodeProject;
var solver = new Problem001_CalculateSquareRoot();
var solution = solver.calculate_square_root(8);
Console.WriteLine(solution);
Console.WriteLine("Press any key...");
Console.ReadKey();
Problem001_CalculateSquareRoot.cs (solves one leetcode problem)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeProject
{
public class Problem001_CalculateSquareRoot
{
public double calculate_square_root(int number)
{
double root = 1;
int i = 0;
while (true)
{
i = i + 1;
root = (number / root + root) / 2;
if (i == number + 1)
{
break;
}
}
return root;
}
}
}
Now you can just add new classes for each problem, and as you work on them just edit Program.cs to create the class you are currently working with and calls its solution methods.
I can (and would - and actually have, in similar cases) implement an interface for this, but the goal here is not to get into OO design principles, but just to get you started so you can get to work on the leetcode problems...once you have a few done you can start thinking about better organization of the code.
I have tried to search for this but every example I find has a problem like them actually having the same namespace as their class or something.
I am simply trying to start using Linq. When I add new item Host is localhost. I have my database in Visualstudio and my project name is different than the DataContext name but I can't get it initialized. I get error:
'LinkedContext' is a namespace but is used like a type'
here is code...
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedContext db = new LinkedContext();
}
}
}
LinkedContext doesn't work? In settings of the Database Diagram it says the Entity Namespace is 'LinkedContext' So what am I missing. I thought I saw you could run that one line of code to connect your database that is already in VisualStudio due to adding a new item and then start playing with it? I just want to be able to practice with a database! Do stuff like:
var example = from x in example.Table
orderby x.field
select x;
you need using LinkedContext at the top of your file. the error you’re getting is telling you LinkedContext is a namespace but you’re treating like a type, ie a class. once you define it at the top you can then use the type that you need within that namespace.
added "using LinkedContext" to the top of code then also had to use LinkedDataContext not just LinkedContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedContext;
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedDataContext db = new LinkedDataContext();
var example = from x in db.employees
orderby x.employee_id
select x;
foreach (var whatever in example)
{
Console.WriteLine(whatever.name);
}
using Foo.Uber;
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
// I want to reference the outer "absolute" Foo.Uber
// but the compiler thinks I'm refering to MyStuff.Foo.Uber
var x = Foo.Uber.Bar();
}
}
}
How could I solve this? Just moving the using statement inside my namespace doesn't help.
You can do this using a namespace alias qualifier (typically global::) to refer to the default / root namespace:
global::Foo.Uber
Alias the namespace in the using statement:
using ThatOuterFoo = Foo.Uber;
...
...
//Some time later...
var x = ThatOuterFoo.Bar();
You can use using alias directives
using Outer = Foo.Uber;
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
var x = new Outer.Bar(); //outer class
}
}
}
You can actually specify the full path via the root namespace
var x = global::Foo.Uber.Bar();
Namespaces Overview
A namespace has the following
properties:
They organize large code projects.
They are delimited with the . operator.
The using directive means you do not need to specify the name of the
namespace for every class.
The global namespace is the "root" namespace: global::system
will always refer to the .NET
Framework namespace System.
I prefer this over aliases because when you read it, you know exactly what is going on. Aliases can be easy to misunderstand if you skip over the definition.
Using Aliaseseseseseses
using Foo.Uber;
using FooUberBar = Foo.Uber.Bar
namespace MyStuff.Foo
{
class SomeClass{
void DoStuff(){
// I want to reference the outer "absolute" Foo.Uber
// but the compiler thinks I'm refering to MyStuff.Foo.Uber
var x = FooUberBar();
}
}
}
You can assign an alias in your using directive as described on MSDN.
How can I add a namespace to a c# project? I am a beginner.
if(!string.IsNullOrEmpty(result))
{
CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);
EmailsList = helper.Extract_Emails;
}
My Form1 needs to use the namespace below:
// this is the file that I need to add
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Coderbuddy
{
public class ExtractEmails
{
private string s;
public ExtractEmails(string Text2Scrape)
{
this.s = Text2Scrape;
}
public string[] Extract_Emails()
{
string[] Email_List = new string[0];
Regex r = new Regex(#"[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}", RegexOptions.IgnoreCase);
Match m;
//Searching for the text that matches the above regular expression(which only matches email addresses)
for (m = r.Match(s); m.Success; m = m.NextMatch())
{
//This section here demonstartes Dynamic arrays
if (m.Value.Length > 0)
{
//Resize the array Email_List by incrementing it by 1, to save the next result
Array.Resize(ref Email_List, Email_List.Length + 1);
Email_List[Email_List.Length - 1] = m.Value;
}
}
return Email_List;
}
}
}
Well, add a using statement in your .cs page
using Coderbuddy;
Then your code can access the methods exposed by this type.
OR, put your winform .cs file in the same namespace (not a recommended idea)
Put this at the top of your code-behind file:
using Coderbuddy;
Read this introduction to namespaces and assemblies on MSDN.
(I am assuming you need to add that second file to your own project. If it is already part of another project in your solution, then add it as a project reference as Darkhydro has answered.)
You don't need to explicitly add namespaces to your project. The namespace declaration in line 6 of the file that you need to use does it implicity.
For this example, add a blank file called ExtractEmails.cs to your project (the convention if a file contains only one class definition is to name the file after the class), and then paste that code into it. Boom - namespace added :)
In your form code, you are already using the fully qualified name of the class (that is, you are mentioning the namespace in the line
CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);
so you don't need a "using" statement.
If you did add "using CoderBuddy;" to the top of your form's .cs file, then that line could change to
ExtractEmails helper = new ExtractEmails(result);
But in this case I would leave it as you already have it, because the namespace hints at the fact that the ExtractEmails code is slightly separated from the rest of your code.
I have a class library that is nested two+ layers under a main GUI application, within that nested class library I want to be able to access the main applications name.
Under .Net 3.5 you could call Application.ProductName to retrieve the value from the Assembly.cs file, but I cannot identify an equivalent in WPF. If I use reflection and GetExecutingAssembly then it returns the class libraries details?
Thanks
You can use Assembly.GetEntryAssembly() to get the EXE assembly, and can then use Reflection to get the AssemblyProductAttribute from that.
This assumes that the product name has been set on the EXE assembly. The WinForms Application.ProductName property actually looked in the assembly containing the main form, so it works even if the GUI is built in a DLL. To replicate this in WPF you would use Application.Current.MainWindow.GetType().Assembly (and again use Reflection to get the attribute).
Here is another solution that I am using to get the Product Name
Public Shared Function ProductName() As String
If Windows.Application.ResourceAssembly Is Nothing Then
Return Nothing
End If
Return Windows.Application.ResourceAssembly.GetName().Name
End Sub
in wpf there are many way to do this ,
here you can find two of this.
using System;`
using System.Windows;
String applicationName = String.Empty;
//one way
applicationName = AppDomain.CurrentDomain.FriendlyName.Split('.')[0];
//other way
applicationName = Application.ResourceAssembly.GetName().Name;
If you need to get the descriptive product name as I did, then this solution may be useful:
// Get the Product Name from the Assembly information
string productName = String.Empty;
var list = Application.Current.MainWindow.GetType().Assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
if (list != null)
{
if (list.Length > 0)
{
productName = (list[0] as AssemblyProductAttribute).Product;
}
}
It returns whatever you've set for the 'AssemblyProduct' attribute in the AssemblyInfo.cs file, e.g. something like "Widget Engine Professional".
Based on the answers above, this works just great immediately:
var productName = Assembly.GetEntryAssembly()
.GetCustomAttributes(typeof(AssemblyProductAttribute))
.OfType<AssemblyProductAttribute>()
.FirstOrDefault().Product;
If you are looking for the values provided by the assembly information, e.g. the title...
... then you have to get the custom attributes like this:
using System.Linq;
using System.Reflection;
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = (Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute)).SingleOrDefault() as AssemblyTitleAttribute)?.Title;
}
}
}
The answer you require is:
Path.GetFileName(Assembly.GetEntryAssembly().GetName().Name)