PageRenderTime 56ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/DICK.B1/B1Engine.cs

https://bitbucket.org/williamybs/uidipythontool
C# | 907 lines | 778 code | 63 blank | 66 comment | 64 complexity | 6d058743098a8215a3fcb742cea683f3 MD5 | raw file
  1. /* This file is part of DI Construction Kit.
  2. *
  3. * DI Construction Kit is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU Lesser General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * DI Construction Kit is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Lesser General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU Lesser General Public License
  14. * along with DI Construction Kit. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. */
  17. using System;
  18. using System.Collections;
  19. using System.Reflection;
  20. using System.Collections.Generic;
  21. using System.IO;
  22. using System.Text;
  23. using System.Data;
  24. using DICK;
  25. using DICK.Core;
  26. using DICK.Core.JobManagement;
  27. using SAPbobsCOM;
  28. using System.Xml;
  29. using IronPython.Hosting;
  30. using IronPython.Runtime;
  31. using Microsoft.Scripting;
  32. using Microsoft.Scripting.Hosting;
  33. using Fireball.Syntax;
  34. namespace DICK.B1
  35. {
  36. /// <summary>
  37. /// B1Engine is an extension of the DICK.Core.Engine class
  38. /// that adds the B1-dependent functionality to the core class.
  39. /// </summary>
  40. public class B1Engine : Engine
  41. {
  42. public const int MAGIC_NULLERRORCODE = -666;
  43. private DataTable dataservertypes;
  44. /// <summary>
  45. /// DataTable containing the database server types supported by DICK.
  46. /// </summary>
  47. public DataTable DataServerTypes
  48. {
  49. get
  50. {
  51. return dataservertypes;
  52. }
  53. }
  54. public string systemdescription;
  55. public CompanyClass session;
  56. private static B1Engine B1instance;
  57. public static bool AutoRelease { get; set; }
  58. public bool pythoninitialized = false;
  59. public ScriptEngine pythonengine;
  60. public ScriptScope scope;
  61. public Dictionary<string, object> B1EnumClassList = new Dictionary<string, object>();
  62. public Dictionary<string, object> B1EnumList = new Dictionary<string, object>();
  63. public Dictionary<string, object> B1EnumValues = new Dictionary<string, object>();
  64. public Dictionary<string, object> B1ObjectList = new Dictionary<string, object>();
  65. public Dictionary<string, object> B1ServiceList = new Dictionary<string, object>();
  66. public enum LISTCASE {
  67. /// <summary>
  68. /// Uppercase
  69. /// </summary>
  70. CASE_UPPER,
  71. /// <summary>
  72. /// Lowercase
  73. /// </summary>
  74. CASE_LOWER,
  75. /// <summary>
  76. /// Any case
  77. /// </summary>
  78. CASE_ALL,
  79. /// <summary>
  80. /// Upper and lower case mixed
  81. /// </summary>
  82. CASE_MIXED};
  83. private B1Engine()
  84. {
  85. PopulateDataServerTypeList();
  86. PopulateB1BusinessObjectList();
  87. PopulateB1ServiceList();
  88. PopulateB1EnumList();
  89. }
  90. private void PopulateB1ServiceList()
  91. {
  92. foreach (object st in Enum.GetValues(typeof(SAPbobsCOM.ServiceTypes)))
  93. {
  94. string sname = st.ToString();
  95. AddIfKeyNotExists(B1ServiceList, sname, st);
  96. AddIfKeyNotExists(B1ServiceList, sname.ToLower(), st);
  97. AddIfKeyNotExists(B1ServiceList, sname.ToUpper(), st);
  98. AddIfKeyNotExists(B1ServiceList, sname.Substring(0,sname.Length-7), st);
  99. AddIfKeyNotExists(B1ServiceList, sname.Substring(0, sname.Length - 7).ToLower(), st);
  100. AddIfKeyNotExists(B1ServiceList, sname.Substring(0, sname.Length - 7).ToUpper(), st);
  101. }
  102. }
  103. private void PopulateDataServerTypeList()
  104. {
  105. dataservertypes = new DataTable("ServerTypes");
  106. dataservertypes.Columns.Add("ServerTypeName", typeof(String));
  107. dataservertypes.Columns.Add("ServerType", typeof(BoDataServerTypes));
  108. string[] dbtypenames = Enum.GetNames(typeof(BoDataServerTypes));
  109. System.Array dbtypevalues = Enum.GetValues(typeof(BoDataServerTypes));
  110. for (int i = 0; i < dbtypenames.Length; i++)
  111. {
  112. string dbtypename = dbtypenames[i].Substring(4, dbtypenames[i].Length - 4).Replace("_", "");
  113. dataservertypes.Rows.Add(dbtypename, dbtypevalues.GetValue(i));
  114. }
  115. }
  116. private string currentIP;
  117. public string CurrentImportProgram
  118. {
  119. get { return currentIP; }
  120. set { currentIP = value; }
  121. }
  122. private string currentPythonJob;
  123. public string CurrentPythonJob
  124. {
  125. get { return currentPythonJob; }
  126. set { currentPythonJob = value; }
  127. }
  128. /// <summary>
  129. /// Used to retrieve a correct type of job
  130. /// </summary>
  131. /// <param name="jobid"></param>
  132. /// <param name="row"></param>
  133. /// <returns></returns>
  134. /// <exclude/>
  135. protected override ExportJob GetRealJob(string jobid, XmlElement row)
  136. {
  137. XmlNode b1 = row.SelectSingleNode("B1Required");
  138. if (b1 != null)
  139. {
  140. string b1RequiredString = b1.InnerText.ToLower().Trim();
  141. if (b1RequiredString.Equals("true"))
  142. {
  143. return new B1ExportJob(jobid, row);
  144. }
  145. else
  146. {
  147. return new ExportJob(jobid, row);
  148. }
  149. }
  150. else
  151. {
  152. LogError("ENGINE.GETREALJOB: B1REQUIRED PARAMETER NOT FOUND FOR JOB " + jobid);
  153. return null;
  154. }
  155. }
  156. public B1ImportJob SetCurrentImportJob(string ID)
  157. {
  158. currentIP = ID;
  159. return GetImportJob(currentIP);
  160. }
  161. public B1ImportJob GetCurrentImportJob()
  162. {
  163. return GetImportJob(currentIP);
  164. }
  165. public B1PythonJob SetCurrentPythonJob(string ID)
  166. {
  167. CurrentPythonJob = ID;
  168. return GetPythonJob(ID);
  169. }
  170. public B1PythonJob GetPythonJob(string name)
  171. {
  172. FileInfo fi = new FileInfo(pythonjobdirectory + name + ".xml");
  173. if (fi.Exists)
  174. {
  175. XmlDocument doc = new XmlDocument();
  176. try
  177. {
  178. doc.Load(fi.FullName);
  179. //Calling the virtual method here - it's overridden in B1Engine
  180. return new B1PythonJob(name, doc.DocumentElement);
  181. }
  182. catch (XmlException xex)
  183. {
  184. LogError("Failed parsing the xml document for ExportJob " + name + ":" + xex.Message);
  185. return null;
  186. }
  187. }
  188. else
  189. {
  190. LogError("ExportJob " + fi.FullName + " not found!");
  191. return null;
  192. }
  193. }
  194. public B1ImportJob GetImportJob(string name)
  195. {
  196. FileInfo fi = new FileInfo(importjobdirectory + name + ".xml");
  197. if (fi.Exists)
  198. {
  199. XmlDocument doc = new XmlDocument();
  200. try
  201. {
  202. doc.Load(fi.FullName);
  203. return new B1ImportJob(name, doc.DocumentElement);
  204. }
  205. catch (XmlException xex)
  206. {
  207. LogError("Failed parsing the xml document for ExportJob " + name + ":" + xex.Message);
  208. return null;
  209. }
  210. }
  211. else
  212. {
  213. LogError("ExportJob " + fi.FullName + " not found!");
  214. return null;
  215. }
  216. }
  217. public System.Collections.Generic.List<B1ImportJob> ListImports()
  218. {
  219. System.Collections.Generic.List<B1ImportJob> imports = new System.Collections.Generic.List<B1ImportJob>();
  220. DirectoryInfo di = new DirectoryInfo(importjobdirectory);
  221. if (di.Exists)
  222. {
  223. FileInfo[] files = di.GetFiles("*.xml");
  224. foreach (FileInfo file in files)
  225. {
  226. XmlDocument doc = new XmlDocument();
  227. doc.Load(file.FullName);
  228. try
  229. {
  230. imports.Add(new B1ImportJob(file.Name.Substring(0, file.Name.Length - 4), doc.DocumentElement));
  231. }
  232. catch (Exception ex)
  233. {
  234. Engine.GetInstance().LogDebug("Failed to initialize ImportJob " + file.Name + ". Errormessage:" + ex.Message);
  235. }
  236. }
  237. }
  238. else
  239. {
  240. LogError("The importjob directory " + di.FullName + " does not exist! ");
  241. }
  242. return imports;
  243. }
  244. /// <summary>
  245. /// Returns the singleton instance of B1Engine
  246. /// </summary>
  247. /// <returns></returns>
  248. public static new B1Engine GetInstance()
  249. {
  250. if (B1instance == null)
  251. {
  252. B1Init();
  253. }
  254. if (B1instance == null)
  255. {
  256. throw new DICKException();
  257. }
  258. return B1instance;
  259. }
  260. public ScriptEngine PythonInit(Stream outstream, Stream tracestream)
  261. {
  262. LogDebug("Initializing PythonEngine...");
  263. if (pythoninitialized)
  264. {
  265. LogDebug("Python already initialized.");
  266. return pythonengine;
  267. }
  268. else
  269. {
  270. pythonengine = Python.CreateEngine();
  271. scope = pythonengine.CreateScope();
  272. AddSessionHandleToPythonScope();
  273. MapStreams(outstream, tracestream);
  274. AddCurrentPathToPythonSearchPath();
  275. //pythonengine.SetStandardOutput(outstream);
  276. /* HUOMIOI NÄMÄ !!!
  277. pythonengine.SetStandardError(new MyStream(Shell));
  278. */
  279. AddDefaultReferencesToPythonScope();
  280. AddB1BusinessObjectReferencesToPythonScope();
  281. AddServiceReferencesToPythonScope();
  282. AddToolReferencesToPythonScope();
  283. AddB1EnumReferencesToPythonScope();
  284. pythoninitialized = true;
  285. }
  286. return pythonengine;
  287. }
  288. private void MapStreams(Stream outstream, Stream tracestream)
  289. {
  290. if (outstream != null)
  291. {
  292. pythonengine.Runtime.IO.SetOutput(outstream, Encoding.Default);
  293. }
  294. if (tracestream != null)
  295. {
  296. pythonengine.Runtime.IO.SetErrorOutput(tracestream, Encoding.Default);
  297. }
  298. }
  299. private void AddCurrentPathToPythonSearchPath()
  300. {
  301. List<string> paths = new List<string>();
  302. paths.Add(Environment.CurrentDirectory);
  303. pythonengine.SetSearchPaths(paths);
  304. }
  305. private void AddSessionHandleToPythonScope()
  306. {
  307. if (Connected)
  308. {
  309. scope.SetVariable("session", session);
  310. scope.SetVariable("Session", session);
  311. scope.SetVariable("SESSION", session);
  312. }
  313. else
  314. {
  315. LogError("Session is not connected!");
  316. throw new DICKException("B1Engine.PythonInit: Session is not connected!");
  317. }
  318. }
  319. private void AddB1BusinessObjectReferencesToPythonScope()
  320. {
  321. foreach (string key in B1ObjectList.Keys)
  322. {
  323. scope.SetVariable(key, B1ObjectList[key]);
  324. }
  325. }
  326. private void PopulateB1BusinessObjectList()
  327. {
  328. Array boobjecttypes = Enum.GetValues(typeof(SAPbobsCOM.BoObjectTypes));
  329. //IronPython.Runtime.List boobjecttypes = pythonengine.Execute<IronPython.Runtime.List>("dir(SAPbobsCOM.BoObjectTypes)", scope);
  330. foreach (object otype in boobjecttypes)
  331. {
  332. string otypename = otype.ToString();
  333. //if (otypename.StartsWith("o"))
  334. //{
  335. string handle;
  336. handle = ProcessObjectNames(otypename);
  337. //BoObjectTypes oref = pythonengine.Execute<BoObjectTypes>("SAPbobsCOM.BoObjectTypes." + otype, scope);
  338. //BoObjectTypes oref = Enum.GetValuesSAPbobsCOM.BoObjectTypes.//)Type.GetType("SAPbobsCOM.BoObjectTypes." + otype);
  339. AddIfKeyNotExists(B1ObjectList, handle, otype);
  340. AddIfKeyNotExists(B1ObjectList, handle.ToLower(), otype);
  341. AddIfKeyNotExists(B1ObjectList, handle.ToUpper(), otype);
  342. AddIfKeyNotExists(B1ObjectList, otypename, otype);
  343. AddIfKeyNotExists(B1ObjectList, otypename.ToLower(), otype);
  344. AddIfKeyNotExists(B1ObjectList, otypename.ToUpper(), otype);
  345. //}
  346. }
  347. }
  348. private static string ProcessObjectNames(string otypename)
  349. {
  350. string handle;
  351. int endcut = 2;
  352. if (otypename.ToUpper().EndsWith("US"))
  353. {
  354. endcut = 1;
  355. }
  356. else if (otypename.ToUpper().EndsWith("HES"))
  357. {
  358. endcut = 3;
  359. }
  360. else if (otypename.ToUpper().EndsWith("S"))
  361. {
  362. endcut = 2;
  363. }
  364. else
  365. {
  366. endcut = 1;
  367. }
  368. handle = otypename.Substring(1, otypename.Length - endcut).ToUpper();
  369. if (handle.EndsWith("IE"))
  370. {
  371. handle = handle.Substring(0, handle.Length - 2) + "Y";
  372. }
  373. return handle;
  374. }
  375. private void AddIfKeyNotExists(Dictionary<string, object> dictionary, string key, object value)
  376. {
  377. if (!dictionary.ContainsKey(key))
  378. {
  379. dictionary.Add(key, value);
  380. }
  381. }
  382. private void AddB1EnumReferencesToPythonScope()
  383. {
  384. foreach (string key in B1EnumList.Keys)
  385. {
  386. scope.SetVariable(key, B1EnumList[key]);
  387. }
  388. }
  389. private void PopulateB1EnumList()
  390. {
  391. System.Collections.Generic.List<string> enums = new System.Collections.Generic.List<string>();
  392. Assembly[] domainAssemblies = AppDomain.CurrentDomain.GetAssemblies();
  393. //TODO: In .NET 4.0 version, use LINQ for selecting the assemblies to process.
  394. foreach (Assembly ass in domainAssemblies)
  395. {
  396. if (ass.FullName.Contains("SAPbobsCOM"))
  397. {
  398. Type[] types = ass.GetTypes();
  399. foreach (Type type in types)
  400. {
  401. if (type.IsEnum)
  402. {
  403. string[] enumnames = System.Enum.GetNames(type);
  404. Array enumvalues = System.Enum.GetValues(type);
  405. for (int enumindex = 0; enumindex < enumnames.Length; enumindex++)
  406. {
  407. if (!enumnames[enumindex].StartsWith("o"))
  408. {
  409. B1EnumList.Add(enumnames[enumindex], enumvalues.GetValue(enumindex));
  410. B1EnumValues.Add(enumnames[enumindex], enumvalues.GetValue(enumindex).GetType().Name);
  411. Type enumclass = enumvalues.GetValue(enumindex).GetType();
  412. if (!B1EnumClassList.ContainsKey(enumclass.Name))
  413. {
  414. B1EnumClassList.Add(enumclass.Name, null);
  415. }
  416. }
  417. //enums.Add(type.Name + ":" + enumvalues.GetValue(enumindex));
  418. }
  419. }
  420. }
  421. }
  422. }
  423. }
  424. private void AddDefaultReferencesToPythonScope()
  425. {
  426. pythonengine.Execute("import clr;clr.AddReferenceToFile(\"Interop.SAPbobsCOM.dll\")", scope);
  427. pythonengine.Execute("import SAPbobsCOM;import System;import System.IO;import System.Text;import System.Collections", scope);
  428. }
  429. private void AddToolReferencesToPythonScope()
  430. {
  431. scope.SetVariable("Engine", this);
  432. scope.SetVariable("engine", this);
  433. scope.SetVariable("ENGINE", this);
  434. scope.SetVariable("TextTools", typeof(TextTools));
  435. scope.SetVariable("texttools", typeof(TextTools));
  436. scope.SetVariable("TEXTTOOLS", typeof(TextTools));
  437. scope.SetVariable("XmlTools", typeof(XmlTools));
  438. scope.SetVariable("xmltools", typeof(XmlTools));
  439. scope.SetVariable("XMLTOOLS", typeof(XmlTools));
  440. scope.SetVariable("QueryToolsADO", typeof(QueryToolsADO));
  441. scope.SetVariable("querytoolsado", typeof(QueryToolsADO));
  442. scope.SetVariable("QUERYTOOLSADO", typeof(QueryToolsADO));
  443. scope.SetVariable("B1QueryTools", typeof(B1QueryTools));
  444. scope.SetVariable("b1querytools", typeof(B1QueryTools));
  445. scope.SetVariable("B1QUERYTOOLS", typeof(B1QueryTools));
  446. }
  447. private void AddServiceReferencesToPythonScope()
  448. {
  449. foreach (string stype in B1ServiceList.Keys)
  450. {
  451. object svc = B1ServiceList[stype];
  452. scope.SetVariable(stype, svc);
  453. }
  454. }
  455. public object ExecutePython(string statement)
  456. {
  457. if (pythoninitialized)
  458. {
  459. LogDebug("PYTHON EXECUTING: " + statement);
  460. object result = pythonengine.Execute(statement, scope);
  461. if (result != null)
  462. {
  463. LogDebug("PYTHON RETURNED: " + result.ToString());
  464. }
  465. else
  466. {
  467. LogDebug("PYTHON RETURNED NULL");
  468. }
  469. return result;
  470. }
  471. else
  472. {
  473. string message = "PYTHON ENGINE NOT INIIALIZED WHEN CALLING ExecutePython with statement " + statement;
  474. B1Engine.GetInstance().LogDebug(message);
  475. return message;
  476. }
  477. }
  478. public void ReleaseComObject(object o)
  479. {
  480. if (AutoRelease)
  481. {
  482. System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o);
  483. }
  484. }
  485. public static string FormatValue(object initial, string format)
  486. {
  487. B1Engine app = B1Engine.GetInstance();
  488. if (initial == null || format == null)
  489. {
  490. app.LogWarn("ERROR: EITHER the initial value or the format string is null!");
  491. return "FORMAT OBJECT IS NULL";
  492. }
  493. try
  494. {
  495. switch (format.ToLower())
  496. {
  497. case "date":
  498. System.DateTime intermediateDate = (System.DateTime)initial;
  499. string res = intermediateDate.ToString("yyyyMMdd");
  500. app.LogDebug("Converted " + initial.ToString() + " into " + res);
  501. return res;
  502. case "currency":
  503. SBObob bob = (SBObob)app.session.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoBridge);
  504. Recordset rs = bob.Format_MoneyToString((double)initial, BoMoneyPrecisionTypes.mpt_Sum);
  505. return rs.Fields.Item(0).Value.ToString().Replace(".", "");
  506. case "html":
  507. return TextTools.HtmlEncode(initial);
  508. case "url":
  509. return TextTools.UrlEncode(initial);
  510. case "xml":
  511. return TextTools.XmlEncode(initial);
  512. default:
  513. return "UNIDENTIFIED FORMAT";
  514. }
  515. }
  516. catch (Exception ex)
  517. {
  518. app.LogWarn("Failed to format value +" + initial + " to " + format + ". Message:" + ex.Message);
  519. return "Failed to format value " + initial == null ? "null" : initial.ToString() + " to " + format;
  520. }
  521. }
  522. #region Initialization and Login
  523. public static MessageToken B1Init()
  524. {
  525. return B1Init(null);
  526. }
  527. public static MessageToken B1Init(string workdirectory)
  528. {
  529. MessageToken res = new MessageToken();
  530. res.OK = false;
  531. if (B1instance == null)
  532. {
  533. //We need to initialize the base class first
  534. Engine coreengine = Engine.GetInstance();
  535. B1Engine.AutoRelease = true;
  536. B1instance = new B1Engine();
  537. //Set the instance Singleton field in the base class to point to the B1Engine instance.
  538. Engine.SetInstance(B1instance);
  539. //InitializeEngineclass is called from the base class
  540. res = InitializeEngine(workdirectory);
  541. if (res.OK)
  542. {
  543. B1instance.LogDebug("Creating an instance of SAPbobsCOM.CompanyClass...");
  544. try
  545. {
  546. B1instance.session = new SAPbobsCOM.CompanyClass();
  547. B1instance.LogDebug("OK");
  548. }
  549. catch (Exception ex)
  550. {
  551. B1instance.LogDebug("Instantiation failed:" + ex.Message);
  552. res.OK = false;
  553. res.AddTextToDetails("Instantiation failed:" + ex.Message);
  554. }
  555. return res;
  556. }
  557. else
  558. {
  559. Engine.GetInstance().LogError("Engine.B1Init failed:" + res.GetMessageBody());
  560. B1instance = null;
  561. Engine.SetInstance(null);
  562. res.AddTextToDetails("Returning from B1Init with failed CoreInit");
  563. return res;
  564. }
  565. }
  566. else
  567. {
  568. res.OK = true;
  569. return res;
  570. }
  571. }
  572. public CompanyClass Connect(string systemID, out string log)
  573. {
  574. MessageToken res = LoadSystemParameters(systemID);
  575. log = res.GetMessageBody();
  576. string log2;
  577. return Login(out log2);
  578. }
  579. /// <summary>
  580. /// Added to accommodate decoupling of DI API and the DICKcmd / DICK Visual Library assemblies.
  581. /// </summary>
  582. /// <param name="log"></param>
  583. public static void SilentLogin(out string log)
  584. {
  585. Login(out log);
  586. }
  587. public static CompanyClass Login(out string log)
  588. {
  589. log = "";
  590. B1Engine engine = B1Engine.GetInstance();
  591. if (engine.session == null)
  592. {
  593. engine.session = new CompanyClass();
  594. }
  595. engine.session.CompanyDB = engine.Db;
  596. engine.session.UserName = engine.User;
  597. engine.session.Password = engine.Password;
  598. engine.session.Server = engine.Host;
  599. engine.session.UseTrusted = engine.UseTrusted;
  600. BoDataServerTypes dst = BoDataServerTypes.dst_MSSQL2005;
  601. DataRow[] rows = engine.DataServerTypes.Select("ServerTypeName='" + engine.dataservertype + "'");
  602. if (rows.Length > 0)
  603. {
  604. dst = (BoDataServerTypes)rows[0]["ServerType"];
  605. }
  606. engine.session.DbServerType = dst;
  607. engine.session.language = BoSuppLangs.ln_English;
  608. if (!engine.session.UseTrusted)
  609. {
  610. engine.session.DbUserName = engine.dbusername;
  611. engine.session.DbPassword = engine.dbpwd;
  612. engine.session.LicenseServer = engine.LicenseServer;
  613. }
  614. int connectionFlag = -1;
  615. StringBuilder messages = new StringBuilder();
  616. try
  617. {
  618. messages.Append("Connecting... ");
  619. engine.LogInfo("Calling company.Connect()");
  620. connectionFlag = engine.session.Connect();
  621. engine.LogInfo("Connection flag:" + connectionFlag);
  622. }
  623. catch (NullReferenceException ex)
  624. {
  625. messages.Append(ex.Message);
  626. engine.LogError("Connection failed. There is a problem with the DI API.");
  627. engine.LogError(ex.Message);
  628. engine.LogError(ex.StackTrace);
  629. }
  630. if (connectionFlag == 0)
  631. {
  632. messages.Append("Connection ok");
  633. engine.LogInfo("Connected successfully to " + engine.session.CompanyName + ".");
  634. log += messages.ToString();
  635. string connectionstring = "Server = " + engine.Host + "; Database = " + engine.Db + "; User ID = " + engine.dbusername + "; Password = " + engine.dbpwd + "; Trusted_Connection = " + (engine.UseTrusted ? "True" : "False") + ";";
  636. engine.ConnectionString = connectionstring;
  637. return engine.session;
  638. }
  639. else
  640. {
  641. messages.Append(connectionFlag.ToString());
  642. int a;
  643. String b;
  644. engine.session.GetLastError(out a, out b);
  645. messages.Append(b);
  646. log += messages.ToString();
  647. engine.LogDebug("Login failed. Errorcode:" + a);
  648. engine.LogDebug("Error message:" + b);
  649. return null;
  650. }
  651. }
  652. #endregion
  653. public void SendSBOMessage(string[] recipients, string subject, string message)
  654. {
  655. try
  656. {
  657. Messages m = (Messages)session.GetBusinessObject(BoObjectTypes.oMessages);
  658. m.MessageText = message;
  659. m.Subject = subject;
  660. bool isfirstrecipient = true;
  661. foreach (string recipient in recipients)
  662. {
  663. if (!isfirstrecipient)
  664. {
  665. m.Recipients.Add();
  666. }
  667. m.Recipients.UserCode = recipient;
  668. m.Recipients.UserType = BoMsgRcpTypes.rt_InternalUser;
  669. m.Recipients.SendInternal = BoYesNoEnum.tYES;
  670. isfirstrecipient = false;
  671. }
  672. m.Add();
  673. }
  674. catch (Exception ex)
  675. {
  676. B1Engine.GetInstance().LogError("SendSBOMessage failed:" + ex.Message);
  677. }
  678. }
  679. #region Accessors and methods duplicated from SAPbobsCOM to enable decoupling of calling classes from DI API
  680. public String CompanyDB
  681. {
  682. get
  683. {
  684. return session.CompanyDB;
  685. }
  686. set
  687. {
  688. session.CompanyDB = value;
  689. }
  690. }
  691. public String DbPassword
  692. {
  693. get
  694. {
  695. return session.DbPassword;
  696. }
  697. set
  698. {
  699. session.DbPassword = value;
  700. }
  701. }
  702. public string DbServerType
  703. {
  704. get
  705. {
  706. return session.DbServerType.ToString();
  707. }
  708. set
  709. {
  710. const int FIRSTROW = 0;
  711. DataRow[] rows = DataServerTypes.Select("ServerTypeName='" + value + "'");
  712. if (rows != null && rows.Length > 0)
  713. {
  714. session.DbServerType = (BoDataServerTypes)rows[FIRSTROW]["ServerType"];
  715. }
  716. }
  717. }
  718. public string DbUserName
  719. {
  720. get
  721. {
  722. return session.DbUserName;
  723. }
  724. set
  725. {
  726. session.DbUserName = value;
  727. }
  728. }
  729. public string Server
  730. {
  731. get
  732. {
  733. return session.Server;
  734. }
  735. set
  736. {
  737. session.Server = value;
  738. }
  739. }
  740. public string CompanyName
  741. {
  742. get
  743. {
  744. return session.CompanyName;
  745. }
  746. }
  747. public bool Connected
  748. {
  749. get
  750. {
  751. return session != null && session.Connected;
  752. }
  753. }
  754. public void Disconnect()
  755. {
  756. if (session != null && session.Connected)
  757. {
  758. session.Disconnect();
  759. }
  760. }
  761. public int GetLastErrorCode()
  762. {
  763. if (session != null && session.Connected)
  764. {
  765. return session.GetLastErrorCode();
  766. }
  767. else
  768. {
  769. return MAGIC_NULLERRORCODE;
  770. }
  771. }
  772. public string GetLastErrorDescription()
  773. {
  774. if (session != null && session.Connected)
  775. {
  776. return session.GetLastErrorDescription();
  777. }
  778. else
  779. {
  780. return "SESSION INVALID OR NOT CONNECTED!";
  781. }
  782. }
  783. #endregion
  784. public ObjectTypeContainer[] GetObjectTypes()
  785. {
  786. string[] objectnames = Enum.GetNames(typeof(BoObjectTypes));
  787. ObjectTypeContainer[] otc = new ObjectTypeContainer[objectnames.Length];
  788. int ocounter = 0;
  789. foreach (string oname in objectnames)
  790. {
  791. BoObjectTypes t = (BoObjectTypes)Enum.Parse(typeof(BoObjectTypes), oname, true);
  792. ObjectTypeContainer li = new ObjectTypeContainer();
  793. li.Name = oname;
  794. li.Value = t;
  795. otc[ocounter] = li;
  796. ocounter++;
  797. }
  798. return otc;
  799. }
  800. public DataView GetCompanyDataView(B1Engine app)
  801. {
  802. Recordset rs;
  803. try
  804. {
  805. rs = app.session.GetCompanyList();
  806. }
  807. catch (System.Exception ex)
  808. {
  809. LogError(ex.Message);
  810. throw;
  811. }
  812. DataTable companytable = new DataTable("companies");
  813. DataColumn dbItem = new DataColumn("dbName", Type.GetType("System.String"));
  814. DataColumn cmpItem = new DataColumn("cmpName", Type.GetType("System.String"));
  815. DataColumn versItem = new DataColumn("versStr", Type.GetType("System.String"));
  816. companytable.Columns.Add(dbItem);
  817. companytable.Columns.Add(cmpItem);
  818. companytable.Columns.Add(versItem);
  819. DataView companyview = new DataView(companytable);
  820. int companyCount = rs.RecordCount;
  821. rs.MoveFirst();
  822. DataRow NewRow;
  823. for (int c = 0; c < companyCount; c++)
  824. {
  825. NewRow = companytable.NewRow();
  826. NewRow["dbName"] = rs.Fields.Item("dbName").Value;
  827. NewRow["cmpName"] = rs.Fields.Item("cmpName").Value;
  828. NewRow["versStr"] = rs.Fields.Item("versStr").Value;
  829. companytable.Rows.Add(NewRow);
  830. rs.MoveNext();
  831. }
  832. return companyview;
  833. }
  834. public object GetBOBHandle()
  835. {
  836. return session.GetBusinessObject(BoObjectTypes.BoBridge);
  837. }
  838. }
  839. public class ObjectTypeContainer
  840. {
  841. public string Name { get; set; }
  842. public BoObjectTypes Value { get; set; }
  843. }
  844. }