/// <summary> /// Initialise the Session and the Service /// </summary> internal void InitialiseSessionAndService() { if (_session == null) { var sessionOptions = new SessionOptions { ServerHost = _serverHost, ServerPort = _serverPort }; //Console.WriteLine("Connecting to {0}:{1}", sessionOptions.ServerHost, sessionOptions.ServerPort); _session = new Session(sessionOptions); if (!_session.Start()) throw new Exception("Failed to connect!"); if (!_session.OpenService("//blp/refdata")) { _session.Stop(); _session = null; throw new Exception("Failed to open //blp/refdata"); } _refDataService = _session.GetService("//blp/refdata"); } }
public Bloomberg(string host, int port) { Name = "Bloomberg"; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = host; sessionOptions.ServerPort = port; Session session = new Session(sessionOptions); Connected = session.Start(); }
public void Test() { string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; Debug.WriteLine("Connecting to " + serverHost + ":" + serverPort); Session session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.Error.WriteLine("Failed to start session."); return; } if (!session.OpenService("//blp/refdata")) { System.Console.Error.WriteLine("Failed to open //blp/refdata"); return; } Service refDataService = session.GetService("//blp/refdata"); Request request = refDataService.CreateRequest("IntradayBarRequest"); request.Set("security", "IBM US Equity"); request.Set("eventType", "TRADE"); request.Set("interval", 60); // bar interval in minutes DateTime tradedOn = getPreviousTradingDate(); request.Set("startDateTime", new Datetime(tradedOn.Year, tradedOn.Month, tradedOn.Day, 13, 30, 0, 0)); request.Set("endDateTime", new Datetime(tradedOn.Year, tradedOn.Month, tradedOn.Day, 21, 30, 0, 0)); Debug.WriteLine("Sending Request: " + request); session.SendRequest(request, null); while (true) { Event eventObj = session.NextEvent(); foreach (Message msg in eventObj.GetMessages()) { Debug.WriteLine(msg.ToString()); } if (eventObj.Type == Event.EventType.RESPONSE) { break; } } }
private void setup() { Logger.Info("About to startup bbg engines...", typeof(Core)); m_processEventHandler = processEvent; try { // start a synchronous session SessionOptions opts = new SessionOptions(); opts.ServerHost = ConfigHelper.BbgHost; opts.ServerPort = ConfigHelper.BbgPort; Logger.Info(string.Format("Bbg Session options: Host={0}; Port={1}", opts.ServerHost, opts.ServerPort.ToString()), typeof(Core)); SyncSession = new Session(opts); if (!SyncSession.Start()) { Logger.Fatal("Failed to start SyncSession instance of bloomberg session", typeof(Core)); IsStarted = false; return; } else { Logger.Info("Bloomberg 'SyncSession' started successfully", typeof(Core)); } if (!SyncSession.OpenService("//blp/refdata")) { Logger.Fatal("Failed to open service //blp/refdata on 'SyncSession' bbg session", typeof(Core)); System.Console.Error.WriteLine("Failed to start RefData service"); return; } else { Logger.Info("Successfully opened service //blp/refdata on 'SyncSession' bbg session", typeof(Core)); } SyncRefService = SyncSession.GetService("//blp/refdata"); ASyncSession = new Session(opts, m_processEventHandler); ASyncSession.Start(); ASyncSession.OpenService("//blp/refdata"); ASyncSession.OpenService("//blp/pagedata"); ASyncRefService = ASyncSession.GetService("//blp/refdata"); IsStarted = true; } catch (Exception ex_) { Logger.Error(string.Format("Error starting up Bloomberg Sessions: {0} {1}", ex_.Message, ex_.StackTrace), typeof(Core)); IsStarted = false; } }
internal static ISession Create( byte[] applicationKey, SessionOptions options) { NativeSession session = new NativeSession(applicationKey, options); session.Initialize(); if (SessionFactory.IsInternalCachingEnabled) { _sessions.Add(session.Handle, session); } return session; }
private void button1_Click(object sender, EventArgs e) { securityList1 = ConfigurationManager.AppSettings["securities1"].Split(',').Select(s => s.Trim()).ToArray(); securityList2 = ConfigurationManager.AppSettings["securities2"].Split(',').Select(s => s.Trim()).ToArray(); currencyList1 = ConfigurationManager.AppSettings["currencies1"].Split(',').Select(s => s.Trim()).ToArray(); currencyList2 = ConfigurationManager.AppSettings["currencies2"].Split(',').Select(s => s.Trim()).ToArray(); baseCurrency = ConfigurationManager.AppSettings["baseCurrency"]; sendTransactions = Convert.ToBoolean(ConfigurationManager.AppSettings["sendTransaction"]); tc = new TransactionComputer (securityList1, securityList2, currencyList1, currencyList2, baseCurrency); ts = new TransactionSender(); SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; Session session = new Session(sessionOptions, new EventHandler(ProcessEvent)); session.StartAsync(); //Invoke(new Action(() => richTextBox1.AppendText("moi\n"); Invoke(new Action(() => richTextBox1.AppendText("end\n"))); }
/// <summary> /// Sets config and other session data to create the session /// </summary> /// <returns></returns> private Session CreateBloombergSession() { // retrieves the appsettings and fills the config object config = new BloombergApiSessionConfig(); var sessionOptions = new SessionOptions { ServerHost = config.BbHost, ServerPort = config.BbPort }; var session = new Session(sessionOptions); if (!session.Start()) { //_Logging.Error("Unable to initiate Bloomberg session."); return null; } if (!session.OpenService(config.BbService)) { //_Logging.Error("Unable to open Bloomberg service."); return null; } return session; }
public SecurityToDateToFldNameToFldVal PerformRequest(DateTime fromDate, DateTime toDate, List <string> tickers, List <string> fieldNames, Dictionary <string, string> optionalParams, Dictionary <string, string> overrideParams) { string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; System.Console.WriteLine("Connecting to " + serverHost + ":" + serverPort); session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.Error.WriteLine("Failed to start session."); CheckFailures(session); return(null); } if (!session.OpenService(BbgStrings.Services.REF_DATA_SERVICE)) { System.Console.Error.WriteLine("Failed to open " + BbgStrings.Services.REF_DATA_SERVICE); CheckFailures(session); return(null); } Service refDataService = session.GetService(BbgStrings.Services.REF_DATA_SERVICE); Request request = refDataService.CreateRequest(BbgStrings.Requests.HISTORICAL_DATA); Element securities = request.GetElement(BbgStrings.Elements.SECURITIES); foreach (string s in tickers) { securities.AppendValue(s); } Element fields = request.GetElement(BbgStrings.Elements.FIELD); foreach (string f in fieldNames) { fields.AppendValue(f); } Element overrides = request.GetElement(BbgStrings.Elements.OVERRIDES); foreach (KeyValuePair <string, string> e in overrideParams) { Element o = overrides.AppendElement(); o.SetElement("fieldId", e.Key); o.SetElement("value", e.Value); } foreach (KeyValuePair <string, string> e in optionalParams) { request.Set(e.Key, e.Value); } request.Set(BbgStrings.QueryParams.START_DATE, fromDate.ToString("yyyyMMdd")); request.Set(BbgStrings.QueryParams.END_DATE, toDate.ToString("yyyyMMdd")); System.Console.WriteLine("Sending Request: " + request); session.SendRequest(request, null); SecurityToDateToFldNameToFldVal result = new SecurityToDateToFldNameToFldVal(); bool isDone = false; while (!isDone) { Event eventObj = session.NextEvent(); foreach (Message msg in eventObj) { System.Console.WriteLine(msg.AsElement); } switch (eventObj.Type) { case Event.EventType.PARTIAL_RESPONSE: ProcessResponseEvent(eventObj, result); break; case Event.EventType.RESPONSE: ProcessResponseEvent(eventObj, result); isDone = true; break; default: ProcessGenericEvent(eventObj); break; } } session.Stop(); return(result); }
private bool createSession() { if (d_session != null) { d_session.Stop(); } string authOptions = string.Empty; d_sessionOptions = new SessionOptions(); if (d_authOption == "APPLICATION") { // Set Application Authentication Option authOptions = "AuthenticationMode=APPLICATION_ONLY;"; authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;"; // ApplicationName is the entry in EMRS. authOptions += "ApplicationName=" + d_name; } else if (d_authOption == "USER_APP") { // Set User and Application Authentication Option authOptions = "AuthenticationMode=USER_AND_APPLICATION;"; authOptions += "AuthenticationType=OS_LOGON;"; authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;"; // ApplicationName is the entry in EMRS. authOptions += "ApplicationName=" + d_name; } else if (d_authOption == "USER_DS_APP") { // Set User and Application Authentication Option authOptions = "AuthenticationMode=USER_AND_APPLICATION;"; authOptions += "AuthenticationType=DIRECTORY_SERVICE;"; authOptions += "DirSvcPropertyName=" + d_dsName + ";"; authOptions += "ApplicationAuthenticationType=APPNAME_AND_KEY;"; // ApplicationName is the entry in EMRS. authOptions += "ApplicationName=" + d_name; } else if (d_authOption == "DIRSVC") { // Authenticate user using active directory service property authOptions = "AuthenticationType=DIRECTORY_SERVICE;"; authOptions += "DirSvcPropertyName=" + d_dsName; } else if (d_authOption == "NONE") { // do nothing } else { // Authenticate user using windows/unix login name authOptions = "AuthenticationType=OS_LOGON"; } System.Console.WriteLine("Authentication Options = " + authOptions); d_sessionOptions.AuthenticationOptions = authOptions; SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count]; int index = 0; System.Console.WriteLine("Connecting to port " + d_port.ToString() + " on host(s):"); foreach (string host in d_hosts) { servers[index] = new SessionOptions.ServerAddress(host, d_port); System.Console.WriteLine(host); index++; } // auto restart on disconnect d_sessionOptions.ServerAddresses = servers; d_sessionOptions.AutoRestartOnDisconnection = true; d_sessionOptions.NumStartAttempts = d_hosts.Count; d_session = new Session(d_sessionOptions); return(d_session.Start()); }
private void InstallTools(int slot, int module) { string ipAddress = GetIPAddress(slot, module); // SessionOptions.Timeout doesn't seem to work so we ping first to make sure the target is alive. Ping ping = new Ping(); PingReply reply = ping.Send(ipAddress, 250); if (reply.Status != IPStatus.Success) { throw new ApplicationException("Could not connect to " + ipAddress); } using (Session session = new Session()) { SessionOptions sessionOptions = new SessionOptions { HostName = ipAddress, UserName = "******", Password = tbPassword.Text, Protocol = Protocol.Scp, // DISA SshHostKeyFingerprint = "ssh-rsa 1040 72:e4:60:61:30:a4:2f:ae:cf:80:c6:10:c3:09:29:68", // VM //SshHostKeyFingerprint = "ssh-rsa 2048 30:e3:8b:37:10:37:89:f1:fe:7c:8a:61:8d:bd:34:04", }; session.Open(sessionOptions); // Determine if DISA (32-bit cpu) or DISA-HP (64-bit cpu). var unameResult = session.ExecuteCommand("uname -m"); unameResult.Check(); TransferOptions xferOptions = new TransferOptions(); xferOptions.FilePermissions = new FilePermissions { Octal = "555" }; var result = session.PutFiles(@"bin-ppc\gdb", @"/usr/bin/gdb", options: xferOptions); result.Check(); if (unameResult.Output == "ppc64") { result = session.PutFiles(@"bin-ppc\sftp-server-64", @"/usr/libexec/sftp-server", options: xferOptions); result.Check(); result = session.PutFiles(@"bin-ppc\libcrypto.so.1.0.0", @"/usr/lib64/libcrypto.so.1.0.0"); result.Check(); } else if (unameResult.Output == "ppc") { result = session.PutFiles(@"bin-ppc\sftp-server-32", @"/usr/libexec/sftp-server", options: xferOptions); result.Check(); } else { throw new ApplicationException("Unknown hardware architecture: " + unameResult.Output); } } }
public static void RunExample() { SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "127.0.0.1"; sessionOptions.ServerPort = 8194; Session session = new Session(sessionOptions); if (session.Start() && session.OpenService("//blp/refdata")) { Service service = session.GetService("//blp/refdata"); if (service == null) { Console.WriteLine("Service is null"); } else { Request request = service.CreateRequest("HistoricalDataRequest"); //request information for the following securities request.Append(HistoricalDataRequest._nSecurities, "MSFT US EQUITY"); request.Append("securities", "C A COMDTY"); request.Append("securities", "AAPL 150117C00600000 EQUITY"); //this is a stock option: TICKER yyMMdd[C/P]\d{8} EQUITY //uncomment the following line to see what a request for a nonexistent security looks like //request.Append("securities", "ZIBM US EQUITY"); // My code treats all securities that start with a 'Z' as a nonexistent security //include the following simple fields in the result request.Append("fields", "BID"); //Note that the API will not allow you to use the HistoricalDataRequest._nBid name as a value here. It expects a string. request.Append("fields", "ASK"); //ditto //uncomment the following line to see what a request for an invalid field looks like //request.Append("fields", "ZBID"); // My code treats all fields that start with a 'Z' as an invalid field //Historical requests allow a few overrides. See the developer's guide A.2.4 for more information. request.Set("startDate", DateTime.Today.AddMonths(-1).ToString("yyyyMMdd")); //Request that the information start three months ago from today. This override is required. request.Set("endDate", DateTime.Today.AddDays(10).ToString("yyyyMMdd")); //Request that the information end three days before today. This is an optional override. The default is today. //Determine the frequency and calendar type of the output. To be used in conjunction with Period Selection. request.Set("periodicityAdjustment", "CALENDAR"); //Optional string. Valid values are ACTUAL (default), CALENDAR, and FISCAL. //Determine the frequency of the output. To be used in conjunction with Period Adjustment. request.Set("periodicitySelection", "DAILY"); //Optional string. Valid values are DAILY (default), WEEKLY, MONTHLY, QUARTERLY, SEMI_ANNUALLY, and YEARLY //Sets quote to Price or Yield for a debt instrument whose default value is quoted in yield (depending on pricing source). request.Set("pricingOption", "PRICING_OPTION_PRICE"); //Optional string. Valid values are PRICING_OPTION_PRICE (default) and PRICING_OPTION_YIELD //Adjust for "change on day" request.Set("adjustmentNormal", true); //Optional bool. Valid values are true and false (default = false) //Adjusts for Anormal Cash Dividends request.Set("adjustmentAbnormal", false); //Optional bool. Valid values are true and false (default = false) //Capital Changes Defaults request.Set("adjustmentSplit", true); //Optional bool. Valid values are true and false (default = false) //The maximum number of data points to return, starting from the startDate //request.Set("maxDataPoints", 5); //Optional integer. Valid values are positive integers. The default is unspecified in which case the response will have all data points between startDate and endDate //Indicates whether to use the average or the closing price in quote calculation. request.Set("overrideOption", "OVERRIDE_OPTION_CLOSE"); //Optional string. Valid values are OVERRIDE_OPTION_GPA for an average and OVERRIDE_OPTION_CLOSE (default) for the closing price CorrelationID requestID = new CorrelationID(1); session.SendRequest(request, requestID); bool continueToLoop = true; while (continueToLoop) { Event eventObj = session.NextEvent(); switch (eventObj.Type) { case Event.EventType.RESPONSE: // final event continueToLoop = false; HistoricalDataRequest.handleResponseEvent(eventObj); break; case Event.EventType.PARTIAL_RESPONSE: HistoricalDataRequest.handleResponseEvent(eventObj); break; default: HistoricalDataRequest.handleOtherEvent(eventObj); break; } } } } else { Console.WriteLine("Cannot connect to server. Check that the server host is \"localhost\" or \"127.0.0.1\" and that the server port is 8194."); } }
private void run(string[] args) { string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; System.Console.WriteLine("Connecting to " + serverHost + ":" + serverPort); Session session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.WriteLine("Failed to start session."); return; } if (!session.OpenService("//blp/refdata")) { System.Console.Error.WriteLine("Failed to open //blp/refdata"); return; } Service refDataService = session.GetService("//blp/refdata"); Request request = refDataService.CreateRequest("ReferenceDataRequest"); Element securities = request.GetElement("securities"); securities.AppendValue("IBM US Equity"); securities.AppendValue("VOD LN Equity"); Element fields = request.GetElement("fields"); fields.AppendValue("PX_LAST"); fields.AppendValue("DS002"); fields.AppendValue("EQY_WEIGHTED_AVG_PX"); // add overrides Element overrides = request["overrides"]; Element override1 = overrides.AppendElement(); override1.SetElement("fieldId", "VWAP_START_TIME"); override1.SetElement("value", "9:30"); Element override2 = overrides.AppendElement(); override2.SetElement("fieldId", "VWAP_END_TIME"); override2.SetElement("value", "11:30"); System.Console.WriteLine("Sending Request: " + request); session.SendRequest(request, null); while (true) { Event eventObj = session.NextEvent(); foreach (Message msg in eventObj) { System.Console.WriteLine(msg.AsElement); } if (eventObj.Type == Event.EventType.RESPONSE) { break; } } }
// find the nearest hostkey option.(might just add a layer on top of this to make it easier. // effectively just handling thj /// <summary> /// Args should contain, in order: the sftp connection information [protocol]/ /// </summary> /// <param name="args"></param> static void Main(string[] args) { string uri = null; // you need this at least. string remote_directory = null; string local_directory = null; // I might dump these down into the keyword arguments, or implicitly as positional arguments. List <string> actions = new List <string>(); // this will handle the additional options (put/get) etc. // We'll set it to assume that just a host implies a "pull *" operation. #if DEBUG for (int j = 0; j < args.Length; j++) { Console.WriteLine(args[j]); } #endif // generate a dictionary to access input. // alrighty - the first few things should simply be the first cases. // THAT WAS AN EPIC TYPO. INITIALIZED I as 9 INSTEAD OF 0 for (int i = 0; i < args.Length; i++) { if (args[i].Contains("=")) { string[] kp = args[i].Split('='); kargs.Add(kp[0], kp[1]); // don't allow #if DEBUG Console.WriteLine($"{args[i]}: Keyword argument"); #endif } // if we're opening with a dash - then load into the list of switches. else if (args[i].Substring(0, 1) == "-") //else if(args[i].Substring(0,3).Contains("-")) { sargs.Add(args[i]); // #if DEBUG Console.WriteLine($"{args[i]}: Switch argument"); #endif } // what is causing this to get add... ooooh..... else { pargs.Add(args[i]); #if DEBUG Console.WriteLine($"{args[i]}: Positional argument"); #endif } } // to handle a variable number of positional arguments. for (int i = 0; i < pargs.Count; i++) { switch (i) { case 0: uri = pargs[i]; #if DEBUG goto default; #endif break; case 1: remote_directory = pargs[i]; #if DEBUG goto default; #endif break; case 2: local_directory = pargs[i]; #if DEBUG goto default; #endif break; default: if (i > 2) { actions.Add(pargs[i]); } Console.WriteLine($"Unused positional argument - {pargs[i]}"); break; } } #if DEBUG // now during debugging we'll just list the sorted arguments and make sure that key value pairs are fine. // we're at a few hundred lines and mostly just dealing with argument parsing. foreach (string a in kargs.Keys) { Console.WriteLine($"{a}:{kargs[a]}"); } foreach (string a in sargs) { Console.WriteLine($"{a}"); } foreach (string a in pargs) { Console.WriteLine($"{a}"); } Console.WriteLine($"URL: {uri?? "<unassigned>"}"); Console.WriteLine($"Remote: {remote_directory ?? "<unassigned>"}"); Console.WriteLine($"Local: {local_directory ?? "<unassigned>"}"); //Console.ReadLine(); #endif // we'll want to try to trigger the most basic form of the function. /* * // scan for hostkey - ' * // we don't need this now.. * // what would the minimum number of necessary arguments be? * // I'm thinking just one should be fine. * for(int i = 0;i<args.Length;i++) * { * if(args[i].Contains("-hostkey")) * { * hostkey = args[i].Split('=')[1]; // if this isn't formed well then it will break. * } * } */ // scan for put/pull files. // string op_ = uri + " " + hostkey; #if DEBUG Console.WriteLine("+Establishing connection based here..." + op_); #endif SessionOptions sopt = parseOpts(op_); // now we could try to run it through the session options mechanism. try { // add session data; using (Session session = new Session()) { session.Open(sopt); // funny - I used the same characters as I ended up using in the other application. TransferOptions topts = new TransferOptions(); // not sure what needs to be added in here. TransferOperationResult tor; // just declare it. } } catch (Exception e) { } }
public result Submit(string ISIN) { result FOSresult = new result(); //open excel to get two parameter SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "WSG053"; sessionOptions.ServerPort = 0x2002; Session session = new Session(sessionOptions); if (!session.Start()) { Console.WriteLine("Could not start session."); Environment.Exit(1); } if (!session.OpenService("//blp/refdata")) { Console.WriteLine("Could not open service //blp/refdata"); Environment.Exit(1); } CorrelationID requestID = new CorrelationID(1L); Request request = session.GetService("//blp/refdata").CreateRequest("ReferenceDataRequest"); request.GetElement("securities").AppendValue(ISIN + " corp"); Element fields = request.GetElement("fields"); fields.AppendValue("SECURITY_DES"); fields.AppendValue("CRNCY"); fields.AppendValue("ISSUER"); fields.AppendValue("COUNTRY_FULL_NAME"); fields.AppendValue("MARKET_SECTOR_DES"); fields.AppendValue("INDUSTRY_SECTOR"); fields.AppendValue("PX_BID"); fields.AppendValue("COUPON"); fields.AppendValue("YLD_YTM_BID"); fields.AppendValue("DUR_BID"); fields.AppendValue("RTG_SP"); fields.AppendValue("RTG_SP_LT_LC_ISSUER_CREDIT"); fields.AppendValue("RTG_MOODY"); fields.AppendValue("RTG_MOODY_LONG_TERM"); fields.AppendValue("RTG_MDY_LC_CURR_ISSUER_RATING"); fields.AppendValue("RTG_FITCH"); fields.AppendValue("RTG_FITCH_LT_ISSUER_DEFAULT"); fields.AppendValue("COLLAT_TYP"); fields.AppendValue("MTY_YEARS_TDY"); fields.AppendValue("NXT_CALL_DT"); fields.AppendValue("MATURITY"); fields.AppendValue("GUARANTOR"); Console.WriteLine("Sending Request:" + request); session.SendRequest(request, null); while (true) { Event eventObj = session.NextEvent(); this.processEvent(eventObj, session); if (eventObj.Type == Event.EventType.RESPONSE) { IssueRating = RTG_SP + "/" + this.GetMoody(RTG_MOODY, RTG_MOODY_LONG_TERM) + "/" + RTG_FITCH; IssuerRating = RTG_SP_LT_LC_ISSUER_CREDIT + "/" + RTG_MDY_LC_CURR_ISSUER_RATING + "/" + RTG_FITCH_LT_ISSUER_DEFAULT; if (CallDate != "NA") { DateTime newdate = DateTime.Parse(CallDate); DateTime nowdate = DateTime.Now; decimal dCallDate = (decimal)(((TimeSpan)(newdate - nowdate)).Days) / 365; CallDate = StandardFormat(Math.Round(dCallDate, 2).ToString(), 2); } FOSresult.CallDate = CallDate; FOSresult.COLLATERAL_TYPE = COLLATERAL_TYPE; FOSresult.COUNTRY_FULL_NAME = COUNTRY_FULL_NAME; FOSresult.COUPON = COUPON; FOSresult.CRNCY = CRNCY; FOSresult.DUR_BID = DUR_BID; FOSresult.INDUSTRY_SECTOR = INDUSTRY_SECTOR.ToUpper(); FOSresult.PX_BID = PX_BID; FOSresult.YLD_YTM_BID = YLD_YTM_BID; FOSresult.SECURITY_DES = SECURITY_DES; FOSresult.IssueRating = IssueRating; FOSresult.IssuerRating = IssuerRating; FOSresult.MARKET_SECTOR_DES = MARKET_SECTOR_DES; FOSresult.YearToMaturity = Maturity; FOSresult.ISSUER = ISSUER; GetInfoFromExcel(FOSresult); //undoImpersonation(); return FOSresult; //return base.Json(new { SECURITY_DES = SECURITY_DES, CRNCY = CRNCY, ISSUER = ISSUER, COUNTRY_FULL_NAME = COUNTRY_FULL_NAME, MARKET_SECTOR_DES = MARKET_SECTOR_DES, INDUSTRY_SECTOR = INDUSTRY_SECTOR.ToUpper(), PX_BID = PX_BID, COUPON = COUPON, YLD_YTM_BID = YLD_YTM_BID, DUR_BID = DUR_BID, IssueRating = IssueRating, IssuerRating = IssuerRating, COLLATERAL_TYPE = COLLATERAL_TYPE, YearToMaturity = Maturity, CallDate = CallDate }); } } }
public static void SendFiler(string localpath, string remotepath, string filetype, bool MakeBackupFolder) { int i = 0; //string RemotePath; string LocalPath = localpath; string LocalPathDate; string myPath = "\\\\10.10.11.11\\MeterData\\OnDemand\\Alarmer\\"; try { DirectoryInfo di = new DirectoryInfo(myPath); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } //FTP options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = "okfile.hstz2.amr.kamstrup.com", PortNumber = 21, UserName = "******", Password = "******", FtpSecure = FtpSecure.Explicit, TlsHostCertificateFingerprint = "d7:99:c2:9e:cb:4c:96:a5:e2:05:21:05:1c:92:c8:7b:fd:d8:38:69", //Skal skiftes hvis cert fejler. Findes ved at oprette ftp til adressen på port 21 i winscp }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); //DateTime dt = DateTime.Now; LocalPathDate = LocalPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\"; string remotePath = remotepath; string fileType = filetype; session.EnumerateRemoteFiles(remotePath, fileType, EnumerationOptions.None); // Hent filliste i dir RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath); foreach (RemoteFileInfo fileInfo in directoryInfo.Files) { // Er der nogen filer? if (fileInfo == null) { throw new Exception("Ingen filer fundet"); } //string d = fileInfo.LastWriteTime.ToString("yyyy-MM-dd"); // Hent valgte fil if (fileInfo.Name != "..") { session.GetFiles((remotePath + fileInfo.Name), localpath, true).Check(); SendMail("*****@*****.**", "*****@*****.**", "", "", "Alarmer", "Vedhæftet er alarmer fra Kamstrup", myPath + fileInfo.Name); Console.WriteLine("Der er sendt {0} filer", fileInfo.Name); i++; } } } Console.WriteLine("Der blev sendt {0} filer", i.ToString()); //Console.Read(); //return 0; //string LocalFilePath = localpath; //Console.Read(); } catch (Exception e) { Console.WriteLine("Error: {0}", e); //Console.ReadLine(); //return 1; } }
public static IDocumentSession CreateDocumentSession(DocumentStore store) { var session = store.OpenSession(SessionOptions.ForCurrentTransaction()); return(session); }
private void button1_Click(object sender, EventArgs e) { Lgr.Start(); int _securities; try { _securities = get_Securities(); } catch (CsvHelper.CsvMissingFieldException) { Invoke(new Action(() => richTextBox1.AppendText("Malformed securities.csv.\nSee that the header line is security1,security2,currency1,currency2,security1scale,security2scale,arbidir\n"))); return; } catch (System.IO.FileNotFoundException) { Invoke(new Action(() => richTextBox1.AppendText("Could not find securities.csv\n"))); return; } Invoke(new Action(() => richTextBox1.AppendText(String.Format("Found {0} securities\n", _securities)))); if (_securities == 0) { Invoke(new Action(() => richTextBox1.AppendText("No valid securities found. Not starting.\n"))); return; } baseCurrency = ConfigurationManager.AppSettings["baseCurrency"]; profitThresholdEur = Convert.ToInt32(ConfigurationManager.AppSettings["profitThresholdEur"]); sendTransactions = Convert.ToBoolean(ConfigurationManager.AppSettings["sendTransaction"]); tc = new TransactionComputer (securityList1, securityList2, currencyList1, currencyList2, securityScale1, securityScale2, baseCurrency, profitThresholdEur); ts = new TransactionSender(); if (running == false) { running = true; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; //pullInitial(sessionOptions); sessionCurr = new Session(sessionOptions, new EventHandler(ProcessEventCurr)); sessionCurr.StartAsync(); sessionSec = new Session(sessionOptions, new EventHandler(ProcessEventSec)); sessionSec.StartAsync(); Invoke(new Action(() => richTextBox1.AppendText("started\n"))); this.button1.Text = "Stop"; } else { // FIXME: Any danger in stopping, eg. to transactions? running = false; sessionCurr.Stop(); sessionSec.Stop(); Invoke(new Action(() => richTextBox1.AppendText("stopped\n"))); this.button1.Text = "Start"; } }
/// <summary> /// Etablie la connection avec Bloomberg /// </summary> private void OpenSession() { sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; session = new Session(sessionOptions); l_title = new List<Title>(); if (!session.Start()) { System.Console.WriteLine("Could not start session."); Console.WriteLine(session.ToString()); Remplissage_Non_connection(); return; } if (!session.OpenService("//blp/refdata")) { System.Console.WriteLine("Could not open service " + "//blp/refdata"); return; } refDataSvc = session.GetService("//blp/refdata"); if (refDataSvc == null) { Console.WriteLine("Cannot get service"); return; } else { request = refDataSvc.CreateRequest("ReferenceDataRequest"); } }
public NativeSession(byte[] applicationKey, SessionOptions options) : base(null, IntPtr.Zero) { _applicationKey = applicationKey; _options = options; }
public abstract IDocumentSession OpenSession(SessionOptions sessionOptions);
public IDocumentSession OpenSession(SessionOptions options) { return(openSession(options)); }
public void Run(String[] args) { if (!ParseCommandLine(args)) { return; } SessionOptions sessionOptions = new SessionOptions(); SessionOptions.ServerAddress[] servers = new SessionOptions.ServerAddress[d_hosts.Count]; for (int i = 0; i < d_hosts.Count; ++i) { servers[i] = new SessionOptions.ServerAddress(d_hosts[i], d_port); } sessionOptions.ServerAddresses = servers; sessionOptions.AutoRestartOnDisconnection = true; sessionOptions.NumStartAttempts = d_hosts.Count; sessionOptions.DefaultSubscriptionService = d_service; sessionOptions.DefaultTopicPrefix = ""; // normally defaults to "ticker" sessionOptions.AuthenticationOptions = d_authOptions; System.Console.WriteLine("Connecting to port " + d_port + " on "); foreach (string host in d_hosts) { System.Console.WriteLine(host + " "); } Session session = new Session(sessionOptions); if (!session.Start()) { System.Console.Error.WriteLine("Failed to start session."); return; } Identity identity = null; if (d_authOptions.Length != 0) { EventQueue tokenEventQueue = new EventQueue(); session.GenerateToken(new CorrelationID(tokenEventQueue), tokenEventQueue); String token = null; const int timeoutMilliSeonds = 10000; Event eventObj = tokenEventQueue.NextEvent(timeoutMilliSeonds); if (eventObj.Type == Event.EventType.TOKEN_STATUS) { foreach (Message msg in eventObj) { System.Console.WriteLine(msg.ToString()); if (msg.MessageType == TOKEN_SUCCESS) { token = msg.GetElementAsString("token"); } } } if (token == null) { System.Console.WriteLine("Failed to get token"); System.Environment.Exit(1); } if (session.OpenService("//blp/apiauth")) { Service authService = session.GetService("//blp/apiauth"); Request authRequest = authService.CreateAuthorizationRequest(); authRequest.Set("token", token); EventQueue authEventQueue = new EventQueue(); identity = session.CreateIdentity(); session.SendAuthorizationRequest(authRequest, identity, authEventQueue, new CorrelationID(identity)); bool isAuthorized = false; while (!isAuthorized) { eventObj = authEventQueue.NextEvent(); if (eventObj.Type == Event.EventType.RESPONSE || eventObj.Type == Event.EventType.PARTIAL_RESPONSE || eventObj.Type == Event.EventType.REQUEST_STATUS) { foreach (Message msg in eventObj) { System.Console.WriteLine(msg.ToString()); if (msg.MessageType == AUTHORIZATION_SUCCESS) { isAuthorized = true; break; } else { System.Console.Error.WriteLine("Not authorized: " + msg); System.Environment.Exit(1); } } } } } } List <Subscription> subscriptions = new List <Subscription>(); // Short topic string; will get qualified by subscribe() using session // options: 'DefaultSubscriptionService' and 'DefaultTopicPrefix' // configured above String topic1 = "IBM Equity"; // Fully qualified topic String topic2 = d_service + "/RHAT Equity"; // Add a topic on unknown service to demonstrate event sequence String topic3 = d_service + "-unknown/RHAT Equity"; subscriptions.Add(new Subscription(topic1, new CorrelationID(topic1))); subscriptions.Add(new Subscription(topic2, new CorrelationID(topic2))); subscriptions.Add(new Subscription(topic3, new CorrelationID(topic3))); session.Subscribe(subscriptions, identity); ProcessSubscriptionResponse(session); }
private void pullInitial(SessionOptions sessionOptions) { Session session = new Session(sessionOptions); if (!session.Start()) { Invoke(new Action(() => richTextBox1.AppendText("Could not start session 2."))); } if (!session.OpenService("//blp/refdata")) { Invoke(new Action(() => richTextBox1.AppendText("Could not open service " + "//blp/refdata"))); } CorrelationID requestID = new CorrelationID(1); Service refDataSvc = session.GetService("//blp/refdata"); Request request = refDataSvc.CreateRequest("ReferenceDataRequest"); foreach (string security in securityList1) { request.Append("securities", security); } foreach (string security in securityList2) { request.Append("securities", security); } foreach (string currency in currencyList1) { if (currency == baseCurrency) { continue; } string currencyID = currency + baseCurrency + " Curncy"; request.Append("securities", currencyID); } foreach (string currency in currencyList2) { if (currency == baseCurrency) { continue; } string currencyID = currency + baseCurrency + " Curncy"; request.Append("securities", currencyID); } Invoke(new Action(() => richTextBox1.AppendText("added securities\n"))); List<string> _fields; _fields = new List<String>(); _fields.Add("LAST_PRICE"); _fields.Add("BEST_BID"); _fields.Add("BEST_ASK"); _fields.Add("BEST_BID1_SZ"); _fields.Add("BEST_ASK1_SZ"); request.Append("fields", "LAST_PRICE"); request.Append("fields", "BEST_BID"); request.Append("fields", "BEST_ASK"); request.Append("fields", "BEST_BID1_SZ"); request.Append("fields", "BEST_ASK1_SZ"); session.SendRequest(request, requestID); bool continueToLoop = true; while (continueToLoop) { Bloomberglp.Blpapi.Event evt = session.NextEvent(); switch (evt.Type) { case Event.EventType.PARTIAL_RESPONSE: Invoke(new Action(() => richTextBox1.AppendText("partial response\n"))); ProcessEvent(evt, _fields); break; case Event.EventType.RESPONSE: // final event Invoke(new Action(() => richTextBox1.AppendText("final response\n"))); continueToLoop = false; // fall through break; } } Invoke(new Action(() => richTextBox1.AppendText("-------------- FINISHED INITIAL PULL -------------"))); Invoke(new Action(() => richTextBox1.AppendText("-------------- FINISHED INITIAL PULL -------------"))); Invoke(new Action(() => richTextBox1.AppendText("-------------- FINISHED INITIAL PULL -------------"))); }
private void Run() { var sessionOptions = new SessionOptions {ServerHost = _dHost, ServerPort = _dPort}; Console.WriteLine(@"Connecting to " + _dHost + @":" + _dPort); var session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { Console.Error.WriteLine("Failed to start session."); _waitEndOfCollection.Release(); return; } if (!session.OpenService("//blp/refdata")) { Console.Error.WriteLine("Failed to open //blp/refdata"); _waitEndOfCollection.Release(); return; } DataManager.CreateTableForContract(_dSecurity); DataManager.DeleteTicks(_dSecurity, _startDate, _endDate); SendIntradayTickRequest(session); EventLoop(session); session.Stop(); }
public static void HentFiler(string localpath, string remotepath, string filetype, bool MakeBackupFolder, bool removeFile) { int i = 0; //string RemotePath; string LocalPath = localpath; string LocalPathDate; try { //FTP options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Ftp, HostName = "okfile.hstz2.amr.kamstrup.com", PortNumber = 21, UserName = "******", Password = "******", FtpSecure = FtpSecure.Explicit, TlsHostCertificateFingerprint = "d7:99:c2:9e:cb:4c:96:a5:e2:05:21:05:1c:92:c8:7b:fd:d8:38:69", //Skal skiftes hvis cert fejler. Findes ved at oprette ftp til adressen på port 21 i winscp }; using (Session session = new Session()) { // Connect session.Open(sessionOptions); //DateTime dt = DateTime.Now; LocalPathDate = LocalPath + DateTime.Now.ToString("yyyy-MM-dd") + "\\"; string remotePath = remotepath; string fileType = filetype; session.EnumerateRemoteFiles(remotePath, fileType, EnumerationOptions.None); // Hent filliste i dir RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath); foreach (RemoteFileInfo fileInfo in directoryInfo.Files) { // Er der nogen filer? if (fileInfo == null) { throw new Exception("Ingen filer fundet"); } string d = fileInfo.LastWriteTime.ToString("yyyy-MM-dd"); // Hent valgte fil if ((fileInfo.Name != "..") && (d == DateTime.Now.ToString("yyyy-MM-dd"))) { session.GetFiles((remotePath + fileInfo.Name), localpath, removeFile).Check(); Console.WriteLine("Download af {0} gennemført", fileInfo.Name); i++; } } } Console.WriteLine("Der blev hentet {0} filer", i.ToString()); //Console.Read(); //return 0; //string LocalFilePath = localpath; string[] files = Directory.GetFiles(LocalPath); string fileName; string destFile; // Kopier filer og overskriv hvis de eksistere i forvejen int x = files.Count(); if ((x > 0) & (MakeBackupFolder)) { if (!Directory.Exists(LocalPathDate)) { Directory.CreateDirectory(LocalPathDate); } foreach (string s in files) { fileName = Path.GetFileName(s); destFile = Path.Combine(LocalPathDate, fileName); File.Copy(s, destFile, true); } } //Console.Read(); } catch (Exception e) { Console.WriteLine("Error: {0}", e); Console.ReadLine(); //return 1; } }
public static IApplicationBuilder UseBlazAdmin(this IApplicationBuilder applicationBuilder, SessionOptions options) { applicationBuilder.UseSession(options); return(applicationBuilder); }
static void Main(string[] args) { // string is null or empty if (args == null || args.Length < 3) { Console.WriteLine("Usage information: dotnet run model.onnx input.jpg output.jpg"); return; } else { if (!(File.Exists(args[0]))) { Console.WriteLine("Model Path does not exist"); return; } if (!(File.Exists(args[1]))) { Console.WriteLine("Input Path does not exist"); return; } } // Read paths string modelFilePath = args[0]; string imageFilePath = args[1]; string outImageFilePath = args[2]; using Image imageOrg = Image.Load(imageFilePath, out IImageFormat format); //Letterbox image var iw = imageOrg.Width; var ih = imageOrg.Height; var w = 416; var h = 416; if ((iw == 0) || (ih == 0)) { Console.WriteLine("Math error: Attempted to divide by Zero"); return; } float width = (float)w / iw; float height = (float)h / ih; float scale = Math.Min(width, height); var nw = (int)(iw * scale); var nh = (int)(ih * scale); var pad_dims_w = (w - nw) / 2; var pad_dims_h = (h - nh) / 2; // Resize image using default bicubic sampler var image = imageOrg.Clone(x => x.Resize((nw), (nh))); var clone = new Image <Rgb24>(w, h); clone.Mutate(i => i.Fill(Color.Gray)); clone.Mutate(o => o.DrawImage(image, new Point(pad_dims_w, pad_dims_h), 1f)); // draw the first one top left //Preprocessing image Tensor <float> input = new DenseTensor <float>(new[] { 1, 3, h, w }); for (int y = 0; y < clone.Height; y++) { Span <Rgb24> pixelSpan = clone.GetPixelRowSpan(y); for (int x = 0; x < clone.Width; x++) { input[0, 0, y, x] = pixelSpan[x].B / 255f; input[0, 1, y, x] = pixelSpan[x].G / 255f; input[0, 2, y, x] = pixelSpan[x].R / 255f; } } //Get the Image Shape var image_shape = new DenseTensor <float>(new[] { 1, 2 }); image_shape[0, 0] = ih; image_shape[0, 1] = iw; // Setup inputs and outputs var container = new List <NamedOnnxValue>(); container.Add(NamedOnnxValue.CreateFromTensor("input_1", input)); container.Add(NamedOnnxValue.CreateFromTensor("image_shape", image_shape)); // Session Options SessionOptions options = new SessionOptions(); options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO; options.AppendExecutionProvider_OpenVINO(@"MYRIAD_FP16"); options.AppendExecutionProvider_CPU(1); // Run inference using var session = new InferenceSession(modelFilePath, options); using IDisposableReadOnlyCollection <DisposableNamedOnnxValue> results = session.Run(container); Console.WriteLine("Inference done"); //Post Processing Steps var resultsArray = results.ToArray(); Tensor <float> boxes = resultsArray[0].AsTensor <float>(); Tensor <float> scores = resultsArray[1].AsTensor <float>(); int[] indices = resultsArray[2].AsTensor <int>().ToArray(); var len = indices.Length / 3; var out_classes = new int[len]; float[] out_scores = new float[len]; var predictions = new List <Prediction>(); var count = 0; for (int i = 0; i < indices.Length; i = i + 3) { out_classes[count] = indices[i + 1]; out_scores[count] = scores[indices[i], indices[i + 1], indices[i + 2]]; predictions.Add(new Prediction { Box = new Box(boxes[indices[i], indices[i + 2], 1], boxes[indices[i], indices[i + 2], 0], boxes[indices[i], indices[i + 2], 3], boxes[indices[i], indices[i + 2], 2]), Class = LabelMap.Labels[out_classes[count]], Score = out_scores[count] }); count++; } // Put boxes, labels and confidence on image and save for viewing using var outputImage = File.OpenWrite(outImageFilePath); Font font = SystemFonts.CreateFont("Arial", 16); foreach (var p in predictions) { imageOrg.Mutate(x => { x.DrawLines(Color.Red, 2f, new PointF[] { new PointF(p.Box.Xmin, p.Box.Ymin), new PointF(p.Box.Xmax, p.Box.Ymin), new PointF(p.Box.Xmax, p.Box.Ymin), new PointF(p.Box.Xmax, p.Box.Ymax), new PointF(p.Box.Xmax, p.Box.Ymax), new PointF(p.Box.Xmin, p.Box.Ymax), new PointF(p.Box.Xmin, p.Box.Ymax), new PointF(p.Box.Xmin, p.Box.Ymin) }); x.DrawText($"{p.Class}, {p.Score:0.00}", font, Color.White, new PointF(p.Box.Xmin, p.Box.Ymin)); }); } imageOrg.Save(outputImage, format); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } var game = app.ApplicationServices.GetService <IGame>(); game.Begin(); // let the game begin! var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; app.UseCors(builder => builder .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin()); var sessionOptions = new SessionOptions(); app.UseSession(sessionOptions); app.UseMiddleware <AuthMiddleware>(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseWebSockets(webSocketOptions); app.UseMvc(); app.Use(async(context, next) => { await context.Session.LoadAsync(); context.Session.SetInt32("active", 1); if (context.Request.Path == "/ws") { var playerSessionProvider = context.RequestServices.GetService <IPlayerSessionProvider>(); if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); var playerSession = await playerSessionProvider.GetAsync(webSocket); if (playerSession == null) { await webSocket.CloseAsync( WebSocketCloseStatus.InternalServerError, "Nope", CancellationToken.None); return; } await context.Session.CommitAsync(); await playerSession.KeepAlive(); } else { context.Response.StatusCode = 400; } } else { await next(); } }); }
public void ProcessJobs() { Program.AddRTBText(rtbStatus, "Processing Jobs"); // Load Mailbox List foreach (DataRow row in dsProfiles.Tables["Mailbox"].Rows) { //Create list of profiles that are attached to the Current Mailbox DataRow[] drRule = dsProfiles.Tables["Rule"].Select("MailBox_id = " + row["Mailbox_id"]); ProfileMailServer mserver = new ProfileMailServer(); mserver.Hostname = row["PopServer"].ToString(); mserver.Port = int.Parse((row["PopPort"].ToString())); mserver.UserName = row["PopUsername"].ToString(); mserver.Password = row["PopPassword"].ToString(); mserver.SSL = row["PopSSL"].ToString(); mserver.AddressTo = row["AddressTo"].ToString(); //Create list of Messages from Current mailbox. Program.AddRTBText(rtbStatus, String.Format("{0:g} ", DateTime.Now) + " Connecting to " + mserver.Hostname + " for mailbox : " + mserver.AddressTo); List <MsgSummary> msgList = RetrieveEmails(mserver); if (msgList == null) { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " No Email found. Moving to next Profile.", Color.Gray); } else { foreach (MsgSummary msg in msgList) { if (msg.MsgFile != null) { foreach (MsgAtt att in msg.MsgFile) { bool ruleFound = false; foreach (DataRow rule in drRule) { if (!ruleFound) { //Loop through each profile to find valid rule ProfileMessage pMessage = new ProfileMessage(); pMessage.AddressFrom = rule["AddressFrom"].ToString(); pMessage.Subject = rule["Subject"].ToString(); pMessage.Action = rule["PopAction"].ToString(); pMessage.FTPServer = rule["FtpServer"].ToString(); pMessage.FTPFolder = rule["FtpFolder"].ToString(); pMessage.FTPPass = rule["FtpPassWord"].ToString(); pMessage.FTPPort = rule["FtpPort"].ToString(); pMessage.FTPUser = rule["FtpUserName"].ToString(); pMessage.ProfilePrinter = rule["PrintQueue"].ToString(); if (string.IsNullOrEmpty(rule["FtpSecure"].ToString())) { pMessage.Secure = false; } else { pMessage.Secure = bool.Parse(rule["FtpSecure"].ToString()); } if (MsgValid(msg, att, pMessage.AddressFrom, pMessage.Subject, "")) { switch (pMessage.Action) { case "FTP": Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Establishing FTP Connection for profile :" + pMessage.ProfileName, Color.Black); SessionOptions sessionOptions = new SessionOptions { HostName = pMessage.FTPServer, PortNumber = int.Parse(pMessage.FTPPort), UserName = pMessage.FTPUser, Password = pMessage.FTPPass }; if (pMessage.Secure) { sessionOptions.Protocol = Protocol.Sftp; } else { sessionOptions.Protocol = Protocol.Ftp; } try { TransferOperationResult tr; using (Session session = new Session()) { session.Open(sessionOptions); if (session.Opened) { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Connected to " + pMessage.FTPServer + ". Sending file :" + att.AttFilename, Color.Black); TransferOptions tOptions = new TransferOptions(); tOptions.OverwriteMode = OverwriteMode.Overwrite; tr = session.PutFiles(att.AttFilename.FullName, pMessage.FTPFolder, true, tOptions); Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Results: ", Color.Black); if (tr.IsSuccess) { MailModule.DeleteMessage(mserver.Hostname, mserver.Port, mserver.SSL, mserver.UserName, mserver.Password, msg.MsgId); } else { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Transfer Result is invalid: ", Color.Black); } } else { } } } catch (SessionRemoteException ex) { MessageBox.Show("FTP Server Error: " + ex.Message, "FTP Server Test", MessageBoxButtons.OK, MessageBoxIcon.Information); } break; case "Print": bool filePrinted = false; string fileType = att.AttFilename.Extension; Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Now Printing " + att.AttFilename.FullName, Color.Black); filePrinted = PrintDoc(att.AttFilename.FullName, pMessage.ProfilePrinter); if (filePrinted) { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Printed Ok.", Color.Black); MailModule.DeleteMessage(mserver.Hostname, mserver.Port, mserver.SSL, mserver.UserName, mserver.Password, msg.MsgId); } else { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Printing Failed !!", Color.Red); } break; } ruleFound = true; } //Process message against Profile Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Checking: " + pMessage.ProfileName, Color.Black); } } if (!ruleFound) { Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Invalid email found. Deleting message. From : " + msg.MsgFrom + " Subject: " + msg.MsgSubject, Color.Red);; MailModule.DeleteMessage(mserver.Hostname, mserver.Port, mserver.SSL, mserver.UserName, mserver.Password, msg.MsgId); ruleFound = true; } } //Looping through messages (and Attachments) } } } // PrintJobs(mserver.ProfilePrinter); } }
public CSession(Graph graph, Status s, bool user_XLA = false) { var opts = new SessionOptions(); session_ = new Session(graph, opts, s); }
public InceptionPage(Model model) : base() { Title = model == Model.Flower ? "Flower Recognition" : "Object recognition (Inception)"; _model = model; if (_inceptionGraph == null) { SessionOptions so = new SessionOptions(); if (TfInvoke.IsGoogleCudaEnabled) { Tensorflow.ConfigProto config = new Tensorflow.ConfigProto(); config.GpuOptions = new Tensorflow.GPUOptions(); config.GpuOptions.AllowGrowth = true; so.SetConfig(config.ToProtobuf()); } _inceptionGraph = new Inception(null, so); _inceptionGraph.OnDownloadProgressChanged += onDownloadProgressChanged; _inceptionGraph.OnDownloadCompleted += onDownloadCompleted; _inceptionGraph.OnDownloadCompleted += (sender, e) => { OnButtonClicked(sender, e); }; } OnImagesLoaded += (sender, image) => { #if !DEBUG try #endif { SetMessage("Please wait..."); SetImage(); Tensor imageTensor; if (_model == Model.Flower) { imageTensor = Emgu.TF.Models.ImageIO.ReadTensorFromImageFile <float>(image[0], 299, 299, 0.0f, 1.0f / 255.0f, false, false); } else { imageTensor = Emgu.TF.Models.ImageIO.ReadTensorFromImageFile <float>(image[0], 224, 224, 128.0f, 1.0f); } Inception.RecognitionResult result; if (_coldSession) { //First run of the recognition graph, here we will compile the graph and initialize the session //This is expected to take much longer time than consecutive runs. result = _inceptionGraph.Recognize(imageTensor)[0]; _coldSession = false; } //Here we are trying to time the execution of the graph after it is loaded //If we are not interest in the performance, we can skip the following 3 lines Stopwatch sw = Stopwatch.StartNew(); result = _inceptionGraph.Recognize(imageTensor)[0]; sw.Stop(); String msg = String.Format("Object is {0} with {1}% probability. Recognized in {2} milliseconds.", result.Label, result.Probability * 100, sw.ElapsedMilliseconds); SetMessage(msg); var jpeg = Emgu.Models.NativeImageIO.ImageFileToJpeg(image[0]); SetImage(jpeg.Raw, jpeg.Width, jpeg.Height); } #if !DEBUG catch (Exception excpt) { String msg = excpt.Message.Replace(System.Environment.NewLine, " "); SetMessage(msg); } #endif }; }
/// <summary> /// Downloads audio from the robot /// </summary> /// <param name="sender"> object that called the method </param> /// <param name="e"> any additional arguments </param> void bgWorker_DoWork(object sender, DoWorkEventArgs e) { // Setup session options SessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp, HostName = ipString, UserName = "******", Password = "******", SshHostKeyFingerprint = "ssh-rsa 20487c:48:34:e3:c0:7a:92:8e:2f:95:79:0e:12:69:79:e7", }; using (Session session = new Session()) { // tell library path to the winSCP executable session.ExecutablePath = System.IO.Directory.GetCurrentDirectory() + "\\winSCPexe.exe"; // Connect session.Open(sessionOptions); //Set up transfer TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; // generate a file based on date and time string time = Convert.ToString(DateTime.UtcNow.ToFileTime()); string destination = "C:\\NAOserver\\" + "NAO_Audio_" + time + ".ogg"; // download files TransferOperationResult transferResult; transferResult = session.GetFiles("/home/nao/temp.ogg", @destination, true, transferOptions); // Throw on any error transferResult.Check(); } }
/// <summary> /// Constructs OnnxModel object from file. /// </summary> /// <param name="modelFile">Model file path.</param> /// <param name="gpuDeviceId">GPU device ID to execute on. Null for CPU.</param> /// <param name="fallbackToCpu">If true, resumes CPU execution quietly upon GPU error.</param> /// <param name="ownModelFile">If true, the <paramref name="modelFile"/> will be deleted when <see cref="OnnxModel"/> is /// no longer needed.</param> /// <param name="shapeDictionary"></param> public OnnxModel(string modelFile, int?gpuDeviceId = null, bool fallbackToCpu = false, bool ownModelFile = false, IDictionary <string, int[]> shapeDictionary = null) { ModelFile = modelFile; // If we don't own the model file, _disposed should be false to prevent deleting user's file. _ownModelFile = ownModelFile; _disposed = false; if (gpuDeviceId != null) { try { _session = new InferenceSession(modelFile, SessionOptions.MakeSessionOptionWithCudaProvider(gpuDeviceId.Value)); } catch (OnnxRuntimeException) { if (fallbackToCpu) { _session = new InferenceSession(modelFile); } else { // If called from OnnxTransform, is caught and rethrown throw; } } } else { _session = new InferenceSession(modelFile); } try { // Load ONNX model file and parse its input and output schema. The reason of doing so is that ONNXRuntime // doesn't expose full type information via its C# APIs. ModelFile = modelFile; var model = new OnnxCSharpToProtoWrapper.ModelProto(); using (var modelStream = File.OpenRead(modelFile)) using (var codedStream = Google.Protobuf.CodedInputStream.CreateWithLimits(modelStream, Int32.MaxValue, 10)) model = OnnxCSharpToProtoWrapper.ModelProto.Parser.ParseFrom(codedStream); // Parse actual input and output types stored in the loaded ONNX model to get their DataViewType's. var inputTypePool = new Dictionary <string, DataViewType>(); foreach (var valueInfo in model.Graph.Input) { inputTypePool[valueInfo.Name] = OnnxTypeParser.GetDataViewType(valueInfo.Type); } var initializerTypePool = new Dictionary <string, DataViewType>(); foreach (var valueInfo in model.Graph.Initializer) { initializerTypePool[valueInfo.Name] = OnnxTypeParser.GetScalarDataViewType(valueInfo.DataType); } var outputTypePool = new Dictionary <string, DataViewType>(); // Build casters which maps NamedOnnxValue to .NET objects. var casterPool = new Dictionary <string, Func <NamedOnnxValue, object> >(); foreach (var valueInfo in model.Graph.Output) { outputTypePool[valueInfo.Name] = OnnxTypeParser.GetDataViewType(valueInfo.Type); casterPool[valueInfo.Name] = OnnxTypeParser.GetDataViewValueCasterAndResultedType(valueInfo.Type, out Type actualType); } var inputInfos = GetOnnxVariablesFromMetadata(_session.InputMetadata, shapeDictionary, inputTypePool, null); var outputInfos = GetOnnxVariablesFromMetadata(_session.OutputMetadata, shapeDictionary, outputTypePool, casterPool); var overrideableInitializers = GetOnnxVariablesFromMetadata(_session.OverridableInitializerMetadata, shapeDictionary, inputTypePool, null); // Create a view to the used ONNX model from ONNXRuntime's perspective. ModelInfo = new OnnxModelInfo(inputInfos, outputInfos, overrideableInitializers); Graph = model.Graph; } catch { _session.Dispose(); _session = null; throw; } }
public void RetrievingFileFromMUFGServer() { _logger.LogInformation("Asking for SFTP Credenitals."); GetSFTPDetailsforverification(); bool sessionOpenStatus = false; SessionOptions sessionOptionsSFTP = new SessionOptions { Protocol = Protocol.Sftp, HostName = sftpServerIP, UserName = sftpUserID, Password = sftpPassword, PortNumber = sftpPort, SshHostKeyFingerprint = stringHostKey }; Session sessionSFTP = new Session(); try { _logger.LogInformation("Trying to open the sftp session for Mufg"); sessionSFTP.Open(sessionOptionsSFTP); sessionOpenStatus = true; } catch (Exception e) { _logger.LogError("Unable to open the session."); _logger.LogError("Check the Exception: " + e.ToString() + " "); sessionOpenStatus = false; _logger.LogError("Logging out..."); return; _logger.LogError("Some exception occurs while creating session with server " + e.ToString()); } if (sessionOpenStatus == true) { _logger.LogInformation("SFTP Session Opened Succesfully"); } try { TransferOptions transferOptionsDownload = new TransferOptions(); transferOptionsDownload.TransferMode = TransferMode.Binary; transferOptionsDownload.PreserveTimestamp = true; transferOptionsDownload.ResumeSupport.State = TransferResumeSupportState.Off; TransferOperationResult transferOperationResult; try { _logger.LogInformation("Function to download file from server is called. "); TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult; transferResult = sessionSFTP.GetFiles("/confirmresponses/ConfirmationReport*.csv", @"Z:\Production\Blotter\SFTP\MUFG\ConfirmationReport\", false, transferOptions); //sessionSFTP.GetFiles("/confirmresponses/ConfirmationReport*.csv", @"Z:\Vendors\Alliance Staging\MUFG Circle Testing\ConfirmationReport\", false, transferOptions); _logger.LogInformation("status of downloading the files from the remote to local RV drive == " + transferResult.IsSuccess); } catch (Exception e) { _logger.LogError("Exception occurred in downloading files from server " + e); } } catch (Exception ex) { _logger.LogError("Exception occurred while processing directory: confirmresponses, exception is >> " + ex); } DirectoryInfo directory = new DirectoryInfo("Z:\\Production\\Blotter\\SFTP\\MUFG\\ConfirmationReport\\"); //DirectoryInfo directory = new DirectoryInfo("Z:\\Vendors\\Alliance Staging\\MUFG Circle Testing\\ConfirmationReport\\"); _logger.LogInformation(" Directory available is : " + directory.FullName + " No of files are: " + directory.GetFiles().Count()); var files = directory.GetFiles(); foreach (var file in files) { _logger.LogInformation("Started To Process file >> >> " + file); string filename = Path.GetFileNameWithoutExtension(file.Name); _logger.LogInformation("Started To Process file with file.name >> >> " + file.Name); var splits = filename.Split('_'); string date = splits[1]; string time = splits[2]; UpdateTradesForTradeids(file.FullName); _logger.LogInformation("Started To move file "); string sourcepath = "/confirmresponses/" + filename + ".csv"; string targetpath = "/confirmresponses/RVReadFiles/" + filename + ".csv"; string localProcessedFilePath = "Z:\\Production\\Blotter\\SFTP\\MUFG\\ProcessedConfirmationReport"; // "Z:\\Vendors\\Alliance Staging\\MUFG Circle Testing\\ProcessedConfirmationReport\\"; try { sessionSFTP.MoveFile("/confirmresponses/" + filename + ".csv", "/confirmresponses/RVReadFiles/" + filename + ".csv"); _logger.LogInformation("File has been moved sucessfully from >> " + sourcepath + " to " + targetpath); _logger.LogInformation("Trying to move processed file from local directory" + directory + filename + " to ProcessedFiles folder."); File.Move(directory + "\\" + filename + ".csv", localProcessedFilePath + filename + ".csv"); } catch (Exception e) { _logger.LogError("Caught exception in moving file from " + sourcepath + " to " + targetpath + " for file >>" + filename); } } sessionSFTP.Close(); }
public void TestSessionOptions() { using (SessionOptions opt = new SessionOptions()) { Assert.NotNull(opt); // check default values of the properties Assert.True(opt.EnableSequentialExecution); Assert.True(opt.EnableMemoryPattern); Assert.False(opt.EnableProfiling); Assert.Equal("onnxruntime_profile_", opt.ProfileOutputPathPrefix); Assert.True(opt.EnableCpuMemArena); Assert.Equal("", opt.LogId); Assert.Equal(LogLevel.Verbose, opt.LogVerbosityLevel); Assert.Equal(0, opt.IntraOpNumThreads); Assert.Equal(0, opt.InterOpNumThreads); Assert.Equal(GraphOptimizationLevel.ORT_ENABLE_BASIC, opt.GraphOptimizationLevel); // try setting options opt.EnableSequentialExecution = false; Assert.False(opt.EnableSequentialExecution); opt.EnableMemoryPattern = false; Assert.False(opt.EnableMemoryPattern); opt.EnableProfiling = true; Assert.True(opt.EnableProfiling); Assert.Equal("onnxruntime_profile_", opt.ProfileOutputPathPrefix); opt.ProfileOutputPathPrefix = "Ort_P_"; Assert.Equal("Ort_P_", opt.ProfileOutputPathPrefix); opt.EnableCpuMemArena = false; Assert.False(opt.EnableCpuMemArena); opt.LogId = "MyLogId"; Assert.Equal("MyLogId", opt.LogId); opt.LogVerbosityLevel = LogLevel.Error; Assert.Equal(LogLevel.Error, opt.LogVerbosityLevel); opt.IntraOpNumThreads = 4; Assert.Equal(4, opt.IntraOpNumThreads); opt.InterOpNumThreads = 4; Assert.Equal(4, opt.InterOpNumThreads); opt.GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_EXTENDED; Assert.Equal(GraphOptimizationLevel.ORT_ENABLE_EXTENDED, opt.GraphOptimizationLevel); Assert.Throws <OnnxRuntimeException>(() => { opt.GraphOptimizationLevel = (GraphOptimizationLevel)10; }); opt.AppendExecutionProvider_CPU(1); #if USE_MKLDNN opt.AppendExecutionProvider_Mkldnn(0); #endif #if USE_CUDA opt.AppendExecutionProvider_CUDA(0); #endif #if USE_NGRAPH opt.AppendExecutionProvider_NGraph("CPU"); //TODO: this API should be refined #endif #if USE_OPENVINO opt.AppendExecutionProvider_OpenVINO(null); //TODO: this won't work, because the native side copies the const char* #endif #if USE_TENSORRT opt.AppendExecutionProvider_Tensorrt(0); #endif #if USE_NNAPI opt.AppendExecutionProvider_Nnapi(); #endif } }
public static void CargaArchivosBitacoraExportacionClienteSFTP(CLLASausageContext db) { var arhivosBitacoraExportacionCliente = db.ExpedienteDigitalBitacoraExportacionCliente.Where(w => w.RutaCompletaExportado != null && w.Exportado == null && DateTime.Now >= w.Programacion && w.IdExpedienteDigitalTipoExportacion == 3).ToList(); foreach (var archivo in arhivosBitacoraExportacionCliente) { if (File.Exists(archivo.RutaOrigen)) { try { SessionOptions sessionOptions = new SessionOptions(); sessionOptions.HostName = archivo.Servidor; sessionOptions.PortNumber = Convert.ToInt32(archivo.Puerto); sessionOptions.UserName = archivo.Usuario; sessionOptions.Password = archivo.Contrasenia; sessionOptions.Protocol = Protocol.Sftp; sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true; Session session = new Session(); session.Open(sessionOptions); string rutaRaizFormateada = archivo.RutaRaiz.Substring(1).Replace(@"\", "/"); if (!session.FileExists(rutaRaizFormateada)) { var directorios = rutaRaizFormateada.Split('/').Where(w => w.Length > 0).ToList(); string ruta = string.Empty; foreach (var directorio in directorios) { ruta = ruta + "/" + directorio; if (!session.FileExists(ruta)) { session.CreateDirectory(ruta); } } } session.PutFileToDirectory(archivo.RutaOrigen, archivo.RutaRaiz.Substring(1).Replace(@"\", "/"), false, new TransferOptions { OverwriteMode = OverwriteMode.Overwrite }); session.Close(); archivo.Exportado = DateTime.Now; } catch (Exception ex) { archivo.Error = DateTime.Now; archivo.ErrorIdExpedienteDigitalEvento = (int)Modelos.Enumerados.ExpedienteDigitalEventoBitacora.FALTA_ARCHIVO_ORIGEN; archivo.ErrorObservaciones = Excepciones.ObtenerMensajesExcepcionEnCadenaSencilla(ex); } } else { archivo.Error = DateTime.Now; archivo.ErrorIdExpedienteDigitalEvento = (int)Modelos.Enumerados.ExpedienteDigitalEventoBitacora.FALTA_ARCHIVO_ORIGEN; archivo.ErrorObservaciones = "FALTA ARCHIVO EN ORIGEN"; } db.SaveChanges(); } }
/// <summary> /// This example Bloomberg request starts a session meant for Reference Requests and requests a few fields for several securities. /// I pulled this example code almost line-for-line from section C.1 of the Bloomberg API Developer's Guide /// </summary> public static void RunExample() { SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "127.0.0.1"; sessionOptions.ServerPort = 8194; Session session = new Session(sessionOptions); if (session.Start() && session.OpenService("//blp/refdata")) { Service refDataService = session.GetService("//blp/refdata"); if (refDataService == null) { Console.WriteLine("Cannot get service"); } else { Request request = refDataService.CreateRequest("IntradayTickRequest"); string security = "SPY US Equity"; //security = "ZYZZ US EQUITY"; //the code treats securities that start with a "Z" as non-existent request.Set("security", security); request.Append("eventTypes", "TRADE"); //One of TRADE (default), BID, ASK, BID_BEST, ASK_BEST, MID_PRICE, AT_TRADE, BEST_BID, BEST_ASK (see documentation A.2.6 for explanations) request.Append("eventTypes", "BID"); //A request can have multiple eventTypes //Note 1) refDataService.ToString() using the Bloomberg API indicates an additional eventType called "SETTLE". "SETTLE" doesn't seem to produce any results. //Note 2) If you request an eventType that isn't supported, the API will throw a KeyNotSupportedException at the "request.Append("eventType", "XXX")" line //Note 3) eventType values are case-sensitive. Requesting "bid" instead of "BID" will throw a KeyNotSupportedException at the "request.Append("eventType", "bid")" line DateTime dtYesterday = DateTime.Today.AddDays(-1); while (dtYesterday.DayOfWeek == DayOfWeek.Saturday || dtYesterday.DayOfWeek == DayOfWeek.Sunday) { dtYesterday = dtYesterday.AddDays(-1); } request.Set("startDateTime", new Datetime(dtYesterday.AddHours(9.5).ToUniversalTime())); request.Set("endDateTime", new Datetime(dtYesterday.AddHours(11).ToUniversalTime())); //goes back at most 140 days (documentation section 7.2.3) //A comma delimited list of exchange condition codes associated with the event. Review QR<GO> for more information on each code returned. request.Set("includeConditionCodes", false); //Optional bool. Valid values are true and false (default = false) //Returns all ticks, including those with condition codes. request.Set("includeNonPlottableEvents", false); //Optional bool. Valid values are true and false (default = false) //The exchange code where this tick originated. Review QR<GO> for more information. request.Set("includeExchangeCodes", false); //Optional bool. Valid values are true and false (default = false) //Option on whether to return EIDs for the security. request.Set("returnEids", false); //Optional bool. Valid values are true and false (default = false) //The broker code for Canadian, Finnish, Mexican, Philippine, and Swedish equities only. // The Market Maker Lookup screen, MMTK<GO>, displays further information on market makers and their corresponding codes. request.Set("includeBrokerCodes", false); //Optional bool. Valid values are true and false (default = false) //The Reporting Party Side. The following values appear: // -B: A customer transaction where the dealer purchases securities from the customer. // -S: A customer transaction where the dealer sells securities to the customer. // -D: An inter-dealer transaction (always from the sell side). request.Set("includeRpsCodes", false); //Optional bool. Valid values are true and false (default = false) //The BIC, or Bank Identifier Code, as a 4-character unique identifier for each bank that executed and reported the OTC trade, as required by MiFID. // BICs are assigned and maintained by SWIFT (Society for Worldwide Interbank Financial Telecommunication). // The MIC is the Market Identifier Code, and this indicates the venue on which the trade was executed. request.Set("includeBicMicCodes", false); //Optional bool. Valid values are true and false (default = false) CorrelationID corr = new CorrelationID(17); session.SendRequest(request, corr); bool continueToLoop = true; while (continueToLoop) { Event evt = session.NextEvent(); switch (evt.Type) { case Event.EventType.RESPONSE: IntradayTickDataRequest.ProcessResponse(evt, security); continueToLoop = false; break; case Event.EventType.PARTIAL_RESPONSE: IntradayTickDataRequest.ProcessResponse(evt, security); break; } } } } else { Console.WriteLine("Cannot connect to server. Check that the server host is \"localhost\" or \"127.0.0.1\" and that the server port is 8194."); } }
private void TestTensorRTProviderOptions() { string modelPath = Path.Combine(Directory.GetCurrentDirectory(), "squeezenet.onnx"); string calTablePath = "squeezenet_calibration.flatbuffers"; string enginePath = "./"; string engineDecrptLibPath = "engine_decryp"; using (var cleanUp = new DisposableListTest <IDisposable>()) { var trtProviderOptions = new OrtTensorRTProviderOptions(); cleanUp.Add(trtProviderOptions); var providerOptionsDict = new Dictionary <string, string>(); providerOptionsDict["device_id"] = "0"; providerOptionsDict["trt_fp16_enable"] = "1"; providerOptionsDict["trt_int8_enable"] = "1"; providerOptionsDict["trt_int8_calibration_table_name"] = calTablePath; providerOptionsDict["trt_engine_cache_enable"] = "1"; providerOptionsDict["trt_engine_cache_path"] = enginePath; providerOptionsDict["trt_engine_decryption_enable"] = "0"; providerOptionsDict["trt_engine_decryption_lib_path"] = engineDecrptLibPath; trtProviderOptions.UpdateOptions(providerOptionsDict); var resultProviderOptionsDict = new Dictionary <string, string>(); ProviderOptionsValueHelper.StringToDict(trtProviderOptions.GetOptions(), resultProviderOptionsDict); // test provider options configuration string value; value = resultProviderOptionsDict["device_id"]; Assert.Equal("0", value); value = resultProviderOptionsDict["trt_fp16_enable"]; Assert.Equal("1", value); value = resultProviderOptionsDict["trt_int8_enable"]; Assert.Equal("1", value); value = resultProviderOptionsDict["trt_int8_calibration_table_name"]; Assert.Equal(calTablePath, value); value = resultProviderOptionsDict["trt_engine_cache_enable"]; Assert.Equal("1", value); value = resultProviderOptionsDict["trt_engine_cache_path"]; Assert.Equal(enginePath, value); value = resultProviderOptionsDict["trt_engine_decryption_enable"]; Assert.Equal("0", value); value = resultProviderOptionsDict["trt_engine_decryption_lib_path"]; Assert.Equal(engineDecrptLibPath, value); // test correctness of provider options SessionOptions options = SessionOptions.MakeSessionOptionWithTensorrtProvider(trtProviderOptions); cleanUp.Add(options); var session = new InferenceSession(modelPath, options); cleanUp.Add(session); var inputMeta = session.InputMetadata; var container = new List <NamedOnnxValue>(); float[] inputData = TestDataLoader.LoadTensorFromFile(@"bench.in"); // this is the data for only one input tensor for this model foreach (var name in inputMeta.Keys) { Assert.Equal(typeof(float), inputMeta[name].ElementType); Assert.True(inputMeta[name].IsTensor); var tensor = new DenseTensor <float>(inputData, inputMeta[name].Dimensions); container.Add(NamedOnnxValue.CreateFromTensor <float>(name, tensor)); } session.Run(container); } }
public abstract IAsyncDocumentSession OpenAsyncSession(SessionOptions sessionOptions);
private void TestRegisterCustomOpLibrary() { using (var option = new SessionOptions()) { string libName = "custom_op_library.dll"; string modelPath = "custom_op_test.onnx"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { libName = "custom_op_library.dll"; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { libName = "libcustom_op_library.so"; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { libName = "libcustom_op_library.dylib"; } string libFullPath = Path.Combine(Directory.GetCurrentDirectory(), libName); Assert.True(File.Exists(libFullPath), $"Expected lib {libFullPath} does not exist."); var ortEnvInstance = OrtEnv.Instance(); string[] providers = ortEnvInstance.GetAvailableProviders(); if (Array.Exists(providers, provider => provider == "CUDAExecutionProvider")) { option.AppendExecutionProvider_CUDA(0); } IntPtr libraryHandle = IntPtr.Zero; try { option.RegisterCustomOpLibraryV2(libFullPath, out libraryHandle); } catch (Exception ex) { var msg = $"Failed to load custom op library {libFullPath}, error = {ex.Message}"; throw new Exception(msg + "\n" + ex.StackTrace); } using (var session = new InferenceSession(modelPath, option)) { var inputContainer = new List <NamedOnnxValue>(); inputContainer.Add(NamedOnnxValue.CreateFromTensor <float>("input_1", new DenseTensor <float>( new float[] { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f, 6.6f, 7.7f, 8.8f, 9.9f, 10.0f, 11.1f, 12.2f, 13.3f, 14.4f, 15.5f }, new int[] { 3, 5 } ))); inputContainer.Add(NamedOnnxValue.CreateFromTensor <float>("input_2", new DenseTensor <float>( new float[] { 15.5f, 14.4f, 13.3f, 12.2f, 11.1f, 10.0f, 9.9f, 8.8f, 7.7f, 6.6f, 5.5f, 4.4f, 3.3f, 2.2f, 1.1f }, new int[] { 3, 5 } ))); using (var result = session.Run(inputContainer)) { Assert.Equal("output", result.First().Name); var tensorOut = result.First().AsTensor <int>(); var expectedOut = new DenseTensor <int>( new int[] { 17, 17, 17, 17, 17, 17, 18, 18, 18, 17, 17, 17, 17, 17, 17 }, new int[] { 3, 5 } ); Assert.True(tensorOut.SequenceEqual(expectedOut)); } } // Safe to unload the custom op shared library now UnloadLibrary(libraryHandle); } }
private static void ConfigureSessionOptions(IServiceCollection services, SessionOptions config) { services.AddSession(options => { MergeHelper.Merge(config, options); }); }
private Session NewSession() { SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = "localhost"; sessionOptions.ServerPort = 8194; return new Session(sessionOptions, new Bloomberglp.Blpapi.EventHandler(ProcessEvent)); }
private void run(string[] args) { string serverHost = "localhost"; int serverPort = 8194; SessionOptions sessionOptions = new SessionOptions(); sessionOptions.ServerHost = serverHost; sessionOptions.ServerPort = serverPort; System.Console.WriteLine("Connecting to " + serverHost + ":" + serverPort); Session session = new Session(sessionOptions); bool sessionStarted = session.Start(); if (!sessionStarted) { System.Console.Error.WriteLine("Failed to start session."); return; } if (!session.OpenService("//blp/refdata")) { System.Console.Error.WriteLine("Failed to open //blp/refdata"); return; } Service refDataService = session.GetService("//blp/refdata"); Request request = refDataService.CreateRequest("HistoricalDataRequest"); Element securities = request.GetElement("securities"); /// securities.AppendValue("IBM US Equity"); /// securities.AppendValue("MSFT US Equity"); securities.AppendValue("/isin/ES0213469580"); /// EIB EUR securities.AppendValue("/isin/XS0070553820"); /// EIB USD securities.AppendValue("/isin/US459056JW87"); /// IBRD USD securities.AppendValue("/isin/XS0094374872"); /// IBRD EUR Element fields = request.GetElement("fields"); fields.AppendValue("PX_LAST"); fields.AppendValue("OPEN"); request.Set("periodicityAdjustment", "ACTUAL"); request.Set("periodicitySelection", "MONTHLY"); request.Set("startDate", "20060101"); request.Set("endDate", "20061231"); request.Set("maxDataPoints", 100); request.Set("returnEids", true); System.Console.WriteLine("Sending Request: " + request); session.SendRequest(request, null); while (true) { Event eventObj = session.NextEvent(); foreach (Message msg in eventObj) { System.Console.WriteLine(msg.AsElement); } if (eventObj.Type == Event.EventType.RESPONSE) { break; } } }
public AmbientTransactionLifetime(SessionOptions options) { _options = options; }
private SessionOptions GetSessionOptions() { var sessionOptions = new SessionOptions { ServerHost = _host, ServerPort = _port }; return sessionOptions; }
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env) { //set root Server path var path = env.ContentRootPath + "\\"; Server.RootPath = path; //get environment based on application build switch (env.EnvironmentName.ToLower()) { case "production": Server.environment = Server.Environment.production; break; case "staging": Server.environment = Server.Environment.staging; break; default: Server.environment = Server.Environment.development; break; } //load application-wide cache var configFile = "config" + (Server.environment == Server.Environment.production ? ".prod" : "") + ".json"; config = new ConfigurationBuilder() .AddJsonFile(Server.MapPath(configFile)) .AddEnvironmentVariables().Build(); Server.config = config; //configure Server defaults Server.nameSpace = config.GetSection("assembly").Value; Server.defaultController = config.GetSection("defaultController").Value; Server.defaultServiceMethod = config.GetSection("defaultServiceMethod").Value; Server.hostUrl = config.GetSection("hostUrl").Value; var servicepaths = config.GetSection("servicePaths").Value; if (servicepaths != null && servicepaths != "") { Server.servicePaths = servicepaths.Replace(" ", "").Split(','); } if (config.GetSection("version").Value != null) { Server.Version = config.GetSection("version").Value; } //configure Server database connection strings Server.sqlActive = config.GetSection("sql:Active").Value; Server.sqlConnectionString = config.GetSection("sql:" + Server.sqlActive).Value; //configure Server security Server.bcrypt_workfactor = int.Parse(config.GetSection("Encryption:bcrypt_work_factor").Value); Server.salt = config.GetSection("Encryption:salt").Value; //configure cookie-based authentication var expires = !string.IsNullOrEmpty(config.GetSection("Session:Expires").Value) ? int.Parse(config.GetSection("Session:Expires").Value) : 60; //use session var sessionOpts = new SessionOptions(); sessionOpts.Cookie.Name = Server.nameSpace; sessionOpts.IdleTimeout = TimeSpan.FromMinutes(expires); app.UseSession(sessionOpts); //handle static files var provider = new FileExtensionContentTypeProvider(); // Add static file mappings provider.Mappings[".svg"] = "image/svg"; var options = new StaticFileOptions { ContentTypeProvider = provider }; app.UseStaticFiles(options); //exception handling if (Server.environment == Server.Environment.development) { app.UseDeveloperExceptionPage(new DeveloperExceptionPageOptions { SourceCodeLineCount = 10 }); } else { app.UseHsts(); } //use HTTPS //app.UseHttpsRedirection(); //set up database connection Query.Sql.connectionString = Server.sqlConnectionString; Server.resetPass = Query.Users.HasPasswords(); Server.hasAdmin = Query.Users.HasAdmin(); //run Datasilk application app.UseDatasilkMvc(new MvcOptions() { IgnoreRequestBodySize = true, Routes = new Routes(), WriteDebugInfoToConsole = true }); }