i am parsing a path from a directory location:
assuming that InitialPath = #"C:\Users\username\Documents\Visual Studio 2015\Projects"
and i have a loop of:
var list = new List<string>();
foreach(var folder in Directory.GetDirectories(InitialPath) {
var folder = Path.GetFileName(folder);
var file = Path.GetFileName(Directory.GetFiles(folder, "*.sln").Single());
list.Add(InitialPath + "\\" + folder + "\\" + file); //would then result something like "C:\Users\username\Documents\Visual Studio 2015\Projects\Folder1\Project1inFolder1.sln"
}
if i try a path from the list and assign it to a richbox as its .text value, it returns a single line text.
but when i'm displaying it on a MessageBox, the string is being broken into two lines as below:
i need to force it not to be broken into several lines. i mean, i need it to be a single line string only no matter the length of the string because Process.Start() wont accept the string because it gets cut into lines. see below for reference:
PS: sorry for not being able to explain my question eligibly, english is not my natural language
just in case, here is my code snippet:
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
namespace The_Projects {
public partial class MainForm : MaterialForm {
public MainForm() {
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
public class DirectoryInformation {
private string _FolderName;
private string _Solution;
private DateTime _Created;
private DateTime _Accessed;
private DateTime _Modified;
private string _SecIdentity;
private string _NTAccount;
private double _FileSize;
private int _FileCount;
public string FolderName {
get { return _FolderName; }
set { _FolderName = value; }
}
public string Solution {
get { return _Solution; }
set { _Solution = value; }
}
public DateTime Created {
get { return _Created; }
set { _Created = value; }
}
public DateTime Accessed {
get { return _Accessed; }
set { _Accessed = value; }
}
public DateTime Modified {
get { return _Modified; }
set { _Modified = value; }
}
public string SecIdentity {
get { return _SecIdentity; }
set { _SecIdentity = value; }
}
public string NTAccount {
get { return _NTAccount; }
set { _NTAccount = value; }
}
public double FileSize {
get { return _FileSize; }
set { _FileSize = value; }
}
public int FileCount {
get { return _FileCount; }
set { _FileCount = value; }
}
}
public string InitialPath = #"X:\_\Document\Visual Studio 2015\Projects\";
public string FolderPath = string.Empty;
public string Solution = string.Empty;
private void MainForm_Load(object sender, EventArgs e) {
var projectList = new List<DirectoryInformation>();
foreach(var dirs in Directory.GetDirectories(InitialPath)) {
var ac = File.GetAccessControl(dirs);
var di = new DirectoryInfo(dirs);
var dirInf = new DirectoryInformation() {
FolderName = Path.GetFileName(dirs),
Solution = Path.GetFileName(Directory.GetFiles(dirs, "*.sln").Single()),
Created = Directory.GetCreationTime(dirs),
Accessed = Directory.GetLastAccessTime(dirs),
Modified = Directory.GetLastWriteTime(dirs),
SecIdentity = ac.GetOwner(typeof(SecurityIdentifier)).ToString(),
NTAccount = ac.GetOwner(typeof(SecurityIdentifier)).Translate(typeof(NTAccount)).ToString(),
FileSize = (double) di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(x => x.Length) / 1024000,
FileCount = Directory.GetFiles(dirs, "*.*", SearchOption.AllDirectories).Count()
};
projectList.Add(dirInf);
}
lstProjectList.DataSource = projectList;
lstProjectList.DisplayMember = "FolderName";
}
private void lstProjectList_SelectedIndexChanged(object sender, EventArgs e) {
var project = lstProjectList.SelectedValue as DirectoryInformation;
lblFolder.Text = project.FolderName;
lblCreated.Text = project.Created.ToString();
lblAccess.Text = project.Accessed.ToString();
lblModified.Text = project.Modified.ToString();
lblIdentifier.Text = project.SecIdentity;
lblOwner.Text = project.NTAccount;
lblSize.Text = project.FileSize.ToString("F2") + " MB";
lblCount.Text = project.FileCount.ToString();
FolderPath = InitialPath + project.FolderName;
Solution = FolderPath + "\\" + project.Solution;
}
private void btnOpenProject_Click(object sender, EventArgs e) {
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
//Clipboard.SetText(Solution);
}
private void btnOpenFolder_Click(object sender, EventArgs e) {
Process.Start("explorer.exe", FolderPath);
}
}
}
It's just the way your MessageBox is wrapping text. You've got two options here:
Create a custom Forms class
Create a form dialog just for showing messages
EDIT:
Change this:
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
to
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", "\"" + Solution + "\"");
What's happening here is the second parameter to the Process.Start method is treated as argument(s) for the executable given by the first parameter. So what process.start does is the equivalent (but not quite the same) of opening the command prompt and typing out:
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" X:\_\Document\Visual Studio 2015\.....
and the command prompt treats (space) as a parameter separator, so it treats X:\_\Document\Visual as one parameter, Studio as the next and so on. When you use "\"" around the string you're telling Process.Start that the whole thing (including spaces) is a single parameter.
Your sample had some bugs in it, for me this worked and I got all *.sln files
//this is just to show that you can get short file name if you need FileInfo
var list = new Dictionary<string, string>();
var files = Directory.GetFiles(InitialPath, "*.sln", SearchOption.AllDirectories);
foreach (var file in files)
{
FileInfo fileInfo = new FileInfo(file);
list.Add(fileInfo.Name, file);
}
Process.Start(list.FirstOrDefault().Value);
On my computer starts with no problems.
But if you want a devenv.exe start with a solution open you do it like so
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", #"devenv/""" + fullFilePath + #"""");
you need the command in arguments devenv/ and you must you must enclose paths in double quotation marks ("fullFilePath").
Related
I have the following code where I am trying to enumerate through files on a shared drive, collect properties for each file, and then return each entry from that collection.
Visual Studio gives me "CS0161: 'Program.EnumerateYourFiles(string)': not all code paths return a value." error when I hover over the EnumerateYourFiles method. I am guessing that it has to do with the fact that the "l" variable I am trying to return is out-of-scope. How do I get that "l" variable into scope so it returns for the function?
using System;
using System.IO;
using System.Collections.Generic;
namespace FileShareMachine
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(EnumerateYourFiles(#"E:\"));
}
public static object EnumerateYourFiles(string pathToSearch)
{
string filePath = pathToSearch;
DirectoryInfo currentParentFileList = new DirectoryInfo(filePath);
DirectoryInfo[] listOfSubDirectories = currentParentFileList.GetDirectories();
List<string> listOfAllFiles = new System.Collections.Generic.List<string>();
foreach (var parentPath in listOfSubDirectories)
{
string pathForEnumeration = parentPath.ToString();
DirectoryInfo individualSubFolder = new DirectoryInfo(pathForEnumeration);
try
{
foreach (var eachFile in individualSubFolder.EnumerateFiles("*", SearchOption.AllDirectories))
{
string individualPaths = eachFile.FullName.ToString();
string lastAccessed = eachFile.LastAccessTime.ToString();
string fileSize = eachFile.Length.ToString();
string creationTime = eachFile.CreationTime.ToString();
string lastWriteTime = eachFile.LastWriteTime.ToString();
string fileDirectory = eachFile.Directory.ToString();
//The following works like a dream. This is how you write to a file. You need an array or list
listOfAllFiles.Add(individualPaths);
listOfAllFiles.Add(fileSize);
listOfAllFiles.Add(fileDirectory);
listOfAllFiles.Add(creationTime);
listOfAllFiles.Add(lastAccessed);
listOfAllFiles.Add(lastWriteTime);
}
}
catch (System.UnauthorizedAccessException)
{
bool errorThrown = true;
if (errorThrown)
{
Console.WriteLine("The following path had an access error {0}", individualSubFolder);
continue;
}
else
{
continue;
}
}
}
//return listOfSubDirectories;
foreach(object l in listOfAllFiles)
{
return l;
}
}
}
}
foreach(object l in listOfAllFiles)
{
return l;
}
isn't going to work.
Try
return listOfAllFiles
instead.
Consider returning something other than an object, like IEnumerable<string>, unless your use case requires object (it's not unprecedented; there are places in WPF that are like that).
If you're trying to return one item from the list each time you call the method, try
yield return l;
instead. Your method should then return a string.
I'm building a small C# program to collect information on the used nuget packages
This is every piece of info i want:
public class Package
{
public string Version { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Count { get; set; }
public List<string> Versions { get; set; }
}
And this is how i collect all the info:
public partial class MainWindow : Window
{
public Dictionary<string, Package> Packages;
public string Folder;
public SaveFileDialog saveFileDialog = new SaveFileDialog();
public FolderBrowserDialog folderBrowseDialog = new FolderBrowserDialog();
public MainWindow()
{
InitializeComponent();
Packages = new Dictionary<string, Package>();
}
private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
DialogResult result = folderBrowseDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
DoneLbl.Content = "Started";
Folder = folderBrowseDialog.SelectedPath;
foreach (string fileName in Directory.EnumerateFiles(Folder, "packages.config", SearchOption.AllDirectories))
{
var file = new PackageReferenceFile(fileName);
foreach (PackageReference packageReference in file.GetPackageReferences())
{
if (Packages.ContainsKey(packageReference.Id))
{
Packages[packageReference.Id].Count++;
if (Packages[packageReference.Id].Versions.Contains(packageReference.Version.ToString()))
{
}
else
{
var oldVersion = new Version(Packages[packageReference.Id].Version);
var newVersion = new Version(packageReference.Version.ToString());
if (newVersion > oldVersion)
{
Packages[packageReference.Id].Version = packageReference.Version.ToString();
}
Packages[packageReference.Id].Versions.Add(packageReference.Version.ToString());
}
}
else
{
var package = new Package();
package.Name = packageReference.Id;
package.Count = 1;
package.Version = packageReference.Version.ToString();
package.Versions = new List<string>();
package.Versions.Add(packageReference.Version.ToString());
Packages.Add(packageReference.Id, package);
}
}
DoneLbl.Content = "Done";
}
}
}
private void ExportBtn_Click(object sender, RoutedEventArgs e)
{
saveFileDialog.Filter = "Text File | *.txt";
DialogResult result = saveFileDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string lines = "Nuget Packages for \r\n" + Folder + "\r\n";
foreach (var Package in Packages)
{
lines += "********************\r\n";
lines += "Name: " + Package.Value.Name + "\r\n";
lines += "Version: " + Package.Value.Version + "\r\n";
lines += "Different Versions: " + Package.Value.Versions.Count + "\r\n";
lines += "Description: " + Package.Value.Description + "\r\n";
lines += "Count: " + Package.Value.Count + "\r\n";
}
StreamWriter file = new StreamWriter(saveFileDialog.FileName);
file.WriteLine(lines);
file.Close();
}
}
}
This gets everything through "Nuget.Core" nuget package.
But i still lack the description. Is there a way to find package description through this nuget package? Or any other way i can use to find package descriptions?
I looked into the Nuget V3 package as described here:
https://learn.microsoft.com/en-us/nuget/api/nuget-api-v3
Using this i made a GetDescription Method
public async void GetDescription(string name, Package package)
{
List<Lazy<INuGetResourceProvider>> providers = new List<Lazy<INuGetResourceProvider>>();
providers.AddRange(Repository.Provider.GetCoreV3()); // Add v3 API support
PackageSource packageSource = new PackageSource("https://api.nuget.org/v3/index.json");
SourceRepository sourceRepository = new SourceRepository(packageSource, providers);
PackageMetadataResource packageMetadataResource = await sourceRepository.GetResourceAsync<PackageMetadataResource>();
IEnumerable<IPackageSearchMetadata> searchMetadata = await packageMetadataResource.GetMetadataAsync(name, true, true, new Logger(), CancellationToken.None);
package.Description = searchMetadata.First().Description;
}
And called it in the code that adds new packages to the list.
{
var package = new Package();
package.Name = packageReference.Id;
package.Count = 1;
GetDescription(packageReference.Id, package);
package.Version = packageReference.Version.ToString();
package.Versions = new List<string>();
package.Versions.Add(packageReference.Version.ToString());
Packages.Add(packageReference.Id, package);
}
I'll later look to get everything trough Nuget V3 but for now everything works as it should.
I am newbie to fix protocol and quick fix programming. I am seeking a help on getting Trade Capture report from ICE. I have googled for the sample/ tutorial to use quick fix/n to get the trade report but I am not being able to get sufficient output of it.
My problem is to get Trade Capture report or deal information for this I tried using TradeCaptureReportRequest, TradeCaptureReportRequestAck, TradeCaptureReport classes but somehow its now working.
A simple how to extract information would be a great help.
thanking everyone out there in advance.
Ok I am posting as an answer because it's going to be way too long for a comment. Please keep in mind that I have written custom constants, message types, etc (I wrote my acceptor server as well, so I'm not restricted by ICE constants/enums). You will need to determine what fields are required by ICE and make changes - this will not be easy to copy/paste...
First, you need to make sure you have all required files in and referenced. I create a folder called "fix" in my project, and copy all fix files into it. These need to be (at least 1) FixXXX.xml file, if you're using FIX50SP1 or 2, you need to also have FIXT11.xml. Along with the .xml files, you need to have an initiator.cfg file (assuming you're making an initiator, no a server, otherwise this will need to be "acceptor.cfg" but again, it sounds like you're trying to connect to ICE, so initiator is the correct usage. Finally, you will need to have a QuickFix.dll. My tree looks as below:
I am not going to go through the XML files - you will need to just learn that - it is very confusing and takes time.. especially if using FIXT11.XML along with SP1 or 2.
Your initiator.cfg should be similar to below:
# default settings for sessions
[DEFAULT]
FileStorePath=store
FileLogPath=log
ConnectionType=initiator
ReconnectInterval=60
SenderCompID=[Enter yours]
ResetOnLogon=Y
ResetOnLogout=Y
ResetOnDisconnect=Y
[SESSION]
BeginString=FIXT.1.1
TargetCompID=[Enter ICE Acceptor]
DefaultApplVerID=FIX.5.0
StartTime=12:30:00
EndTime=21:30:00
# overide default setting for RecconnectInterval
ReconnectInterval=30
HeartBtInt=30
SocketConnectPort=[From ICE]
# (optional) only listen for incoming connections on a specific host
#SocketConnectHost=127.0.0.1
SocketConnectHost=[ICE Ip Address- from your documentation/registration]
DataDictionary=..\..\fix\FIX50.xml
TransportDataDictionary=..\..\fix\FIXT11.xml
Ok, assuming that you have QuickFix.dll imported and referenced, and your initiator.cfg properly connected, it's actually fairly simple:
Create a Class that handles everything. Ignore AddToLB, that is a testing function.
public class TCT_Fix : Control, IApplication
{
private readonly string username = [removed]
private readonly string password = [removed]
public string InitiatorID;
SessionID sessionID;
public bool running;
SessionSettings settings;
IMessageStoreFactory storeFactory;
ILogFactory logFactory;
SocketInitiator initiator;
public event EventHandler AddToLB;
public event EventHandler AddToAdmin;
public void StopIt()
{
if (sessionID == null) return;
try
{
Session.LookupSession(sessionID).Disconnect("Stopping");
settings.Remove(sessionID);
settings = null;
initiator.Dispose();
settings = new SessionSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fix", "initiator.cfg"));
storeFactory = new FileStoreFactory(settings);
logFactory = new FileLogFactory(settings);
initiator = new SocketInitiator(
this,
storeFactory,
settings,
logFactory);
}
catch { }
}
public void FromApp(QuickFix.Message msg, SessionID sessionID)
{
var sMsg = "FROM APP: " + msg.ToString();
AddToLB(sMsg, null);
if (msg.Header.GetField(35) == "TC") //Cash
{
DateTime dtTdate;
float fPrice;
int Qty;
int OrdType;
bool BPisBuyer;
DateTime.TryParse(msg.GetField(CustomConstants.TDATE),out dtTdate);
string BPSide = msg.GetField(CustomConstants.BP_SIDE);
float.TryParse(msg.GetField(CustomConstants.F_PRICE), out fPrice);
int.TryParse(msg.GetField(CustomConstants.QTY), out Qty);
string TCTReference = msg.GetField(CustomConstants.TCT_REF);
string BPAcct = msg.GetField(CustomConstants.BP_COMPANY);
int.TryParse(msg.GetField(CustomConstants.ORDER_TYPE), out OrdType);
string ExecBkr = msg.GetField(CustomConstants.EXEC_BKR);
string CounterParty = msg.GetField(CustomConstants.COUNTER_PARTY);
BPisBuyer = msg.GetField(CustomConstants.IS_BUYER) == "Y";
string BPTrader = msg.GetField(CustomConstants.BP_TRADER);
string CounterTrader = msg.GetField(CustomConstants.COUNTER_TRADER);
string Grade = msg.GetField(CustomConstants.GRADE);
string Location = msg.GetField(CustomConstants.LOCATION);
string CycDt = msg.GetField(CustomConstants.CYCLE_DATE);
string DelMo = msg.GetField(CustomConstants.DELIVER_MONTH);
string Terms = msg.GetField(CustomConstants.TERMS);
string Payment = msg.GetField(CustomConstants.PAYMENT);
string Origin = msg.GetField(CustomConstants.ORIGIN);
string NumOfCyc = msg.GetField(CustomConstants.NUM_OF_CYCLES);
string Via = msg.GetField(CustomConstants.VIA);
string MoveMo = msg.GetField(CustomConstants.MOVE_MONTH);
string Comment = msg.GetField(CustomConstants.COMMENT);
}
else if (msg.Header.GetField(35) == "TE") //EFP
{
DateTime dtTdate;
float fPrice;
int Qty;
int OrdType;
bool BPisBuyer;
bool IsWater;
DateTime.TryParse(msg.GetField(CustomConstants.TDATE), out dtTdate);
string BPSide = msg.GetField(CustomConstants.BP_SIDE);
float.TryParse(msg.GetField(CustomConstants.F_PRICE), out fPrice);
int.TryParse(msg.GetField(CustomConstants.QTY), out Qty);
string TCTReference = msg.GetField(CustomConstants.TCT_REF);
string BPAcct = msg.GetField(CustomConstants.BP_COMPANY);
int.TryParse(msg.GetField(CustomConstants.ORDER_TYPE), out OrdType);
string ExecBkr = msg.GetField(CustomConstants.EXEC_BKR);
string CounterParty = msg.GetField(CustomConstants.COUNTER_PARTY);
BPisBuyer = msg.GetField(CustomConstants.IS_BUYER) == "Y";
string BPTrader = msg.GetField(CustomConstants.BP_TRADER);
string CounterTrader = msg.GetField(CustomConstants.COUNTER_TRADER);
string Grade = msg.GetField(CustomConstants.GRADE);
string Location = msg.GetField(CustomConstants.LOCATION);
string CycDt = msg.GetField(CustomConstants.CYCLE_DATE);
string DelMo = msg.GetField(CustomConstants.DELIVER_MONTH);
string Terms = msg.GetField(CustomConstants.TERMS);
string Payment = msg.GetField(CustomConstants.PAYMENT);
string Origin = msg.GetField(CustomConstants.ORIGIN);
string NumOfCyc = msg.GetField(CustomConstants.NUM_OF_CYCLES);
string Via = msg.GetField(CustomConstants.VIA);
string MoveMo = msg.GetField(CustomConstants.MOVE_MONTH);
string Comment = msg.GetField(CustomConstants.COMMENT);
IsWater = msg.GetField(CustomConstants.ISWATER) == "Y";
string BPFloorBkr = msg.GetField(CustomConstants.BP_FLOOR_BKR);
string CounterFloorBkr = msg.GetField(CustomConstants.COUNTER_FLOOR_BKR);
string Diff = msg.GetField(CustomConstants.DIFFERENCE);
string MercMo = msg.GetField(CustomConstants.MERC_MO);
string MercPr = msg.GetField(CustomConstants.MERC_PRICE);
}
else if (msg.Header.GetField(35) == "TI") //Index
{
DateTime dtTdate;
float fPrice;
int Qty;
int OrdType;
bool BPisBuyer;
bool IsWater;
DateTime.TryParse(msg.GetField(CustomConstants.TDATE), out dtTdate);
string BPSide = msg.GetField(CustomConstants.BP_SIDE);
float.TryParse(msg.GetField(CustomConstants.F_PRICE), out fPrice);
int.TryParse(msg.GetField(CustomConstants.QTY), out Qty);
string TCTReference = msg.GetField(CustomConstants.TCT_REF);
string BPAcct = msg.GetField(CustomConstants.BP_COMPANY);
int.TryParse(msg.GetField(CustomConstants.ORDER_TYPE), out OrdType);
string ExecBkr = msg.GetField(CustomConstants.EXEC_BKR);
string CounterParty = msg.GetField(CustomConstants.COUNTER_PARTY);
BPisBuyer = msg.GetField(CustomConstants.IS_BUYER) == "Y";
string BPTrader = msg.GetField(CustomConstants.BP_TRADER);
string CounterTrader = msg.GetField(CustomConstants.COUNTER_TRADER);
string Grade = msg.GetField(CustomConstants.GRADE);
string Location = msg.GetField(CustomConstants.LOCATION);
string CycDt = msg.GetField(CustomConstants.CYCLE_DATE);
string DelMo = msg.GetField(CustomConstants.DELIVER_MONTH);
string Terms = msg.GetField(CustomConstants.TERMS);
string Payment = msg.GetField(CustomConstants.PAYMENT);
string Origin = msg.GetField(CustomConstants.ORIGIN);
string NumOfCyc = msg.GetField(CustomConstants.NUM_OF_CYCLES);
string Via = msg.GetField(CustomConstants.VIA);
string MoveMo = msg.GetField(CustomConstants.MOVE_MONTH);
string Comment = msg.GetField(CustomConstants.COMMENT);
IsWater = msg.GetField(CustomConstants.ISWATER) == "Y";
string BPFloorBkr = msg.GetField(CustomConstants.BP_FLOOR_BKR);
string CounterFloorBkr = msg.GetField(CustomConstants.COUNTER_FLOOR_BKR);
string Diff = msg.GetField(CustomConstants.DIFFERENCE);
string MercMo = msg.GetField(CustomConstants.MERC_MO);
string MercPr = msg.GetField(CustomConstants.MERC_PRICE);
}
}
public void OnCreate(SessionID sessionID)
{
AddToAdmin("SESSION CREATED: " + sessionID.ToString(), null);
}
public void OnLogout(SessionID sessionID)
{
AddToAdmin("LOGOUT: " + this.sessionID.ToString(), null);
}
public void OnLogon(SessionID sessionID)
{
this.sessionID = sessionID;
AddToAdmin("LOG ON: " + this.sessionID.ToString(),null);
}
public void FromAdmin(QuickFix.Message msg, SessionID sessionID)
{
AddToAdmin("FROM ADMIN: " + msg.ToString(), null);
}
public void ToAdmin(QuickFix.Message msg, SessionID sessionID)
{
if (msg.Header.GetField(35).ToString() == "A")
{
msg.SetField(new QuickFix.Fields.Username(username));
msg.SetField(new QuickFix.Fields.Password(password));
}
AddToAdmin("TO ADMIN: " + msg.ToString(), null);
}
public void ToApp(QuickFix.Message msg, SessionID sessionID)
{
AddToLB("TO APP: " + msg.ToString(), null);
}
public void GetTestMessage(string msgType)
{
if (sessionID == null) return;
QuickFix.FIX50.TestMessage msg = new QuickFix.FIX50.TestMessage();
msg.TestType = msgType;
msg.Header.SetField(new QuickFix.Fields.MsgType("TEST"));
msg.SetField(new QuickFix.Fields.StringField(CustomConstants.TEST_TYPE, msgType));
Session.SendToTarget(msg, sessionID);
}
public TCT_Fix()
{
settings = new SessionSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fix", "initiator.cfg"));
storeFactory = new FileStoreFactory(settings);
logFactory = new FileLogFactory(settings);
initiator = new SocketInitiator(
this,
storeFactory,
settings,
logFactory);
}
public TCT_Fix(ref string initID)
{
InitiatorID = initID;
settings = new SessionSettings(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "fix", "initiator.cfg"));
storeFactory = new FileStoreFactory(settings);
logFactory = new FileLogFactory(settings);
initiator = new SocketInitiator(
this,
storeFactory,
settings,
logFactory);
}
public void RunIt()
{
if (running) return;
if(initiator.IsStopped)
{
try
{
initiator.Start(); //This can throw an error due to current set up. I would recommend making the connection,
//pulling data, and then closing the connection (polling) to ensure the initiator clears the
//log files
//reference http://lists.quickfixn.com/pipermail/quickfixn-quickfixn.com/2013q1/000747.html
//2013 issue, still unresolved... Restart app
}
catch(Exception ex)
{
if (MessageBox.Show("Error restarting initiator. Program will close due to file access. This is a Quickfix bug, not an issue with this program. Please restart." + Environment.NewLine + Environment.NewLine +
"Reference: http://lists.quickfixn.com/pipermail/quickfixn-quickfixn.com/2013q1/000747.html for more information. Click ok to copy link to clipboard. Click \"X\" to ignore.") == DialogResult.OK)
{
Clipboard.SetText("http://lists.quickfixn.com/pipermail/quickfixn-quickfixn.com/2013q1/000747.html");
}
throw new Exception(ex.ToString());
}
}
running = true;
}
}
Finally, to make it stand out (this is actually in the block above as well), you construct a message similar to below, keeping in mind that your ICE Message will have certain required fields that my "TestMessage" does not. I cannot give code from production though - sorry.
public void GetTestMessage(string msgType)
{
if (sessionID == null) return;
QuickFix.FIX50.TestMessage msg = new QuickFix.FIX50.TestMessage();
msg.TestType = msgType;
msg.Header.SetField(new QuickFix.Fields.MsgType("TEST"));
msg.SetField(new QuickFix.Fields.StringField(CustomConstants.TEST_TYPE, msgType));
Session.SendToTarget(msg, sessionID);
}
The learning curve is substantial. You will just need to keep playing around until you get it. Once you get it down though, it makes sense. Stick with it. Let me know if you need anything else.
I'm working on a project in which I am creating a IronPython compiler depend on IronPython ,
But I have some problem on debugging the Script and can use breakpoint ? could you please give me some help ? thanks. all my code is there: [https://github.com/heyxEvget/IronPython-Debugger]
public ScriptEngine GetEngine()
{
if (_engine != null)
return _engine;
_engine = Python.CreateEngine();
_engine.Runtime.IO.SetOutput(_stream, Encoding.UTF8);
_engine.Runtime.IO.SetErrorOutput(_stream, Encoding.UTF8);
string path = Environment.CurrentDirectory;
string ironPythonLibPath = string.Format(#"{0}\IronPythonLib.zip", path);
var paths = _engine.GetSearchPaths() as List<string> ?? new List<string>();
paths.Add(path);
paths.Add(ironPythonLibPath);
path = Environment.GetEnvironmentVariable("IRONPYTHONPATH");
if (!string.IsNullOrEmpty(path))
{
var pathStrings = path.Split(';');
paths.AddRange(pathStrings.Where(p => p.Length > 0));
}
_engine.SetSearchPaths(paths.ToArray());
return _engine;
}
private void GetPythonVarsInfo(ScriptScope scope)
{
_varList.Clear();
var items = scope.GetItems();
foreach (var item in items)
{
_varList.Add(new VarValue
{
VarName = item.Key,
Value = item.Value
});
}
valueListView.ItemsSource = _varList;
}
private void OnExecuteButtonClick(object sender, ItemClickEventArgs e)
{
string outPutString = string.Empty;
outPutString = "*************************************" +
"Excute Date: " + DateTime.Now.ToLocalTime().ToString(CultureInfo.InvariantCulture);
ExeceutePython(document, outPutString);
TabControl.SelectedIndex = 2;
}
private void ExeceutePython(EditorDocument document, string outPutString)
{
ScriptEngine engine = GetEngine();
string script = document.Text;
ScriptSource source = engine.CreateScriptSourceFromString(script);
ScriptScope scope = _engine.CreateScope();
try
{
source.Compile();
OutputTextBox.AppendText(outPutString + Environment.NewLine);
var result = source.Execute(scope);
if (result != null)
{
OutputTextBox.AppendText(engine.Operations.Format(result));
}
OutputTextBox.AppendText(Environment.NewLine);
GetPythonVarsInfo(scope);
}
catch (Exception ex)
{
var eo = engine.GetService<ExceptionOperations>();
var eoString = eo.FormatException(ex);
OutputTextBox.AppendText(eoString);
return;
}
}
Given this setup code to create the IronPython script engine
var engine = IronPython.Hosting.Python.CreateEngine(new Dictionary<string, object> { { "Debug", ScriptingRuntimeHelpers.True }});
Debug.Assert(engine.Runtime.Setup.DebugMode);
var source = engine.CreateScriptSourceFromFile("script.py");
dynamic result = source.Execute();
You can then use
System.Diagnostics.Debugger.Break()
inside your scripts to get the debugger to break.
You can use visual studio isolated shell for that
Visual Studio Isolated Shell
The end goal is to have some form of a data structure that stores a hierarchal structure of a directory to be stored in a txt file.
I'm using the following code and so far, and I'm struggling with combining dirs, subdirs, and files.
/// <summary>
/// code based on http://msdn.microsoft.com/en-us/library/bb513869.aspx
/// </summary>
/// <param name="strFolder"></param>
public static void TraverseTree ( string strFolder )
{
// Data structure to hold names of subfolders to be
// examined for files.
Stack<string> dirs = new Stack<string>( 20 );
if ( !System.IO.Directory.Exists( strFolder ) )
{
throw new ArgumentException();
}
dirs.Push( strFolder );
while ( dirs.Count > 0 )
{
string currentDir = dirs.Pop();
string[] subDirs;
try
{
subDirs = System.IO.Directory.GetDirectories( currentDir );
}
catch ( UnauthorizedAccessException e )
{
MessageBox.Show( "Error: " + e.Message );
continue;
}
catch ( System.IO.DirectoryNotFoundException e )
{
MessageBox.Show( "Error: " + e.Message );
continue;
}
string[] files = null;
try
{
files = System.IO.Directory.GetFiles( currentDir );
}
catch ( UnauthorizedAccessException e )
{
MessageBox.Show( "Error: " + e.Message );
continue;
}
catch ( System.IO.DirectoryNotFoundException e )
{
MessageBox.Show( "Error: " + e.Message );
continue;
}
// Perform the required action on each file here.
// Modify this block to perform your required task.
/*
foreach ( string file in files )
{
try
{
// Perform whatever action is required in your scenario.
System.IO.FileInfo fi = new System.IO.FileInfo( file );
Console.WriteLine( "{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime );
}
catch ( System.IO.FileNotFoundException e )
{
// If file was deleted by a separate application
// or thread since the call to TraverseTree()
// then just continue.
MessageBox.Show( "Error: " + e.Message );
continue;
}
}
*/
// Push the subdirectories onto the stack for traversal.
// This could also be done before handing the files.
foreach ( string str in subDirs )
dirs.Push( str );
foreach ( string str in files )
MessageBox.Show( str );
}
You can use a sort of Composite pattern where a Composite item - is a folder.
Here is a sample code, that builds Tree structure of target folder. It works recursively, and consumes a bit more memory, but simplicity worth it.
class TreeItem
{
public string FolderName;
public List<TreeItem> SubFolders = new List<TreeItem>();
public string[] Files;
}
class Program
{
private static TreeItem FileTree(string rootFolder){
var item = new TreeItem();
item.FolderName = rootFolder;
item.Files = System.IO.Directory.GetFiles(rootFolder);
foreach(var folder in System.IO.Directory.GetDirectories(rootFolder))
{
item.SubFolders.Add(FileTree(folder));
}
return item;
}
//Traversal algorithm
private static void PrintComposite(TreeItem node, int ident)
{
var dirName = System.IO.Path.GetFileName(node.FolderName);
Console.WriteLine(#"{0}{1}", new string('-', ident), dirName);
foreach(var subNode in node.SubFolders)
{
PrintComposite(subNode, ident + 1);
}
}
public static void Main(string[] args)
{
var tree = FileTree(#"D:\Games");
PrintComposite(tree,0);
}
}
For one thing, I think you need to make more objects. A DirectoryElementInterface interface or abstract class and a DirectoryElement object, and a FileElement object that implement DirectoryElementInterface. Now, rather than using a stack to iterate through the heirarchy, create DirectoryElementInterface root = new DirectoryElement(nameOfNode). Then for every file in getFiles do something like root.addElement(new FileElement(filename));. addElement should add to a List within the DirectoryElement. Do similarly for the directories. OK, now you can create one level.
Now for the iteration step. Take the routine you just wrote and make root a parameter. You can call it anything but for this discussion I will be calling this new routine addDirectoryInformation. Your main will now be the creation of the root and calling addDirectoryInformation passing in the root. To iterate we need to ask the now filled in root for its list of elements, do a foreach over the list and call addDirectoryInformation for each of the elements that is a directory. Once you have that working, move the loop into the end of addDirectoryInformation. Now every directory you add adds all its children recursively.
One more thing for a proper recursive program. You have to know when to stop recursing. In this case it's easy. If there are no directories in the list addDirectoryInformation never gets called. So you are done.
I did a course last week where we did something similar, the output was to console but no reason you can't streamwrite it to a .txt file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShowDirectory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This program lists all the files in the directory.");
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(#"C:\");
foreach (System.IO.FileInfo file in dir.GetFiles("*.*"))
{
Console.WriteLine("{0}, {1}", file.Name, file.Length);
}
Console.ReadLine();
}
}
}
I got it working using code based on http://weblogs.asp.net/israelio/archive/2004/06/23/162913.aspx
// How much deep to scan. (of course you can also pass it to the method)
const int HowDeepToScan=20;
public static void ProcessDir ( string dirName, int recursionLvl, string strFileName)
{
string tabs = new String( '-', recursionLvl );
if ( recursionLvl<=HowDeepToScan )
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles( dirName );
TextWriter tw = new StreamWriter( strFileName, true );
tw.WriteLine( tabs + "" + System.IO.Path.GetFileName( dirName ) + "<br />" );
foreach ( string fileName in fileEntries )
{
// do something with fileName
tw.WriteLine( tabs + "" + System.IO.Path.GetFileName( fileName ) + "<br />" );
}
tw.Close();
// Recurse into subdirectories of this directory.
string [] subdirEntries = Directory.GetDirectories( dirName );
foreach ( string subdir in subdirEntries )
// Do not iterate through reparse points
if ( ( File.GetAttributes( subdir ) &
FileAttributes.ReparsePoint ) !=
FileAttributes.ReparsePoint )
ProcessDir( subdir, recursionLvl+1, strFileName );
}
}
output
code<br />
FluentPath (1).zip<br />
index.html<br />
One of the approaches is to use iterator over files tree like this:
// IncludeExcludeFileEnumerator(string baseDir, string includePattern, string excludePattern)
// Include pattern can include ** that means tree hierarchy
var myFiles = new IncludeExcludeFileEnumerable(#"C:\test\aaa", #"**.bmp,*.jpg", "*excl_bad*.*,*fu*");
foreach (var s in myFiles)
{
Console.Out.WriteLine(s);
}
Code for file iterator ( IEnumerator, IEnumerable ):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace IncludeExcludeFileEnumerator
{
public class IncludeExcludeFileEnumerator : IEnumerator<String>
{
private string excludeRegExPattern;
private readonly Regex regexSeparateFilePath;
private readonly Regex excludeRegex = null;
private int currentPatternIndex;
private IEnumerator<string> filesEnum;
private IEnumerable<string> files;
bool isNext = true;
private readonly List<Tuple<string, string, SearchOption>> incPatternsList;
public IncludeExcludeFileEnumerator(string baseDirectory, string includePattern, string excludePattern)
{
// Split comma separated string to array of include patterns
var initIncludePatterns = includePattern.Split(',');
regexSeparateFilePath = new Regex(#"(.*)[\\/]([^\\/]*$)", RegexOptions.Compiled);
// Prepare include patterns
incPatternsList = initIncludePatterns.ToList().ConvertAll(
(incPattern) =>
{
incPattern = incPattern.Trim();
var matches = regexSeparateFilePath.Matches(incPattern);
string pathPattern;
string filePattern;
if (matches.Count == 0)
{
pathPattern = "";
filePattern = incPattern;
}
else
{
pathPattern = matches[0].Groups[1].Value;
filePattern = matches[0].Groups[2].Value;
}
SearchOption searchOption = SearchOption.TopDirectoryOnly;
if (filePattern.Contains("**"))
{
filePattern = filePattern.Replace("**", "*");
searchOption = SearchOption.AllDirectories;
}
var fullPathPattern = Path.Combine(baseDirectory, pathPattern);
// Returns tuple {PathPattern, FilePattern, SearchOption}
return new Tuple<string, string, SearchOption>(fullPathPattern, filePattern, searchOption);
});
// Prepare regular expression for exclude case (all in one, concatinated by (| - or) separator)
if (!String.IsNullOrWhiteSpace(excludePattern))
{
var excPatterns = excludePattern.Replace(".", #"\.");
excPatterns = excPatterns.Replace("*", ".*");
excludeRegExPattern = excPatterns.Replace(",", "|");
excludeRegex = new Regex(excludeRegExPattern, RegexOptions.Compiled);
}
Reset();
}
public string Current
{
get { return filesEnum.Current; }
}
public void Dispose()
{
}
object System.Collections.IEnumerator.Current
{
get { return (Object)this.Current; }
}
public bool MoveNext()
{
do
{
if (( filesEnum == null ) && (incPatternsList.Count < currentPatternIndex + 2))
{
return false;
}
if ((filesEnum == null) || (isNext == false))
{
var tuple = incPatternsList[++currentPatternIndex];
files = Directory.EnumerateFiles(tuple.Item1, tuple.Item2, tuple.Item3);
filesEnum = files.GetEnumerator();
isNext = true;
}
while (isNext)
{
isNext = filesEnum.MoveNext();
if (isNext)
{
if (excludeRegex==null) return true;
if (!excludeRegex.Match(filesEnum.Current).Success) return true;
// else continue;
}
else
{
filesEnum = null;
}
}
} while (true);
}
public void Reset()
{
currentPatternIndex = -1;
filesEnum = null;
}
}
public class IncludeExcludeFileEnumerable : IEnumerable<string>
{
private string baseDirectory;
private string includePattern;
private string excludePattern;
public IncludeExcludeFileEnumerable(string baseDirectory, string includePattern, string excludePattern)
{
this.baseDirectory = baseDirectory;
this.includePattern = includePattern;
this.excludePattern = excludePattern;
}
public IEnumerator<string> GetEnumerator()
{
return new IncludeExcludeFileEnumerator(baseDirectory, includePattern, excludePattern);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return (IEnumerator)this.GetEnumerator();
}
}
}