DotNetBrowser: How to use multiple IEngine? - c#

I'm having trouble using multiple DotNetBrowser IEngine instances at once.
Whenever I try to use more than one at a time, they conflict, even though I have already defined different folders for each one.
Follow the code I'm using.
public void initializeBrowser(string guid)
{
string contextDirectory = Application.StartupPath + #"\cache\" + guid;
string pathProxy = ConfigurationManager.AppSettings["pathProxy"];
BrowserView browserView = new BrowserView()
{
Dock = DockStyle.Fill
};
engine = EngineFactory.Create(new EngineOptions.Builder
{
UserDataDirectory = contextDirectory,
SandboxDisabled = true,
RenderingMode = RenderingMode.OffScreen,
}.Build());
browserView.InitializeFrom(browser);
browser = engine.CreateBrowser();
browser.Navigation.FrameLoadFinished += delegate (object sender, FrameLoadFinishedEventArgs e)
{
Console.Out.WriteLine($"FrameLoadFinished: URL = {e.ValidatedUrl},"
+ $" IsMainFrame = {e.Frame.IsMain}");
};
}

Related

Match EventLog and SearchResultEntry

I want to get all ad changes, including all attributes, who made the change and on which machine. No api satisfies both conditions, so I use a combination of SearchResultEntry and EventLogRecord.
To get the "who" and "where" I register a EventLogWatcher:
var query = new EventLogQuery("Security", PathType.LogName, "*");
var propertySelector = new EventLogPropertySelector(new[]
{
"Event/EventData/Data[#Name='TargetUserName']",
"Event/EventData/Data[#Name='TargetDomainName']",
"Event/EventData/Data[#Name='TargetSid']",
"Event/EventData/Data[#Name='SubjectUserName']",
"Event/EventData/Data[#Name='SubjectDomainName']",
"Event/EventData/Data[#Name='SubjectUserSid']",
"/Event/EventData/Data[#Name='AttributeLDAPDisplayName']",
"/Event/EventData/Data[#Name='AttributeValue']",
"/Event/EventData/Data[#Name='OperationType']",
"/Event/System/Computer"
});
using (var watcher = new EventLogWatcher(query))
{
watcher.EventRecordWritten +=
(object eventLogWatcher, EventRecordWrittenEventArgs eventArgs) =>
{
var eventLogRecord = eventArgs.EventRecord as EventLogRecord;
var props = eventLogRecord.GetPropertyValues(propertySelector);
// process entry
};
watcher.Enabled = true;
// block the thread like await Task.Delay(-1);
}
But this will not include all changes and keep in mind, that the properties will vary based on the event type. To get a full copy of the new object when a change occurs, you can register a callback with SearchRequest:
SearchRequest request = new SearchRequest(dn,filter,scope,attributes);
request.Controls.Add(new DirectoryNotificationControl());
IAsyncResult result = _connection.BeginSendRequest(
request,
TimeSpan.FromDays(1),
PartialResultProcessing.ReturnPartialResultsAndNotifyCallback,
(res) =>
{
var r = _connection.GetPartialResults(res);
foreach (SearchResultEntry entry in r)
{
// process entry
}
},
request);
But how do I match these two events ? SearchResultEntry contains just a new object with attributes and EventLogRecord many information, but none to match them exactly. It is assumed, that both tools run on the same domain controller. Just time as match property is not sufficient enough.
You can use pull mush method to millions of data.You don't need to get all the events from AD intead 5136 event itself has all the changes in AD.You can get all the information from EventLogRecord API.Below are my codes
public class EventLogMgmt{
public static void Main(string[] args)
{
Stirng logName = "Security";
String queryString = "<QueryList> <Query Id="0" Path="Security"><Select Path="Security">*[System[(EventID = 5136)]]</Select></Query></QueryList>";
EventLogQuery subscriptionQuery = new EventLogQuery(logName, PathType.LogName, queryString);
watcher = new EventLogWatcher(subscriptionQuery, null, true); //EventLog watcher
watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);
watcher.Enabled = true;
}
public void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
{
if (arg.EventRecord != null)
{
EventRecord eventInstance = arg.EventRecord;
//String eventMessage = eventInstance.FormatDescription(); // You can get event information from FormatDescription API itself.
//String eventMessageXMLFmt = eventInstance.ToXml(); // Getting event information in xml format
String[] xPathRefs = new String[9];
xPathRefs[0] = "Event/System/TimeCreated/#SystemTime";
xPathRefs[1] = "Event/System/Computer";
xPathRefs[2] = "Event/EventData/Data[#Name=\"TargetUserName\"]";
IEnumerable<String> xPathEnum = xPathRefs;
EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);
IList<object> logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
Log("Time: ", logEventProps[0]);
Log("Computer: ", logEventProps[1]);
}
}
}
All the information like target user,caller user name,modified properties,etc available in above API.

