I get an error in C# "The type or namespace name does not exist in namespace" - c#

I get an error in C# "The type or namespace name does not exist in namespace". I checked everywhere but it didn't solve my problem here is the main program
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
class Program
{
static void Main(string[] args)
{
var startTime = DateTime.Now;
BlockChainMySelf.BlockChain StepCoin = new BlockChain();
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 10));
StepCoin.CreateTransaction(new Transaction("lkjsdf", "MaADLKHesh", 15));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 20));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 60));
StepCoin.ProcessPendingTransactions("Bill");
And here is the class that I want to call
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
public class BlockChain
{
IList<Transaction> PendingTransactions = new List<Transaction>();
public IList<Block> Chain { set; get; }
public int Difficulty { set; get; } = 2;
Here are the Screendhots
Main
Class
answerquestion
answerquestion2

The second screenshot in an earlier edit of your question clearly shows the BlockChain class as being 'Miscellaneous Files' in Visual Studio:
The MSDN page for the Miscellaneous Files Project says (emphasis mine):
When a user opens project items, the IDE assigns to the Miscellaneous Files project any items that are not members of any projects in a solution.
Presumably you were in the middle of trying to fix the issue, so you put static in - but that won't work because then you can't create an instance of a BlockChain.
Your question is a duplicate of Visual Studio - project shows up as “Miscellaneous Files”.
The/a solution is to right-click on the bad file in Solution Explorer, remove it from the project, then re-add it, e.g. this answer.

I had this issue... however, I had two classes under the same namespace but in different projects. All I had to do to fix this was to add a reference to the project directly.

Related

dotnet regex to capture using, namespace and its content [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I need a regular expression to capture the using section, the namespace name and the content of the block.
using ns1;
using ns2;
using alias = ns3.Class1;
namespace ns4
{
<content>
}
Each line ends with windows CRLF (\r\n).
I have something using notepad++ (with multiline option) (using.*?;)*(?:\r\n)*(namespace.*?)\r\n\{(.*?)\}(?:\r\n)*\z but it does not work in c# (I tried it here)
I have a console program that finds 2 class files in the same namespace, then combine their using, and namespace block content.
I would strongly advise against using regular expressions for dealing with source files. Regular expressions will just make things harder. Instead, I would advise using a parser, as properly noted by #Cid.
If I understand you correctly, you need to merge two C# source files. Here's my solution using a proper parser.
Let's imagine I have two files, F1.cs and F2.cs.
F1.cs:
using System.Text.RegularExpressions;
using alias = System.Int32;
namespace ConsoleApp3
{
public class DummyClass1
{
public alias DummyProperty { get; set; }
}
}
F2.cs
using System;
namespace ConsoleApp3
{
public class DummyClass2
{
public Int32 Kek { get; set; }
}
}
Here's a quick and dirty program I wrote that merges two C# files together using a parser (warning: not production quality code):
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
namespace ConsoleApp3
{
public static class Program
{
public static async Task Main(string[] args)
{
var sourceFiles = await Task.WhenAll( // reading input files
File.ReadAllTextAsync("F1.cs"),
File.ReadAllTextAsync("F2.cs"));
var tokensOfInterest = sourceFiles
// 1. parse source files
.Select(x => CSharpSyntaxTree.ParseText(x))
// 2. get file syntax tree root elements
.Select(x => x.GetRoot())
// 3. get all top-level using directives and namespace declarations
.SelectMany(root => root.ChildNodes().Where(node => node.Kind() == SyntaxKind.UsingDirective
|| node.Kind() == SyntaxKind.NamespaceDeclaration))
// 4. sort them so that usings come before namespace declarations
.OrderByDescending(x => x.Kind())
// 5. get raw token strings
.Select(x => x.ToString())
.ToArray();
var combined = string.Join(Environment.NewLine, tokensOfInterest);
Console.WriteLine(combined);
}
}
}
Here's how the output looks for my F1.cs and F2.cs files:
using System.Text.RegularExpressions;
using alias = System.Int32;
using System;
namespace ConsoleApp3
{
public class DummyClass1
{
public alias DummyProperty { get; set; }
}
}
namespace ConsoleApp3
{
public class DummyClass2
{
public Int32 Kek { get; set; }
}
}
Yeah... Two namespace declarations of the same namespace... Not pretty, but this is valid C#, so I didn't bother doing anything about it. This file compiles and works as you would expect.
Still, let me assure you - this approach is going to be much easier than wrestling with regular expressions' corner cases, and it only took me five to ten minutes to come up with this, and it's the first time I'm using a C# parser, so it's definitely not rocket science.
Oh, and you'll have to depend on Roslyn by installing Microsoft.CodeAnalysis.CSharp NuGet package. Though it's a small price to pay.

Type ObservableDictionary cannot be found in visual studio community 2017

In the Visual Studio Community MainPage.xaml.cs file containing the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Animation;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App2
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
Random random = new Random();
///private NavigationHelper navigationHelper; ///not needed in Visual Studio 2017
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public MainPage()
{
this.InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
AddEnemy();
}
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100), random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
playArea.Children.Add(enemy);
}
private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
{
Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
DoubleAnimation animation = new DoubleAnimation()
{
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
};
Storyboard.SetTarget(animation, enemy);
Storyboard.SetTargetProperty(animation, propertyToAnimate);
storyboard.Children.Add(animation);
storyboard.Begin();
}
}
}
... the line
private ObservableDictionary defaultViewModel = new ObservableDictionary();
produces the following error message:
Error CS0246 The type or namespace name 'ObservableDictionary' could not
be found (are you missing a using directive or an assembly reference?)
What library am I supposed to include to make this error message go away?
I know that this question is too old, but Head First C# used a Common folder, that has this ReadMe:
The Common directory contains classes and XAML styles that simplify application development.
These are not merely convenient, but are required by most Visual
Studio project and item templates. If you need a variation on one of
the styles in StandardStyles it is recommended that you make a copy in
your own resource dictionary. When right-clicking on a styled control
in the design surface the context menu includes an option to Edit a
Copy to simplify this process.
Classes in the Common directory form part of your project and may be
further enhanced to meet your needs. Care should be taken when
altering existing methods and properties as incompatible changes will
require corresponding changes to code included in a variety of Visual
Studio templates. For example, additional pages added to your project
are written assuming that the original methods and properties in
Common classes are still present and that the names of the types have
not changed.
In the VS2013 solution common folder (there is a VS2012 too, with totally different classes) these are the cs files:
To use these classes you have to add:
using Save_the_Humans.Common;
HFC# had not once in the book cited or referred to these classes; I'm assuming that they were boilerplate code at that time; they wrap some Interfaces and Dictionaries:
public class ObservableDictionary : IObservableMap<string, object>
{
private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<string>
{
public ObservableDictionaryChangedEventArgs(CollectionChange change, string key)
{
this.CollectionChange = change;
this.Key = key;
}
public CollectionChange CollectionChange { get; private set; }
public string Key { get; private set; }
...
You can get the C# code - not only the common folder - from them with the VS2012 version too or from my repository with only VS2013; from their repository you cannot open or import into VS2017 - at least I couldn't; mine is already fresh made with VS2017.
Hope it helps someone.

How to log results to console with MongoDB 3.0 c# driver

I am writing the simple c# console program to connect mongodb db instance and get the value from the mongodb and need to display console window. I am using mongodb version 3.0.
I am getting date but not able display console. I am getting struck with syntax.
Any one please help me, I have shared my sample code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Linq;
namespace MongoCHash
{
class Program
{
static void Main(string[] args)
{
var mongod = new MongoClient();
var db=mongod.GetDatabase("MyDB");
var movies = db.GetCollection<Movie>("movie");
}
}
public class Movie
{
public ObjectId Id { get; set; }
public string name { get; set; }
}
}
You have got a Movie object collection you need to iterate over the collection and the do a Console.Log() of what ever property of the movie object you want including date. If you want I can post an example.

error : 'classA' doesnot exist in current context

I started new project of Windows Forms. First page is UserLogin. in form load event I am taking the logintable from database into memory.
I am using a class in which all read and write operations methods are stored.
when I am calling the class in formload event, the error comes "doesnot exist in current context"
I may be missing some references or headerfilename..
Please Help
Thanks in Advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
namespace InvestmentAndReturns
{
public partial class UserLogin : Form
{
public UserLogin()
{
InitializeComponent();
CenterToScreen();
}
public string UserID = null;
private string userPass = null;
public string UserGroup = null;
DataTable UserLoginTable;
int logintry = 1;
public bool LoginStatus = false;
private void Form1_Load(object sender, EventArgs e)
{
txtUserID.Select();
string cmd = "Select * from UserLogin";
UserLoginTable = DbRdRw.SqlDbRead(cmd, "UserLogin");
}
DbRdRw: this is the Class
SqlDbRead: this is read method
i have included that class by directly pasting it in the project folder and then opened solution and then included in the project
It looks like you have copy pasted source file containing definition of DbRdRw from some other project - which mostly means the namespace declaration in the file will be from older project.
Things will work if you change the namespace to your current project InvestmentAndReturns.
However, why are you copy pasting this around? You could make a library dll for your DbRdRw and reference the dll. That way you will keep your source code at one place.

namespace not being recognized?

I created a very very simple domain layer in visual studio (2010). I then used the new test wizard to create a basic unit test. However when I try to put in the using statement so that I can test my code.. it says my namespace could not be found... This is my first time using visual studio so I am at a loss as to what I am doing wrong.
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Home
{
class InventoryType
{
/// <summary>
/// Selects the inventory type and returns the selected value
/// </summary>
public class InventorySelect
{
private string inventoryTypes;
public String InventoryTypes
{
set
{
inventoryTypes = value;
}
get
{
return inventoryTypes;
}
}
/// <summary>
/// Validate that the inventory is returning some sort of value
/// </summary>
/// <returns></returns>
public bool Validate()
{
if (InventoryTypes == null) return false;
return true;
}
}
}
}
My Test Code
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Home.InventoryType.InventorySelect;
namespace HomeTest
{
[TestClass]
public class TestInventoryTypeCase
{
[TestMethod]
public void TestInventoryTypeClass()
{
InventorySelect select = new InventorySelect();
select.inventoryTypes = "Collection";
if (Validate() = true)
Console.WriteLine("Test Passed");
else
if (Validate() = false)
Console.WriteLine("Test Returned False");
else
Console.WriteLine("Test Failed To Run");
Console.ReadLine();
}
}
}
using refers to a namespace, not a specific class (unless you add an alias for the class name). Your using statement should only include the word Home.
using Home.InventoryType.InventorySelect;
//becomes
using Home;
Here is a link to MSDN on using directive: using Directive (C#)
I'm assuming your test class is in its own project, so you need to add a reference to that project. (A using statement doesn't add a reference, it merely allows you to use a type in your code without fully qualifying its name.)
Declare InventoryType class as public
InventorySelect class can be private rather than public
When you create a "multi-project" in a solution (by adding projects to any existing solution), the projects do not know about each other.
Go to your test project on Solution Explorer and under "References", right click and select "Add Reference". Then select "project" tab and you will be able to add your project's reference to the test project.
Also, make sure you define the classes in the project as "public" to be able to access them in test project.
namespace Home
{
public class InventoryType
{
...
}
}
Note that you still need the "using" keyword on top of your C# test class:
using Home;
namespace HomeTest
{
public class TestInventoryTypeCase
{
...
}
}

Categories

Resources