Problems with MessageBox.Show() - c#

I'm new to code and most things work, but I can't get this code to run. Can someone help?
I tried using System.Forms but it showed as missing a namespace. When I used using System.Windows.Forms that message went away. It does not let me use both.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(#"file.csv");
// for set encoding
// StreamReader sr = new StreamReader(#"file.csv", Encoding.GetEncoding(1250));
string strline = "";
String[] _values = null;
int x = 0;
while(!sr.EndOfStream)
{
strline = sr.ReadLine();
_values = strline.Split(',');
if (_values.Length >= 6 && _values[0].Trim().Length > 0)
{
MessageBox.show(_values[1]);
}
}
sr.Close();
}
}
}

There is no such namespace System.Forms, the class you were trying to use (MessageBox) is in System.Windows.Forms. By correcting your using statement, the error went away.
Remember, you must have a reference to System.Windows.Forms.dll in your console app to use this class.

You need to reference System.Windows.Forms.dll in your project. Here is a detailed instruction how to do that.

There is no such namespace as System.Forms there is only a namespace called System.Windows.Forms, wich has the MessageBox class you are talking about. To be able to use it, you need to add a reference to the System.Windows.Forms.dll to to your project (find it in the .NET Tab in the "Add Reference ..." dialog) and it will work. Also note that MessageBox.Show() requires a capital 'S'. Please see below an optimized and fully working version of your code.
using System.IO;
using System.Windows.Forms;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(#"file.csv"))
{
while (sr.Peek() >= 0)
{
string strline = sr.ReadLine();
string[] values = strline.Split(',');
if (values.Length >= 6 && values[0].Trim().Length > 0)
{
MessageBox.Show(values[1]);
}
}
}
}
}
}

You try use it in Console application first you should add System.Windows.Forms dll in your references (from .Net reference tab) then use it by adding it's namespace.

I'm a bit confused here. there is no namespace called System.Forms. It's always System.Windows.Forms. And the MessageBox class is defined in System.Windows.Forms
You need to manually ADD a reference to your project for System.Windows.Forms as you are on a console application and not a Windows Application. Just add the reference.

Related

File.Exists and SpreadsheetDocument.Open returning File Not Found Exception in UWP Application

Im having an issue with using DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open is not opening a spreadsheet, it returns a file not found exception. The class i'm using has worked many times before, but i've never used it in a UWP project.
I've created a simple example and found that I get the same issue when using File.Exists i've include all the using statements i use if that helps.
Does anyone know why the File.Exists cannot detect the file?
and yes i've triple checked the file does exist on D:!
C# UWP Project created using UWP Template Studio [MainPage.xaml.cs]
using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Windows.UI.Xaml;
using UWP_APP.ViewModels;
using Windows.UI.Xaml.Controls;
namespace UWP_APP.Views
{
public sealed partial class MainPage : Page
{
public MainViewModel ViewModel { get; } = new MainViewModel();
public MainPage()
{
InitializeComponent();
string filePath = #"D:\example.xlsm";
if (File.Exists(filePath))
{
int a = 1;
}
else
{
int a = 0;
}
}
Does anyone know why the File.Exists cannot detect the file?
UWP app is running in sandbox, because File.Exists is System.IO api. So it could not work for accessing file except ApplicationData.Current.LocalFolder. If you do want to check if the file exist in the specific path, we suggest you add broadFileSystemAccess capability and enable in the system file access setting. This capability works for APIs in the Windows.Storage namespace.
And using the flolowing method to check if the file exist.
try
{
var file = StorageFile.GetFileFromPathAsync(#"C:\Users\Karan\OneDrive\Desktop\2010.pdf");
if (file != null)
{
isExist = true;
}
}
catch (Exception)
{
isExist = false;
}

C# Preprocessor Directives (#if and #endif) not working. Compilation error

I am trying to debug an existing application in VS2010, 4.0 framework. I get this compile-time error:
"The name 'b_resources' does not exist in the current context" .
I cannot see anything wrong in the code below:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
#if TR
using b_resources = Common.Resources.TResources;
#endif
#if EN
using b_resources = Common.Resources.EnResources;
#endif
namespace Common
{
public static class BResources
{
public static string caption { get { return b_resources.ProductName; } }
public static string company_name { get { return b_resources.CompanyName; } }
}
}
TResources and EnResources are resource files (.resx)
Am I missing some references related to .Net ?
The most obvious question is: do you define the TR or EN compilation symbol in your current build? If not, both #IF statements will be false and the using statement won't be included. In other words, if you do not define those symbols, the following code will be compiled:
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Drawing;
// Note: missing using statements
namespace Common
{
public static class BResources
{
public static string caption { get { return b_resources.ProductName; } }
public static string company_name{ get { return b_resources.CompanyName; } }
}
}
To check or set compilation symbols, go to your project's properties. Then on the Build tab you see as textbox named Conditional compilation symbols. Check if the symbols are defined there. If not, add one of them there.
If you are using Visual Studio, you can in fact immediately see if this is the case. If a symbol is not defined for the current build, the code within the #IF block will be greyed out. If the symbol is defined, it will display jsut like normal code.
You have no default case so if neither TR or EN is defined you get no definition of b_resources. You need to have some else cases in there so it can always compile. For example, if you wanted your EN resource as default:
#if TR
using b_resources = Common.Resources.TResources;
#elif EN
using b_resources = Common.Resources.EnResources;
#else
using b_resources = Common.Resources.EnResources; // or whatever you want as default
#endif
If neither TR or EN are defined the final else will be included.
For your code to compile, you need to define either TR or EN in the Build settings of your Project properties. Currently neither are defined, so b_resources never gets defined.

unhandled exception c# dll

I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project

Im getting exception Typeload what the exception can be?

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.

Getting DLLs in WinForms application

I have to create a class that will load all the dll's from repository and check whether
they are inheriting from IMFServicePlugin interface and returns the
valid dlls.
that I have done using this...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Forms.ComponentModel;
using MFDBAnalyser;
namespace MFDBAnalyserAssemblyValidator
{
public class MFDBAnalyserAssemblyValidator
{
static void Main(string[] args)
{
List<string> assemblyNames = new List<string>();
Assembly[] oAssemblies = new Assembly[args.Length];
for (int assemblyCount = 0; assemblyCount < args.Length; assemblyCount++)
{
oAssemblies[assemblyCount] = Assembly.LoadFile(args[assemblyCount]);
try
{
foreach (Type oType in oAssemblies[assemblyCount].GetTypes())
{
// Check whether class is inheriting from IMFServicePlugin.
if (oType.GetInterface("IMFDBAnalyserPlugin") == typeof(IMFDBAnalyserPlugin))
{
assemblyNames.Add(args[assemblyCount].Substring(args[assemblyCount].LastIndexOf("\\") + 1));
}
}
}
catch (Exception ex)
{
lblError.Text = "ERROR";
}
}
// Passing data one application domain to another.
AppDomain.CurrentDomain.SetData("AssemblyNames", assemblyNames.ToArray());
}
}
}
but this was for loading the dll from the repository but I also want to store these dll in another ORM class.
Can anybody help me out...
If possible plz provide some links so that I can get a sufficient idea of how dll works for an windows/desktop application.
At a first tip you should use Assembly.ReflectionOnlyLoad(). Cause if you load the assembly by using Assembly.LoadFile() the assembly will automatically be put into your local AppDomain!

Categories

Resources