I am using mcs version 2.10.8.1 in Ubuntu 12.04, I have the following code:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.ShowDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
MessageBox.Show(fileName);
}
}
}
}
I compile using the command
$ mcs source_code.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll
And I receive the error
source_code.cs(11,13): error CS0103: The name `InitializeComponent' does not exist in the current context
Compilation failed: 1 error(s), 0 warnings
I've seen many answers to this question in cases using Visual Basic; I would like to know what I should do to solve this problem. Thanks.
Was your C# code originally created in Visual Studio? If so, then you'll probably have a Form1.Designer.cs file as well as the file containing the code that you've written by hand. You need to include the file in the command line.
If this isn't C# code originally created in Visual Studo, you may not even have an InitializeComponent method... but in that case you'll need more code to do anything useful in your form (like creating the button and hooking up its Click event).
Related
I am working on a visual studio project in which I have a webpage I would like to display in webbrowser. Currently I have a folder named resources in which I have copied all the required html,js and css files, but I don't know how to point it in the project. Any ideas? Thank you.
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string appPath = Assembly.GetEntryAssembly().Location;
string filename = Path.Combine(Path.GetDirectoryName(appPath), "resources\\index.html");
notes.Navigate(filename);
}
}
}
Thank you.
Update
I have pasted the contents of the resources folder directly in the project, and tried multiple options suggested in the URL. Unfortunately, nothing is working, and I am new to Visual studio, so don't even have an idea what's going wrong. Updated code :
private void Form1_Load(object sender, EventArgs e)
{
//string curDir = Directory.GetCurrentDirectory();
//this.notes.Url = new Uri(String.Format("file:///resources/index.html", curDir));
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "index.html");
notes.Url = new Uri("file:///" + myFile);
}
If you want to open a link in a browser from your desktop app (e.g. "show in the browser" button in WinForms app), you can use System.Diagnostics.Process.Start("http://localhost:42") as it's discussed here (production code will have some non-localhost link there).
Before that you should host your website on local IIS and specify the port (e.g. 42) there.
On the other hand, if you want to create a web application (with C# back-end code), you should use another type of project (not WinForms), e.g. ASP.NET MVC
EDIT:
System.Diagnostics.Process.Start also works with local files, e.g. System.Diagnostics.Process.Start(#"C:\Sites\index.html");
EDIT 2:
You also could use application directory e.g. System.Diagnostics.Process.Start(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"site\index.html")) to keep paths in your app relative
In his book Erik Brown writes the following code
and compiles it from the command-line:
csc MyForm.cs
[assembly: System.Reflection.AssemblyVersion("1.1")]
namespace MyNamespace
{
public class MyForm : System.Windows.Forms.Form
{
public MyForm()
{
this.Text = "Hello Form";
}
public static void Main()
{
System.Windows.Forms.Application.Run(new MyForm());
}
}
}
I want to add another form and call it from the first.
Do I need a project file? An assembly file? I don't understand the build process. Can you explain the very basics to me: how do I tell the compiler to build a two-forms application?
First form (form1.cs):
public class MyForm : System.Windows.Forms.Form
{
public MyForm()
{
this.Text = "Hello Form";
this.Click += Form_Click;
}
public static void Main()
{
System.Windows.Forms.Application.Run(new MyForm());
}
private void Form_Click(object sender, System.EventArgs e)
{
MyForm2 form2 = new MyForm2();
form2.ShowDialog();
}
}
Second form (form2.cs):
public class MyForm2 : System.Windows.Forms.Form
{
public MyForm2()
{
this.Text = "Hello Form 2";
}
}
Now from the command line, locate to the location where you saved these .cs files and then run:
csc form1.cs form2.cs
It will create an EXE file. Run it and click in the form to open form2.
You need to use Visual Studio (VS) command prompt and mention the C# code file names (*.cs) of all the Windows forms in your project. You must include each form's code-behind file as well as designer code-behind file. Otherise, the compilation will not succeed.
A sample project structure is as below:
WindowsFormsApplication1.csproj
--Program.cs
--Form1.cs
----Form1.Designer.cs
--Form2.cs
----Form2.Designer.cs
The compilation command for above project will look like:
csc /target:winexe Program.cs Form1.cs Form1.Designer.cs Form2.cs Form2.Designer.cs
Note: It is compulsory to include Program.cs file during compilation, else the compiler fails to obtain the project's entry point(the Main method). The /target switch helps you to launch the output EXE file as a GUI based Windows Forms application.
There is a shorter version of the above command which uses wildcard to include all the files names in one go:
csc /target:winexe *.cs
The easiest alternative is to use the msbuild command in place of csc on Visual Studio command prompt. msbuild command can be used to build the project file which contains the reference of all the *.cs files. Here is how the command looks like:
msbuild WindowsFormsApplication1.csproj
This relieves us from mentioning all the C# code file names individually (whether in project root directory or nested sub-direcotries). Build the project file and you are done.
I've been trying to run a command from an app written in C#, and all I've read had to do with using System.Diagnostics.Process.Start to run it. However, whenever I try to use this function, the compiler throws an error telling me that 'The type or namespace name 'Process' does not exist in the namespace System.Diagnostics'.
When I try to write the command, intellisense doesn't show anything about "Process" inside the System.Diagnostics namespace.
This doesn't work:
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using System.Diagnostics;
namespace App2
{
sealed partial class App : Application
{
public App()
{
}
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
System.Diagnostics.Process.Start("CMD.exe", "help"); // This is giving me an error
}
}
}
EDIT: I just tried creating a new Windows Forms project, and I could find System.Diagnostics.Process.Start. Does anyone know how can I run a command from an Universal Windows App, since it's apparently not supported?
I'm trying to get SQLite running in Visual Studio 2012 for C#.
However after going through a set of tutorials I still get the error DllNotFoundException for the SQLite.Interop.dll.
This is the full error I receive:
Unable to load DLL 'SQLite.Interop.dll': The specified path is
invalid. (Exception from HRESULT: 0x800700A1)
I have created a reference for the System.Data.SQLite.dll. Now I found that I have to add the SQLite.Interop.dll file into my project folder but I still get this error.
Oh and BTW, this is my code, if anyone is interested:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace SQLiteWinFormCS
{
public partial class Form1 : Form
{
private SQLiteConnection _sqlCon;
private SQLiteCommand _sqlCmd;
private SQLiteDataAdapter _db;
private DataSet _ds = new DataSet();
private DataTable _dt = new DataTable();
private string _dbPath = String.Empty;
public Form1()
{
InitializeComponent();
}
private void uiOpenDB_Click(object sender, EventArgs e)
{
Console(String.Format("You clicked {0}.", ((Button)sender).Name));
this._dbPath = uiDatabaseFilepath.Text;
Console("Filepath to DB = " + this._dbPath);
Console("Attempting to open DB connection...");
this._sqlCon = new SQLiteConnection(String.Format("Data Source={0};", #"\\Some-PC\ISC\Databases\testdbs\test.db3")); // << ERROR
Console("DB connection succesfull!");
}
private void Console(string text)
{
uiConsoleOutput.AppendText(text);
uiConsoleOutput.ScrollToCaret();
}
}
}
Can anyone help me get this thing working?
Thanks in advance.
Copy the SQLite.Interop.dll file into your debug folder.
For example "Projects\sqlite test18\sqlite test18\bin\Debug" place it here.
And dont add the Interop as a reference.
Add only these references
System.Data.SQLite
System.Data.SQLite.EF6
System.Data.SQLite.EF6
This solved my problem.
And I was using Sqlite x86 under x64 OS.
Dohh...
I was probably using a wrong System.Data.SQLite.dll.
For anyone who is interested you can find the new .dll file I downloaded here:
http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
I needed the .dll for the 4.5 Framework (x86); I clicked the first download link.
Also I am using just the System.Data.SQLite.dll, no other files!
Hope this answer helps someone else. :-)
I'm getting really stuck trying to refer to methods/classes in a project imported into a blank project. The exact steps to recreate this are as follows
Download and Extract into a temp folder http://mywsat.codeplex.com/
Create a new project in VS - Asp.Net Empty Web Application .NET 3.5 named WebApplication1
Copy all files from MYWSAT35 folder across to the new project
In VS solution explorer, select Show all files
If you now build and run the project runs fine with no errors.
5 In VS solution explorer, for all of the imported files right click and select Include in Project
Now try rebuilding the project I get the error
The type or namespace name 'GetAdminMasterPage' could not be found
(are you missing a using directive or an assembly reference?)
GetAdminMasterPage.cs is located in WebApplication1\App_Code\class\GetAdminMasterPage.cs and looks like this
#region using references
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Caching;
using System.Web.UI;
#endregion
/// <summary>
/// Gets the MasterPage for the user selected Admin Theme.
/// </summary>
public class GetAdminMasterPage : System.Web.UI.Page
{
#region Get Admin MasterPage
protected override void OnPreInit(EventArgs e)
{
if (Cache["cachedAdminMaster"] == null)
{
GetDefaultMasterPage();
}
else
{
string loadMasterFromCache = Cache["cachedAdminMaster"].ToString();
Page.MasterPageFile = loadMasterFromCache;
}
}
private void GetDefaultMasterPage()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbMyCMSConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_admin_SelectMasterPage", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (myReader.Read())
{
string masterPageFileName = myReader["ThemeUrl"] as string;
Cache.Insert("cachedAdminMaster", masterPageFileName, null, DateTime.Now.AddSeconds(300), System.Web.Caching.Cache.NoSlidingExpiration);
Page.MasterPageFile = masterPageFileName;
}
myReader.Close();
con.Close();
con.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
#endregion
}
An example of one of the methods that now gives an error is
using System;
public partial class admin_admin_edit_css : GetAdminMasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
//gives error The type or namespace name 'GetAdminMasterPage' could not be found
(are you missing a using directive or an assembly reference?)
So I know I must refer to GetAdminMasterPage with Using xxxxxx; but just can't figure out the correct syntax.
Firstly why does the error only occur when I select "Include In Project" and not when just copied?
Secondly, how do I fix the error with the correct path to the GetAdminMasterPage?
After opening the project as a web site, right-click the project and choose "Convert to Web Application". The result of the conversion is what you'll want to move to your blank project, or perhaps you'll want to leave the changes in place.
You have to open the project as a web site.
If you are using VS2010, then it will prompt you for upgrade to .net 4.0. You can choose no.
But if you are opening in VS2012, it will open it with no prompts.
Both will build successfully.
Note: you do not create a new project.
1.Copy the MYWSAT35 folder in a drive (for example: d:\MYWSAT35)
2.in Visual Studio go to File -> Open web site
3.select d:\MYWSAT35 and click on open
4.press F5 key to run application