C# Constructor of class initialising and running script - c#

Got some strange behaviour with a script, the constructor of my FileHandler class appears to be calling the class and running the script.
The class itself is only being referenced in VS15 once and that is by its constructor, the main method has not yet even have an object of FileHandler, which is not mentioned anywhere else in the code.
Surely this code should not be running?
Edit: I placed a breakpoint at the start of the Program.cs and began stepping through, but when I did this I noticed that the public class FileHandler becomes class Program and my constructor is 'replaced' by a Main method.
Is this something that C# does by design?
Programs.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using QuantConnect;
using QuantConnect.Securities;
using QuantConnect.Securities.Forex;
namespace TradingDaysFileChecker
{
class Program
{
static void Main(string[] args)
{
var securityType = SecurityType.Forex;
var ticker = TickType.Trade;
var marketHoursDatabase = MarketHoursDatabase.FromDataFolder();
var market = Market.FXCM;
var symbol = Symbol.Create(ticker.ToString(), securityType, market);
var marketHoursDbEntry = marketHoursDatabase.GetEntry(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType);
var exchange = new ForexExchange(marketHoursDbEntry.ExchangeHours);
Console.ReadLine();
}
}
}
FileHandler.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using QuantConnect.Securities.Forex;
namespace TradingDaysFileChecker
{
public class FileHandler
{
private readonly StreamWriter _writeToFile;
private readonly List<Tuple<string, string>> _missingDays;
private readonly string _dataFilePath;
private readonly DateTime _startDate;
private readonly DateTime _endDate;
private readonly ForexExchange _exchange;
private readonly IEnumerable<DateTime> _validTradingDays;
private readonly string[] _forexSecuritiesFolders;
public FileHandler(ForexExchange exchange)
{
_startDate = new DateTime(2007, 04, 01);
_endDate = new DateTime(2016, 07, 25);
_exchange = exchange;
_writeToFile = new StreamWriter(#"C:\Users\RichardsPC\Documents");
_dataFilePath = #"C:\Users\RichardsPC\Desktop\export\exporter\forex\fxcm\minute\";
_forexSecuritiesFolders = Directory.GetDirectories(_dataFilePath);
_missingDays = new List<Tuple<string, string>>();
_validTradingDays = IterateOverDateRange(_exchange, _startDate, _endDate);
}
public void CheckForMissingFiles()
{
foreach (var validDay in _validTradingDays)
{
foreach (var forexSecurity in _forexSecuritiesFolders)
{
var fxPair = new DirectoryInfo(forexSecurity).Name;
var formattedDate = FormatDate(validDay);
var path = SetPath(_dataFilePath, fxPair, formattedDate);
if (!File.Exists(path))
{
_missingDays.Add(Tuple.Create(fxPair, formattedDate));
}
}
}
Results();
}
public void Results()
{
if (_missingDays.Count > 0)
{
foreach (var missingDay in _missingDays.OrderBy(md => md.Item1))
{
var formattedTupleOutput = missingDay.ToString().TrimStart('(').TrimEnd(')');
Console.WriteLine(formattedTupleOutput);
WriteResultsToFile(formattedTupleOutput);
}
}
else
{
var noFilesMissing = "No results missing";
Console.WriteLine(noFilesMissing);
WriteResultsToFile(noFilesMissing);
}
Console.WriteLine("Records missing: " + _missingDays.Count);
}
public void WriteResultsToFile(string result)
{
_writeToFile.WriteLine(result);
}
public static string FormattedFileName(string tradingDay)
{
return tradingDay + "_quote.zip";
}
public string FormatDate(DateTime validDay)
{
return validDay.ToString("yyyyMMdd");
}
public static string SetPath(string dataFilePath, string fxPair, string formattedDate)
{
return dataFilePath + fxPair + #"\" + FormattedFileName(formattedDate);
}
public IEnumerable<DateTime> IterateOverDateRange(ForexExchange exchange, DateTime start, DateTime end)
{
for (var day = start.Date; day.Date <= end.Date; day = day.AddDays(1))
if (exchange.IsOpenDuringBar(day.Date, day.Date.AddDays(1), false))
{
yield return day;
}
}
}
}

I figured out what was happening.
I had an old version of TradingDaysFileChecker.cs in the Documents folder of my system that I had backed up for some reason.
In that version all the file handling logic was inside Program.cs.
I refactored and extracted out the file handling to the new class.
For some reason when I was running the script, it was still using that old copy, even though it was not in the solution folder.
That's why the change in the class name and appeared to happen, it was jumping into the Program.cs and Main method of that other file, pulling it up from my Documents folder.
How that happened, I do not know.
I deleted the file from my Documents folder and now it is behaving correctly.

Related

What is the difference between creating a new guid instance or selecting in Visual Studio tools > create guid?

In my state script I select Tools > Create GUID > New GUID > Copy
The script is looking like this now :
The guide is not the same as in the screenshot it's just for example.
The problem is that on each object I want to add to this state script format I need manually to generate a new GUID copy it and paste it to the code and it's a bit annoying. So I wonder what is the difference between creating a new guid instance or selecting in visual studio tools > create guide.
This is when creating a new instance :
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateGuid : MonoBehaviour
{
public string uniqueGuidID;
private Guid guidID;
public void GenerateGuidNum()
{
guidID = Guid.NewGuid();
uniqueGuidID = guidID.ToString();
}
}
I wonder why not use the same new instance technic in both cases, why or what the tool for creating guide number 5 is for ?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateTest : MonoBehaviour, IStateQuery
{
private State m_state = new State();
public Guid UniqueId => Guid.Parse("571E6219-DFD4-4893-A3B0-F9A151BFABFE");
private class State
{
public bool s1;
// bool the kid holding the navi is true
}
public string GetState()
{
return JsonUtility.ToJson(m_state);
}
public void SetState(string jsonString)
{
m_state = JsonUtility.FromJson<State>(jsonString);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
I will edit and update the usage of it :
With this script :
using System;
public interface IStateQuery
{
string GetState();
void SetState(string jsonString);
Guid UniqueId { get; }
}
In the TestState script I'm using the IStateQuery :
public class StateTest : MonoBehaviour, IStateQuery
Then use it like this in the Save and Load methods :
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SaveLoad : MonoBehaviour
{
public FadeInOutSaveGameText fadeInOutSaveGame;
public float timeToStartSaving;
public float savingFadeInOutTime;
private string saveString;
private void Awake()
{
SaveSystem.Init();
}
public void Save(string Folder, string FileName)
{
var objectsToSave = UpdateObjectsToSave();
SaveGame saveGame = new SaveGame();
saveGame.saveObjects = new List<SaveObject>();
for (int i = 0; i < objectsToSave.Count; i++)
{
SaveObject saveObject = new SaveObject();
saveObject.transformSaver = new TransformSaver();
Debug.Log($"{i}");
Debug.Log($"{objectsToSave[i].name}");
saveObject.gameObjectUniqueID = objectsToSave[i].GetComponent<GenerateGuid>().uniqueGuidID;
var x = objectsToSave[i].GetComponents<Component>();
var stateQueryComponent = x.Where(component => component is IStateQuery).ToList();
List<KeyToValue> componentsState = new List<KeyToValue>();
foreach (var z in stateQueryComponent)
{
var w = z as IStateQuery;
componentsState.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
}
saveObject.transformSaver.position = objectsToSave[i].transform.position;
saveObject.transformSaver.rotation = objectsToSave[i].transform.rotation;
saveObject.transformSaver.scaling = objectsToSave[i].transform.localScale;
saveObject.componentsState = componentsState;
saveGame.saveObjects.Add(saveObject);
}
string json = JsonUtility.ToJson(saveGame);
if (Folder == null && FileName == null)
{
SaveSystem.Save(json);
}
else
{
SaveSystem.Save(Folder, FileName, json);
}
}
public void Load(string Folder, string FileName)
{
var objectsToLoad = UpdateObjectsToSave();
Dictionary<string, GameObject> uniqueIdToObject = objectsToLoad
.ToDictionary(o => o.GetComponent<GenerateGuid>().uniqueGuidID, o => o);
saveString = SaveSystem.Load(Folder, FileName);
if (saveString != null)
{
SaveGame saveGame = JsonUtility.FromJson<SaveGame>(saveString);
foreach (var saveObject in saveGame.saveObjects)
{
List<KeyToValue> loadedComponents = saveObject.componentsState;
if (uniqueIdToObject.ContainsKey(saveObject.gameObjectUniqueID))
{
var objectToSetState = uniqueIdToObject[saveObject.gameObjectUniqueID];
objectToSetState.transform.position = saveObject.transformSaver.position;
objectToSetState.transform.rotation = saveObject.transformSaver.rotation;
objectToSetState.transform.localScale = saveObject.transformSaver.scaling;
var y = objectToSetState.GetComponents<Component>();
var z = y.Where(component => component is IStateQuery).ToList();
Dictionary<string, IStateQuery> zz = z.ToDictionary(sq => (sq as IStateQuery).UniqueId.ToString(), sq => sq as IStateQuery);
foreach (KeyToValue keyvalue in loadedComponents)
{
zz[keyvalue.Key].SetState(keyvalue.Value);
}
}
}
}
}
private List<GameObject> UpdateObjectsToSave()
{
var objectsWithGenerateGuid = GameObject.FindObjectsOfType<GenerateGuid>().ToList();
var objectsToSave = new List<GameObject>();
if (objectsWithGenerateGuid.Count > 0 && objectsToSave.Count == 0)
{
for (int i = 0; i < objectsWithGenerateGuid.Count; i++)
{
objectsToSave.Add(objectsWithGenerateGuid[i].gameObject);
}
}
return objectsToSave;
}
public IEnumerator AuatomaticSaveWithTime()
{
yield return new WaitForSeconds(timeToStartSaving);
Save(null, null);
StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
}
public IEnumerator SaveWithTime(string Folder, string FileName)
{
yield return new WaitForSeconds(timeToStartSaving);
Save(Folder, FileName);
StartCoroutine(fadeInOutSaveGame.OverAllTime(savingFadeInOutTime));
}
}
Depends on what you want, really.
The Visual Studio tool is meant to generate guid you are free to use for whatever you like. It isn't tied to your code in any way. You can of course use these values as static resources for your app, so they will always be the same at runtime.
The Guid.NewGuid will generate a new Guid value whenever your code runs. It will always be dynamic, even for the same object. You run the same app today and tomorrow, you'll get different guids.
Based on your comments, my understanding is that you really are looking for an easier way to inject static guids in your code editor to uniquely identify component types. If that's the case, have a look at the following extension:
https://marketplace.visualstudio.com/items?itemName=florians.InsertGUIDCommand
It will allow you to use SHIFT-ALT-G to inject a brand new guid value in your code. It should save you a few mouse clicks. ;)

OpenNLP.Net inputStreamFactory : Error on attempt to load file

Hy,
I am pretty rookie to OpenNLP.Net and am a little bit lost on basic step.
I looked at some java code and try to convert it in C# but I think I am quite wrong given that I don't find any C# code
Right now I am trying to run this code located in the main
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using opennlp.tools.doccat;
using opennlp.tools.tokenize;
using opennlp.tools.util;
public class Account
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime DOB { get; set; }
}
namespace Loading_OpenNLP
{
class Program
{
static void Main(string[] args)
{
Account account = new Account
{
Name = "John Doe",
Email = "john#microsoft.com",
DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json);
getNLPModel();
string pause = Console.ReadLine();
}
static void getNLPModel()//java.io.File openNLPTraining)
{
InputStreamFactory inputStreamFactory = new MarkableFileInputStreamFactory(new java.io.File("D:\\text.txt"));
ObjectStream lineStream = new PlainTextByLineStream(inputStreamFactory, "UTF-8");
ObjectStream sampleStream = new DocumentSampleStream(lineStream);
}
}
}
It compiles but the File is not Found ... What's wrong?
You can implement InputStreamFactory by your own.
Here is F# sample that train custom NER model, InputStreamFactory is implemented using F# object expressions
open java.nio.charset
open java.io
#I "../packages/OpenNLP.NET/lib/"
#r "opennlp-tools-1.8.4.dll"
#r "opennlp-uima-1.8.4.dll"
open opennlp.tools.util
open opennlp.tools.namefind
let train (inputFile:string) =
let factory =
{ new InputStreamFactory with
member __.createInputStream () =
new FileInputStream(inputFile) :> InputStream }
let lineStream = new PlainTextByLineStream(factory, StandardCharsets.UTF_8)
use sampleStream = new NameSampleDataStream(lineStream)
let nameFinderFactory = new TokenNameFinderFactory()
let trainingParameters = new TrainingParameters();
//trainingParameters.put(TrainingParameters.ITERATIONS_PARAM, "5");
//trainingParameters.put(TrainingParameters.CUTOFF_PARAM, "200");
NameFinderME.train ("en", "person", sampleStream, trainingParameters, nameFinderFactory)
in C# the same code may look like this
using java.nio.charset;
using java.io;
using opennlp.tools.util;
using opennlp.tools.namefind;
namespace OpenNLP.Train
{
class MyStreamFactory: InputStreamFactory
{
public Factory(string fileName) => _filename = fileName;
private readonly string _filename;
public InputStream createInputStream()
=> new FileInputStream(_filename);
}
class Program
{
static void Main(string[] args)
{
var factory = new MyStreamFactory("D:\\text.txt");
var lineStream = new PlainTextByLineStream(factory, StandardCharsets.UTF_8);
var sampleStream = new NameSampleDataStream(lineStream);
var nameFinderFactory = new TokenNameFinderFactory();
var trainingParameters = new TrainingParameters();
var model = NameFinderME.train("en", "person", sampleStream, trainingParameters, nameFinderFactory);
}
}
}

Why conversion between default system datetime to PersianCalendar is not working?

I have a dateTime stored in database using this line of code:
var now=DateTime.Now;
so after it stored, the data is like this in database and also after recalling the entity:
2019-01-26 17:27:46.297
when i try to convert it to another culture datetime using this method:
public static string ToPersianDate(this DateTime t)
{
var pc = new PersianCalendar();
return $"{pc.GetYear(t)}/{pc.GetMonth(t)}/{pc.GetDayOfMonth(t)}";
}
after using this method :
var persianDate=now.ToPersianDate();
I get this string as a result:
2019/01/26
But I expected to get this result:
1397/11/06
Here is a complete example that converts time to PersianCalender,
using System;
using System.Globalization;
namespace ConsoleApp1
{
public class Program
{
public static void Main(String[] args)
{
var date = DateTime.Now;
var str = date.ToPersianDate();
Console.WriteLine(str);
Console.Read();
}
}
public static class Extender
{
public static string ToPersianDate(this DateTime t)
{
var pc = new PersianCalendar();
return $"{pc.GetYear(t)}/{pc.GetMonth(t)}/{pc.GetDayOfMonth(t)}";
}
}
}
your problem its not reproducible, code is attached for further reference

How do I access members of a class in C# like I think I could do in c++?

How do I access members of a class in C# like I think I could do in c++ ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DateAndMoney
{
class InputNode
{
DateTime dateTime;
string dollarAmount;
}
class Program
{
public static void ReadFile(string filename)
{
InputNode inputNode = new InputNode();
if (System.IO.File.Exists(filename))
{
var reader = new StreamReader(File.OpenRead(filename));
while (!reader.EndOfStream)
{
var input = reader.ReadLine();
var values = input.Split(',');
inputNode.dateTime = values[0];
inputNode.dollarAmount = values[1];
}
}
}
static void Main(string[] args)
{
string filename;
Console.WriteLine("enter path and file name of input file");
filename = Console.ReadLine();
ReadFile(filename);
}
}
}
The precompiler does not like:
inputNode.dateTime = values[0];
inputNode.dollarAmount = values[1];
And this change changes nothing
struct InputNode
{
DateTime dateTime;
string dollarAmount;
}
If you change
class InputNode
{
DateTime dateTime;
string dollarAmount;
}
to
class InputNode
{
public DateTime dateTime;
public string dollarAmount;
}
You can then access them as you were trying, although you'd need to convert your text to date to put it in the date time.
By default in C# fields are private, so you can't access it. Better to use Properties to set and get values
In your case:
class InputNode
{
public DateTime DateTime{get;set;}
public string DollarAmount{get;set}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DateAndMoney
{
public class InputNode
{
public DateTime dateTime;
public string dollarAmount;
}
public class Program
{
public static void ReadFile(string filename)
{
InputNode inputNode = new InputNode();
if (System.IO.File.Exists(filename))
{
var reader = new StreamReader(File.OpenRead(filename));
while (!reader.EndOfStream)
{
var input = reader.ReadLine();
var values = input.Split(',');
try
{
inputNode.dateTime = Convert.ToDateTime(values[0]);
inputNode.dollarAmount = Convert.ToDouble(values[1]);
}
catch(Exception e)
{}
}
}
}
public static void Main(string[] args)
{
string filename;
Console.WriteLine("enter path and file name of input file");
filename = Console.ReadLine();
ReadFile(filename);
}
}
}
This did it.
class InputNode
{
public DateTime dateTime;
public string dollarAmount;
}
class Program
{
public static void ReadFile(string filename)
{
InputNode inputNode = new InputNode();
if (System.IO.File.Exists(filename))
{
var reader = new StreamReader(File.OpenRead(filename));
while (!reader.EndOfStream)
{
var input = reader.ReadLine();
var values = input.Split(',');
inputNode.dateTime = Convert.ToDateTime(values[0]);
inputNode.dollarAmount = values[1];
}
}
}
First of all ( as everyone else said ) you need to make the fields "visible" for the rest of the application.
class InputNode
{
// DateTime dateTime;
internal DateTime dateTime;
public string dollarAmount;
// string dollarAmount;
}
You can read more about access modifiers here
Second thing is that you're assigning string to the DateTime type field. In C# you have bunch of converters which can cast from one type into another and also you can create your own converters using this example
You could create public method, which returns the value of a particular member (recommended) or make the members themselves public.
You can use for reference (https://msdn.microsoft.com/en-us/library/st6sy9xe.aspx)
class InputNode
{
private DateTime dateTime;
private string dollarAmount;
public DateTime GetDate()
{
return dateTime;
}
}

Seperation of db connection in seperate class file doesn't work

Rookie here needing help. I'm trying to build a prototype with the neo4j .NET driver using Bolt. My aim with the prototype is building multiple methods for creation and searches in the db, but only one method to connect to the db - here I'm continuously having problems. I've Googled all weekend for examples, tutorials and traversed through the documentation and now I need your help.
Programs.cs
using System;
using DTUneo4jConsoleApp.Db;
namespace DTUneo4jConsoleApp
{
public class Program
{
public static void Main(string[] args)
{
MyProperties something = new MyProperties();
neo4jdb session = new neo4jdb();
session.Run($"CREATE (a:Person {{name:'{something.Name}', title:'{something.Title}'}})");
var result = session.Run($"MATCH (a:Person) WHERE a.name = '{something.Name}' RETURN a.name AS name, a.title AS title");
foreach (var record in result)
{
Console.WriteLine($"{record["title"].As<string>()} {record["name"].As<string>()}");
}
Console.ReadKey();
}
}
public class MyProperties
{
public string Name { get; set; }
public string Title { get; set; }
}
}
db.cs
using Neo4j.Driver.V1;
namespace DTUneo4jConsoleApp.Db
{
public class neo4jdb
{
public static void Connection()
{
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("user", "pass")))
using (var session = driver.Session())
{
}
}
}
}
When I instantiate the neo4jdb session = new neo4jdb(); I don't get i.e. the Run() method from the driver.
I hope someone can guide me in the right direction.
I am doing it like this:
public static List<IStatementResult> ExecuteCypher(List<Statement> statements)
{
List<IStatementResult> results = new List<IStatementResult>();
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("user", "pass")))
{
using (var session = driver.Session())
{
using (var tx = session.BeginTransaction())
{
foreach (var statement in statements)
{
results.Add(tx.Run(statement));
}
tx.Success();
}
}
}
return results;
}
usage:
MyProperties something = new MyProperties();
var createCypher = new Statement($"CREATE (a:Person {{name:'{something.Name}', title:'{something.Title}'}})");
var matchCypher = new Statement($"MATCH (a:Person) WHERE a.name = '{something.Name}' RETURN a.name AS name, a.title AS title");
var statements = new List<Statement>();
statements.Add(createCypher);
statements.Add(matchCypher);
var results = ExecuteCypher(statements);
//you can now query result for each statement or
//your query your desired result
foreach (var record in results.Last())
{
Console.WriteLine($"{record["title"].As<string>()} {record["name"].As<string>()}");
}
In this way I can also create multiple records in a single transaction and get the result of all those as well.

Categories

Resources