Reload Assembly for access to new ScriptableObject script type

I am creating a new script from a template. However, this new script type is not accessible until the Assembly has had a chance to re-compile. I am trying to create an instance of the new ScriptableObject, in order to generate it through code.
public override void Def()
{
NewAssetName = EditorGUILayout.TextField(NewAssetName);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Add"))
{
TemplateLines = File.ReadAllLines("E:/Unity/Editor/Data/Resources/ScriptTemplates/NewScriptableObject.cs.txt");
for (int i = 0; i < TemplateLines.Length; i++)
{
if (TemplateLines[i].Contains("#SCRIPTNAME#"))
{
TemplateLines[i] = TemplateLines[i].Replace("#SCRIPTNAME#", NewAssetName);
}
}
NewFilePath = "Assets/" + NewAssetName + '/' + NewAssetName + ".cs";
NewSOPath = "Assets/" + NewAssetName + '/' + NewAssetName + ".asset";
File.WriteAllLines(NewFilePath, TemplateLines);
ScriptableObject NewSO = CreateInstance(TypeName);
AssetDatabase.CreateAsset(NewSO, NewSOPath);
}
Everything works fine, up until I use CreateInstance(); At this point, the type does not exist yet. I have to wait for the Assembly to re-compile and capitulate the type...
I have Googled the concept of refreshing the Assembly, but have not found anything.
I have also Googled using async/await in order to delay calling CreateInstance(), until AFTER the Assembly, for sure, has the new type... So far, these attempts have either locked up the Editor, or do not work as intended... (I am new to this async style in C#)
I am open to either an Assembly solution, or an async solution, for solving this problem.
One solution is to save a request to create your scriptable object in EditorPrefs and create your asset in a callback after scripts reloaded.
Unfortunately, you can't do that without locking the editor.
using UnityEditor;
using UnityEngine;
public class EditorUtils
{
[MenuItem("Tools/Create SO")]
private static void CreateSO()
{
GenerateAndSaveSOClass();
ShouldCreateSO = true;
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
private static bool ShouldCreateSO
{
get { return EditorPrefs.GetBool("should_create", false); }
set { EditorPrefs.SetBool("should_create", value);}
}
[UnityEditor.Callbacks.DidReloadScripts]
private static void OnScriptsReloaded()
{
if (ShouldCreateSO)
{
ShouldCreateSO = false;
var so = ScriptableObject.CreateInstance("MyClassName");
var path = "Assets/SO.asset";
AssetDatabase.CreateAsset(so, path);
}
}
private static void GenerateAndSaveSOClass()
{
// TODO: generate and save class
}
}
This is what wound up working:
using UnityEditor;
using UnityEngine;
public class HandleNewScriptAndSO : ScriptableObject
{
public StringRef ActiveDirectory_Ref;
public StringRef NewSOName;
public BoolRef TypeHasBeenAdded_Ref;
private string NewSOPath;
private void OnEnable()
{
AssemblyReloadEvents.afterAssemblyReload += GenerateNewSO;
}
public void GenerateNewSO()
{
if (TypeHasBeenAdded_Ref.Val)
{
ScriptableObject NewSO = CreateInstance(NewSOName.Val);
NewSOPath = ActiveDirectory_Ref.Val + '/' + NewSOName.Val + '/' + NewSOName.Val + ".asset";
AssetDatabase.CreateAsset(NewSO, NewSOPath);
TypeHasBeenAdded_Ref.Val = false;
}
}
}
The boolean is set to true when the user presses the 'Add' button in the EditorWindow:
if (GUILayout.Button("Add") && NewSOName_Ref.Val != "")
{
AssetDatabase.CreateFolder(ActiveDirectory_Ref.Val, NewSOName_Ref.Val);
TemplateLines = File.ReadAllLines("E:/Unity/Editor/Data/Resources/ScriptTemplates/NewScriptableObject.cs.txt");
for (int i = 0; i < TemplateLines.Length; i++)
{
if (TemplateLines[i].Contains("#SCRIPTNAME#"))
{
TemplateLines[i] = TemplateLines[i].Replace("#SCRIPTNAME#", NewSOName_Ref.Val);
}
}
NewFilePath = ActiveDirectory_Ref.Val + '/' + NewSOName_Ref.Val + '/' + NewSOName_Ref.Val + ".cs";
File.WriteAllLines(NewFilePath, TemplateLines);
TypeHasBeenAdded_Ref.Val = true;
AssetDatabase.Refresh();
}
'AssemblyReloadEvents.afterAssemblyReload' delegated needed to be subscribed with the code to add the new objects. It also needed to be bool-guarded, in order to make sure it only runs when the user issues a fresh Add.

C# building a tool to collect project Nuget information

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.

WebIce Integration using Quick fix

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.

Need a default search engine for web browser control

I have created a web browser app for windows phone 7 using web browser control. I want to add a default search engine(i.e, a textBox that is used for Google search or Bing search). And also if the user type anything(words like technology or so on), the search should be redirected to the above default search engine. Can anyone help me with this???
The textBox that I used for entering URL is named as "UrlTextBox" and my web browser control is named as "browsers". The textBox is used for search engine is named as "SearchTextBox".
Thanks in advance for your hard work!!!
public void browsers_Navigating(object sender, NavigatingEventArgs e)
{
UrlTextBox.Text = e.Uri.ToString();
if (navigationcancelled)
{ e.Cancel = true; }
SearchEngine[] availableSearchEngines = new SearchEngine[]
{new SearchEngine(){ Name = "Google", URLPattern = "http://www.google.com/search?q={0}" }};
new SearchEngine(){ Name = "Yahoo", URLPattern = "http://search.yahoo.com/search?p={0}" };
new SearchEngine(){ Name = "Bing", URLPattern = "http://www.bing.com/search?q={0}" };
}
UrlTextBox-:
private void UrlTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Uri url;
if (Uri.TryCreate(UrlTextBox.Text, UriKind.Absolute, out url))
{
this.urls[this.currentIndex] = UrlTextBox.Text;
this.browsers[this.currentIndex].Navigate(url);
}
if (!Uri.TryCreate(UrlTextBox.Text, UriKind.Absolute, out url))
{
SearchEngine defaultSearchEngine = availableSeachEngines[0];
String URL = String.Format(defaultSearchEngine.URLPattern, UrlTextBox.Text);
}
else
{
Navigate(UrlTextBox.Text);
}
}
}
But there is an error says "availableSeachEngines" --->
The name availableSeachEngines does not exist in the current context.
Now i have added my codes above that i have used in my program and also added Muaz Othman codes into it. But its not working for me and also shows the error. I think am making some mistakes in it. Can anyone correct it??? Thanks in advance!!!
You can create a class like this:
public class SearchEngine {
public string Name {set; get}
public string URLPattern { get; set;}
public override string ToString(){
return Name;
}
}
and in your code you can have this array:
SearchEngine[] availableSearchEngines = new SearchEngine[]{
new SearchEngine(){ Name = "Google", URLPattern = "http://www.google.com/search?q={0}" };
new SearchEngine(){ Name = "Yahoo", URLPattern = "http://search.yahoo.com/search?p={0}" };
new SearchEngine(){ Name = "Bing", URLPattern = "http://www.bing.com/search?q={0}" };
}
but in your code you should have only one SearchEngine object:
SearchEngine defaultSearchEngine;
so when the user enters text and chooses "Go" you check if the entered text is a valid URL (maybe using a regular expression), and if not you do this:
String url = String.Format(defaultSearchEngine.URLPattern, SearchTextBox.Text);

Categories