I have this piece of code from one of my classes and when i hover over the semicolon next to "//error is here" "} Expected" but all the brackets are closed, i have no idea why its causing this, i tried rebuilding but nothing changes
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite.Net;
using SQLite.Net.Platform.WinRT;
namespace HomeAutomation
{
public class MainCode
{
static string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
static SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path)
{
conn.CreateTable<User>;//ERROR IS HERE
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
You're using an object initiationalization. You don't use semi-colon in it b/c a semi-colon indicates the termination point of a command. You're not allowed to end a statement in the middle of initialization. You would separate each field you're initializing with a comma and then end the statement after the last curly brace.
Edit
It looks like you shouldn't be using object initialization after looking at the code again. This syntax is for initializing property on objects. You need to separate the two statments. I.e.
static SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path); // End initialization statement
static MainCode()
{
conn.CreateTable<User>;//Initialize in static constructor
}
This conn.CreateTable<User>;//ERROR IS HERE should read
conn.CreateTable<User>();//solved
You forgot the brackets
Not sure if this will help but maybe try:
conn.CreateTable<User>("SELECT somethingHere FROM somewhere");
I think what you've done here to use the keyword static when you should have used using
Looking at what you're trying to achieve I'd suggest your code might need to look something like:
using SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path)
{
conn.CreateTable<User>();//ERROR IS HERE
}
What have I changed?
I've changed the word static to using and added the brackets to the end of the conn.CreateTable<User>()
Hope this helps!
Related
I am developing a windows phone 8 app using sqlite and am trying to check if the database exists and if it doesnt exist,it should be created. but i keep getting the error message "System.windows.shapes.path does not contain a definition for combine". Is there another way to do it or how can i improve it?
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));//DataBase Name
public App()
{
if (!CheckFileExists("ContactsManager.sqlite").Result)
{
using (var db = new SQLiteConnection(DB_PATH))
{
db.CreateTable<Contacts>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
Do you really need to check if the database exist? I don't know about windows phone, but in Windows, as soon as you try to add a table into a SQLite database, if the database doesn't exist, it creates it. If you are worried about the table existing already, you can use:
CREATE TABLE IF NOT EXISTS tableName(...)
(I tried to ask it as comment but I don't have the reputation)
Why do you have a Path.Combine in a Path.Combine? If Path.Combine is not available with one or two parameter, why not simple concat two strings?
You have it 2x: public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));
you can check by this:
public async Task<bool> isFilePresent(string fileName)
{
return System.IO.File.Exists(string.Format(#"{0}\{1}", ApplicationData.Current.LocalFolder.Path, fileName);
}
#Panagiotis Kanavos's comment was right, you have resolved the Path class using wrong namespace!
Remove
using System.Windows.Shapes; // for silverlite
using Windows.UI.Xaml.Shapes; // for winrt
and add
using System.IO;
As the title says, Visual Studio is throwing an exception when I execute my program.
The exact error:
An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll
As I'm rather new to using Visual Studio, and C# for that matter, I was unable to discern what the issue was. I did Google, but none of the information I found assisted the recovery of my excepted program.
Program code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Game {
public struct entity {
int XP,
HP,
mana,
luck,
strength,
defense;
float modStrength,
modDefense;
string stance;
}
public class Game {
private entity enemy;
private static Dictionary<string, int> playerData =
new Dictionary<string, int>();
public static string[] entityPool =
new StreamReader(Properties.Resources.Entities).ToString().Split('?');
static void Main (string[] args) {
instancePlayer();
Console.ReadKey();
}
private static void instancePlayer () {
string[] playerDataDummy = entityPool[0].Trim().Split(';');
foreach (string s in playerDataDummy) {
string[] indivArr = s.Split(' ');
playerData.Add(indivArr[0], Convert.ToInt16(indivArr[1]));
}
foreach (KeyValuePair<string, int> s in playerData) {
Console.WriteLine("[{0}] {1}", s.Key, s.Value);
}
}
private void instanceEnemy () {
}
}
}
I have been able to narrow the issue down to this line, though...
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
That's about as much as I've been found out; removing the initialization of that, and all it's reference, nullifies the issue. But alas, I do need it there.
Take a look at the streamreader class on MSDN. There are several constructors for it and a simple example for reading from a text file. I'm not sure what you have in Properties.Resources.Entities (a file path I assume). Assuming this is a valid file path or stream and the constructor isn't throwing the error, you are creating the streamreader then calling .ToString() which gives you a string representation of the StreamReader object, not the contents of the file or stream. This is probably not what you are expecting. The sample on the MSDN page should help you with using the StreamReader class.
This line is wrong.
public static string[] entityPool = new StreamReader(Properties.Resources.Entities).ToString().Split('?');
What you probably meant was to read all the contents of the stream. Something like this.
StreamReader sr = new StreamReader(Properties.Resources.Entities);
string[] entityPool = sr.ReadToEnd().Split('?');
Better to put this code in the constructor with a try-catch rather than in an initialiser.
It appears that a StreamReader was not necessary to access the contents of the file.
string[] entityPool = Properties.Resources.Entities.split('?'); works as I previously intended.
I appreciate the responses, All.
This is my first time posting here, so I apologize if this is the wrong place/ format/ etc.
I am new to both C# and neo4j and I am having trouble getting the basics right. I have looked around at the neo4jClient Git Wiki and I am still having trouble. I want to write code that simply finds a node and displays some of its information, however I cant seem to get it to work. Visual Studio is not giving me any error messages, the code just does not seem to work as it returns no name values and the counter is still at 0. Here is the code:
using Neo4jClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neo4jtest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World");
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
var tomQuery = client.Cypher
.Match("(tom:Person)")
.Where((Person tom) => tom.Name == "Tom Cruise")
.Return(tom => tom.As<Person>());
var peopleNamedTomCruise = tomQuery.Results;
int counter = 0;
foreach (Person value in peopleNamedTomCruise)
{
Console.WriteLine(value.Name);
counter++;
}
Console.WriteLine(counter.ToString());
}
public class Person
{
public string Name {get; set;}
public int Born { get; set; }
}
}
}
As for the data I am using the sample data from the Neo4j "The Movie Graph" exercise.
Any and all help would be greatly appreciated!
Property names in Neo4j are case sensitive.
The movies example uses lowercase names like name.
You have followed the C# convention with your POCO and used Name.
This will cause the WHERE clause to return no matches.
i know i could search proccessId / name of running tasks and kill processes i need .
though till now i was not developing schedualed tasks / self executble Applications,
so i didn't need to know how to make the application close itself after execition
trying to close everything (including WebDriver) via Application.Exit + OR this.Close()
right after i have got what i was looking for. mission Complete .
please close ... no more work for you .
but mr . Program.cs still needs somthing from Form1.
saying somthing about
Cannot access a disposed object.
Object name: 'Form1'.
any combination of both was returning in some point an exeption error
(from program.cs ) even though mission complete . no more code was requested .(?) by me..atleast.
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 OpenQA.Selenium;
using OpenQA.Selenium.IE;
using System.IO;
namespace HT_R_WbBrows2
{
public partial class Form1 : Form
{
public IeEnginGenerator Iengn = new IeEnginGenerator();
public Form1()
{
InitializeComponent();
//setLogView(View.Details);
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
this.Close();
Application.Exit();
}
public class IeEnginGenerator
{
private string directory = Environment.CurrentDirectory;///Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
public IWebDriver IwebEngine;
public List<string> ListElementsInnerHtml = new List<string>();
public HtmlAgilityPack.HtmlDocument Dnetdoc = new HtmlAgilityPack.HtmlDocument();
#region <<=========== setupDriver ============>>
public string ExtractPageValue(IWebDriver DDriver, string url="")
{
if(string.IsNullOrEmpty(url))
url = #"http://www.boi.org.il/he/Markets/ExchangeRates/Pages/Default.aspx";
var service = InternetExplorerDriverService.CreateDefaultService(directory);
service.LogFile = directory + #"\seleniumlog.txt";
service.LoggingLevel = InternetExplorerDriverLogLevel.Trace;
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
DDriver = new InternetExplorerDriver(service, options, TimeSpan.FromSeconds(60));
DDriver.Navigate().GoToUrl(url);
Dnetdoc.LoadHtml(DDriver.PageSource);
string Target = Dnetdoc.DocumentNode.SelectNodes("//table//tr")[1].ChildNodes[7].InnerText;
//.Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())
//.ToList();
return Math.Round(Convert.ToDouble(Target), 2).ToString();
//return "";//Math.Round(Convert.ToDouble( TempTxt.Split(' ')[10]),2).ToString();
}
#endregion
}
}
}
Why use a winform application? A Console application would probably suffice for what you are doing. Once Main() ends your app will close as well. Main() never ends in a winform app because of the applications runloop.
Edit:
Here would be the correct way to do this. You need to register to the forms Load event and run your code there, not in the constructor. You can't close a winform from inside a constructor.
Edit 2: Put this code in the Form1() constructor. Somewhere after InitializeComponent();
this.Load += (sender,args)=>{ /*do all your work here*/
string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);
string flnm = #" the directory path to file --> \dolarRate.asp";
File.WriteAllText(fn, extractededVal);
Application.Exit();
};
I have a TextBox that is eventually saved in a xml node. I am using the SecurityElement.Escape(string2Escape) to escape the invalid characters before saving the xml.
Problem: I tried using the IsValidText to test if i need to run the escape method, but it returns ''' and '&' as valid but then when you save the xml the system barfs because they are, in fact, not valid. It seems to only return false on '<' or '>'.
Simple solution, remove the check, but my question is why would this be the case?
The following is my failing code:
private string EscapeXML(string nodeText)
{
if (!SecurityElement.IsValidText(nodeText))
{
return SecurityElement.Escape(nodeText);
}
return nodeText;
}
Here's what I got from Reflector.
This can explain why it's behaving the way it's behaving. I don't see any method in SecurityElement that does what your are looking for but it is simple enough to implement one yourself, maybe as an extension method.
The SecurityElement constructor is apparently already doing some escaping on its own (including the "&" character), so the IsValidText seems to be only checking for the characters the constructor is not already taking care of.
As a consequence, it doesn't look safe to use the SecurityElement's IsValidText/Escape combo, unless you're using SecurityElement to build the whole xml.
I'll try to explain better with an example:
using System;
using System.Diagnostics;
using System.Security;
class MainClass
{
public static void Main (string[] args)
{
// the SecurityElement constructor escapes the & all by itself
var xmlRoot =
new SecurityElement("test","test &");
// the & is escaped without SecurityElement.Escape
Console.WriteLine (xmlRoot.ToString());
// this would throw an exception (the SecurityElement constructor
// apparently can't escape < or >'s
// var xmlRoot2 =
// new SecurityElement("test",#"test & > """);
// so this text needs to be escaped before construction
var xmlRoot3 =
new SecurityElement("test",EscapeXML(#"test & > """));
Console.WriteLine (xmlRoot3.ToString());
}
private static string EscapeXML(string nodeText)
{
return (SecurityElement.IsValidText(nodeText))?
nodeText :
SecurityElement.Escape(nodeText);
}
}