Environment: c#.net VS 2010
Solution has the following two projects:
A dll with several tested methods I've added.
A test project
The only thing in the test project is a form with following code: (names changed for readability)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using DLL_PROJECT; //Yes I remembered to include the dll project
namespace DLL_PROJECT_Test
{
public partial class frmTest : Form
{
private Class_1 myClass_1; //this comes from the dll - no errors here
private Class_2 myClass_2 = new Class_2(); // no errors here either
public frmTest()
{
InitializeComponent();
//TransparencyKey = BackColor;
this.SetStyle(System.Windows.Forms.ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = System.Drawing.Color.FromArgb(0, System.Drawing.Color.Black);
myDebouncer = new Debouncer(this);
this.SetDragging(true); //THIS EXTENSION COMES FROM THE DLL AND WORKS FINE
this.RoundCorners(40, 80); //AS DOES THIS ONE
myClass_2 = new Class_2();
myClass_2.HoldStartEvent += new Class_2EventHandler(myClass_2_HoldStartEvent);
myClass_2.DragStartEvent += new Class_2EventHandler(myClass_2_DragStartEvent);
}
private void myClass_2_DragStartEvent(Class_2 sender)
{
myClass_2("DragStart") += 1; //THE ONLY ERROR IS HERE AS FOLLOWS
//ERROR: "The name 'myClass_2' does not exist in the current context"
// - Yes, the DLL is included
// - Yes, the project is .Net 4 (not client profile)
// - Yes xxx WRONG xxx, this exact syntax has been tested before on an instance of
// this class, it's just a default parameter.
// xxx should be [] instead of () for the indexer in c#. #VB_Fails
}
void myClass_2_HoldStartEvent(Class_2 sender)
{
this.Close();
}
}
}
This code:
myClass_2("DragStart") += 1;
... is using myClass_2 as if it were either the name of a method or a delegate instance.
Did you actually mean to use the indexer? That would be:
myClass_2["DragStart"] += 1;
What does "DragStart" mean here? Is it actually a property name? Perhaps you want:
myClass_2.DragStart += 1;
I very much doubt that "this exact syntax has been tested before on an instance of this class".
Admittedly the error message doesn't make much sense in this case. I think it's actually more likely that you've got a typo in your real code - a typo which isn't propagated here because you've changed the names. If you could reproduce this in a short but complete program, it would make life a lot simpler.
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);
}
I am trying to connect to R from c# using the following code. It looks like C# is not reading the R dll files. My R installation directory is this:
C:\Users\R-2-13\R-2.13.0\bin\i386
and I also downloaded and put the R.NET.dll in the same directory. In Visual Studio, I set the reference to R.NET.dll file. When I run the following code, the code goes the the catch section "unable to find the R Installation". Any ideas? Has anybody got this working?
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 RDotNet;
namespace RNet_Calculator
{
public partial class Form1 : Form
{
// set up basics and create RDotNet instance
// if anticipated install of R is not found, ask the user to find it.
public Form1()
{
InitializeComponent();
bool r_located = false;
while (r_located == false)
{
try
{
REngine.SetDllDirectory(#"C:\Users\R-2-13\R-2.13.0\bin\i386");
REngine.CreateInstance("RDotNet");
r_located = true;
}
catch { MessageBox.Show(#"Unable to find R installation's \bin\i386 folder. Press OK to attempt to locate it.");
MessageBox.Show("error");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
This is http://rdotnet.codeplex.com/ (RDotNet) to develop Winform applications. While I know Shiny and all the other Web-like R-tools quite well, the combination of c# and R still is my preferred end-user combinations. Try simple things like disabling buttons with Shiny...
Too bad rdotnet is quite buggy; in the current version, it crashes on R exeptions, even in try-catched ones.
This said: please make absolutely sure that you use version 1.5, not the stupidly called "stable" (=early beta) version on the page. Best download it via NuGet. Also check if you did not mix 32bit R with 64 bit c#.
Using the Helper-functions of 1.5, initialization is:
Helper.SetEnvironmentVariables();
engine = REngine.CreateInstance(EngineName);
engine.Initialize();
# Assuming you want to catch the graphic window, use my RGraphAppHook
# on the rdotnet site http://rdotnet.codeplex.com/workitem/7
cbt = new RGraphAppHook { GraphControl = GraphPanelControl };
I added as reference 3 dll's: Google.Apis , Google.Apis.Translate.v2 , System.Runtime.Serialization
In Form1 i have one line:
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Translator.translate(new TranslateInput());
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Now the error the exception is on the first line in the class Translator:
The line that throw the error is: var service = new TranslateService { Key = GetApiKey() };
The class code is:
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.Net;
using System.IO;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Google.Apis.Util;
using Google.Apis.Translate.v2;
using Google.Apis.Translate.v2.Data;
using TranslationsResource = Google.Apis.Translate.v2.Data.TranslationsResource;
public class Translator
{
public static string translate(TranslateInput input)
{
// Create the service.
var service = new TranslateService { Key = GetApiKey() };
string translationResult = "";
// Execute the first translation request.
Console.WriteLine("Translating to '" + input.TargetLanguage + "' ...");
TranslationsListResponse response = service.Translations.List(input.SourceText, input.TargetLanguage).Fetch();
var translations = new List<string>();
foreach (TranslationsResource translation in response.Translations)
{
translationResult = translation.TranslatedText;
}
return translationResult;
}
private static string GetApiKey()
{
return "AIzaSyCjxMe6RKHZzd7xSfSh2pEsBqUdXYm5tA8"; // Enter Your Key
}
}
/// <summary>
/// User input for this example.
/// </summary>
[Description("input")]
public class TranslateInput
{
[Description("text to translate")]
public string SourceText = "Who ate my candy?";
[Description("target language")]
public string TargetLanguage = "fr";
}
The error is:
Could not load type 'Google.Apis.Discovery.FactoryParameterV1_0' from assembly 'Google.Apis, Version=1.1.4497.35846, Culture=neutral, PublicKeyToken=null'.
Tried to google for help and also tried to change the project type to x64 platform but it didnt help. So i put it back on x86
I have windows 7 64bit visual studio c# 2010 pro .net 4.0 profile client.
Cant figure out what is the error ?
This error as reported in the above-posted messages is due to a local copy in the bin\Debug folder of your solution or project. Even though you attempt to clean your solution, such copies will persist to exist.
In order to avoid this to happen, you have to force Visual Studio to refer to the correct DLL by adding reference paths within a project properties. Unfortunately, if you got several projects within your solutions, you will have to set the reference paths for the projects one after another until completed.
Should you wish to know how to setup reference paths follow these simple instructions:
1.Select your project, right-click, then click "Properties";
2.In the project properties, click "Reference Paths";
3.Folder, type or browse to the right location of your DLL, click [Add Folder].
You will need to perform these steps for as many different locations you may have for each of your DLLs. Consider setting an output path under the Build tab of the same project properties, so that you may output your DLLs in the same directory for each of them, thus assuring you to find all the latest builds under the same location, simplifying forward your referencing.
Note this can only be one reason for this error. But it is sure that is has to do something with a wrong copy of the mentioned assembly.
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.