Something wrong with my connection C# - Microsoft Access 2010 - c#

Ok, so, I created a connection between Visual Studio's C# (2012) and Access. That means, I've done it the manual way (with no code). However, this method can't help me do exactly what I want, so I've done the coding way as well.
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.OleDb;
using System.Configuration;
using System.Xml.Serialization;
namespace WindowsFormsApplication1
{
public partial class horaireForm : Form
{
DateTime semSess;
int numSemaine;
int jourSem;
int periode;
string theoOuLabo;
string lesCours;
string cours;
string lesProfs;
string unprof;
string lesLocaux;
string lesGroupes;
string laComm;
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Stanley\\Desktop\\stuff\\Hiver 2013\\Horaires_EcranA2013.accdb";
(Sorry if it's long). Anyways, after this, I have this code here that gets info from a combobox (each case is the date of the weeks of a college semester). Since apparently I can't select the primary key if it's the values in the combobox, I've decided to use the dates as the values to select in the combobox and then use it to select the actual primary key in the database.
semSess = Convert.ToDateTime(comboSemSess.Text);
OleDbConnection laConn = new OleDbConnection(conn);
try
{
laConn.Open();
laComm = "SELECT NumeroSemaine FROM SemainDelaSession WHERE DebutSemaine = " + semSess;
OleDbCommand myAccessCommand = new OleDbCommand(laComm, laConn);
OleDbDataReader reader = myAccessCommand.ExecuteReader();
while (reader.Read())
{
numSemaine = Convert.ToInt32(reader["NumeroSemaine"]);
}
}
catch
{
MessageBox.Show("Une erreur s'est produite en accédant à la base de données");
}
finally
{
laConn.Close();
}
However, I still can't connect. It still gets the MessageBox. Does it have to do with the fact that I've done another connection before it, or the way I typed the connectionString, because I have no idea.

I can see a few issues... in the While (reader.Read()) block, you're overwriting numSemaine each time so you'll only ever get the last result in the datareader.
Also the date in the SELECT statement should have quotes around it (treat it like a string in SQL) and really it should be parameterised rather than concantenated (hard to SQL Inject from a combo box but not impossible and it's good practise anyway).
Also, a path just needs one \ between directories, not two.

Related

Dapper 'Query' not recognised

The 'connection.Query' does not prompt for Dapper using statement. Dapper has been installed several times. I've tried entering the using statement 'using Dapper' but it's underlined in red saying:
Dapper namespace could not be found
Why is it happening?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace DataAccessLibrary
{
public class SQLDataAccess
{
public List<T> LoadData<T, U>(string sqlStatement, U parameters, string connectionString)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
List<T> rows = connection.Query<T>(sqlStatement, parameters).ToList();
}
}
}
}
I'm embarrassed to say i installed Dapper into the wrong project in my application. I assumed (never assume, always check) wrongly that the installation would be seen throughout my app.
Problem solved.

List comparison not working

I'm trying to make an application that reads two text files, takes the two, and merges them into one single list. Then take said list, and compare it to another list (from another text file). The problem is that no matter what I do my program always goes to else (see the line where it says
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
). I don't know why it does this.
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.IO;
using System.Linq; //Needed for concat.
namespace Name_Search
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string BoyNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\BoyNames.txt"); //Reads BoyNames txt file.
List<string> BoyNamesList = BoyNames.Split('\n').ToList(); //Converts it to a list.
//BoyNamesList.ForEach(Console.WriteLine); <-Testing to make sure that the list is working properly.
string GirlNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\GirlNames.txt"); //Reads GirlNames txt file.
List<string> GirlNamesList = GirlNames.Split('\n').ToList(); //Converts it to a list.
List<string> BoysAndGirlsList;
BoysAndGirlsList = BoyNamesList.Concat(GirlNamesList).ToList(); //Adds the lists together.
//BoysAndGirlsList.ForEach(Console.WriteLine); <-Again just testing that the list is working.
string MostPopularNames = System.IO.File.ReadAllText(#"D:\Google Drive\Course Work\C# Intro\Student Sample Programs\Chap07\MostPopularBoyAndGirlNames.txt"); //Reads MostPopularBoyAndGirlNames txt file. Compiled from http://goo.gl/1crLcY.)
List<string> MostPopularNamesList = MostPopularNames.Split('\n').ToList(); //Converts it to a list.
string NameEntered = nameInput.Text;
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
{
MessageBox.Show("This name is one the most popular names!");
}
else
{
MessageBox.Show("This is not one of the most popular names.");
}
}
}
}
What is not working properly here? I've tried putting in a break, and when I did the values looked fine to me.
The issue is probably solved as mentioned by the comments, where redundant spaces in the 'names' causes them to compare unequally. You also have an issue when you want to compare names in a case-insensitive manner.
The first issue can be solved by trimming whitespace from each name:
BoysAndGirlsList = BoysAndGirlsList.Select(name => name.Trim()).ToList();
MostPopularNamesList = MostPopularNamesList.Select(name => name.Trim()).ToList();
The second issue can be solved by using an invariant case comparer:
if (BoysAndGirlsList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase) &&
MostPopularNamesList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase))

Fill ComboBox with Results of LINQ Query, Directly

I am new to c#/.net/WPF.
I am trying to fill a combobox with values taken from a database.
The LINQ query gets a list of all companies in the database and the code attempts to fill a ComboBox control with this list.
The C# code below successfully gets the results (I previously outputted it with a MessageBox.Show()).
My Next step was to remove that bit and, instead, put in the code which would fill out this ComboBox:
<ComboBox Name="companyComboBox"/>
The c#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace LeadSystem
{
/// <summary>
/// Interaction logic for NewLead.xaml
/// </summary>
public partial class NewLead : Window
{
public NewLead()
{
// Use a connection string.
DataContext db = new DataContext("Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True");
// Get a typed table to run queries.
Table<Company> Companies = db.GetTable<Company>();
// Attach the log to show generated SQL.
db.Log = Console.Out;
// Query for all companies.
var companyQuery =
from c in Companies
select new { Name = c.CompanyName, ID = c.CompanyID };
companyComboBox.ItemsSource = companyQuery.ToList();
companyComboBox.DisplayMemberPath = "Name";
companyComboBox.SelectedValuePath = "ID";
InitializeComponent();
}
}
}
The problem I keep getting is:
Object reference not set to an instance of an object.
^ it's talking about companyQuery, where I try to use it to fill the comboBox.
I thought this must be because of deferred execution, and so I had a look around the web to find a solution. I've seen several people say to add ToList() at the end of that line of code, but nothing changed.
So, does someone here know what I'm doing wrong??
I have looked around the web (including Stackoverflow) and nothing has helped me fix mine.
Also, if it's not too cheeky to ask two questions in one go... How do I set the selected value and displayed values in my ComboBox? Is it correct, the way I already have it?
Thanks
Try to fill the companyComboBox after the initializeComponent
InitializeComponent();
companyComboBox.ItemsSource = companyQuery.ToList();
companyComboBox.DisplayMemberPath = "Name";
companyComboBox.SelectedValuePath = "ID";
Put InitializeComponent(); before you set the itemSource

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.

Is there a tool that allows easy exporting of messages from a message queue (MSMQ)?

I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
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.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}

Categories

Resources