暂无描述

MainWindow.xaml.cs 112KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Globalization;
  15. using WpfLocalization;
  16. using System.Threading;
  17. using System.Data.SqlClient;
  18. using System.Data;
  19. using System.Diagnostics;
  20. using System.IO;
  21. using System.Collections;
  22. using System.IO.Ports;
  23. using System.Collections.ObjectModel;
  24. using System.Reflection;
  25. using System.Configuration;
  26. using System.Collections.Specialized;
  27. using System.Data.SqlServerCe;
  28. using System.ComponentModel;
  29. using System.Windows.Threading;
  30. using System.Data.OleDb;
  31. namespace WpfApplication19
  32. {
  33. /// <summary>
  34. /// Interaction logic for MainWindow.xaml
  35. /// </summary>
  36. ///
  37. public partial class MainWindow : Window
  38. {
  39. private bool isFullScreen = false;
  40. private Debug dw;
  41. public SqlConnection configConn, masterConn, transConn, proConn;
  42. private SqlCeConnection _opConn;
  43. //private SqlDataReader reader;
  44. string[] obTables = new string[] {"BEL-MAS-1", "BEL-MAS-3", "E-MAS-1", "E-MAS-3",
  45. "MG-MAS-1", "MG-MAS-3", "V-MAS-1", "V-MAS-3"};
  46. public SerialPort comport = new SerialPort();
  47. ObservableCollection<MeasurePoint> mps;
  48. int nextCol = 3;
  49. bool isMiddle = false, _haveMiddle = false;
  50. bool _isIn = false;
  51. public string inStarGS = "";
  52. public string midGS = "";
  53. string sMi16, sMi20, kind;
  54. enum RecordTypes { TopUnder, InOut }
  55. string[] masViews = new string[] { "bel_master_view", "e_master_view", "mg_master_view", "v_master_view" };
  56. List<string> list;
  57. string header;
  58. Stack<string> _lastAction = new Stack<string>();
  59. bool _isTkx = false;
  60. DateTime _lastTimeDataPort;
  61. bool _isCheck = false;
  62. DailyCheck _dc;
  63. RLAlert _rl;
  64. public RLWindow _rlWindow;
  65. Encoding encAscii = Encoding.ASCII;
  66. Dictionary<string, string> rolesDescription = new Dictionary<string, string>
  67. {
  68. {"qa_staff", "QA Staff"},{"user","User"}, {"admin", "Administrator"}, {"qa_man", "QA Ass't Manager"}
  69. };
  70. Dictionary<string, string> _sideMap = new Dictionary<string, string>
  71. {
  72. {"out", "in"},{"in","under"}, {"rim", "base"}, {"top", "under"}, {"outer", "inner"}
  73. };
  74. private double out0, out1;
  75. private double in0, in1;
  76. MeasurePoint currentMP;
  77. string currentColumn;
  78. Debug _debugWindow;
  79. Thread _aThread, _bThread;
  80. bool _clearThread = false, _canSent = true;
  81. int _pattern = 1;
  82. string _updated_at;
  83. private int _obLimit, _obCount, _ocLimit, _ocCount, _rhLimit, _rhCount;
  84. bool _isOver = false;
  85. bool _isFirstMeasure = true;
  86. DateTime _startUsing = new DateTime();
  87. int _usingTime;
  88. bool _isExisting = false;
  89. private List<string> _agreementList = new List<string>();
  90. string _currentValue, _prevValue = null;
  91. double _lower1, _upper1, _lower2, _upper2;
  92. string strAccessConnEMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\E-Master.mdb;Mode=Share Deny None";
  93. string strAccessConnBELMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\BEL-Master.mdb;Mode=Share Deny None";
  94. string strAccessConnMGMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\MG-Master.mdb;Mode=Share Deny None";
  95. string strAccessConnVMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\V-Master.mdb;Mode=Share Deny None";
  96. OleDbConnection accessConnEMASTER = null;
  97. OleDbConnection accessConnBELMASTER = null;
  98. OleDbConnection accessConnMGMASTER = null;
  99. OleDbConnection accessConnVMASTER = null;
  100. OleDbConnection tempConn = null;
  101. string obCondition;
  102. public MainWindow()
  103. {
  104. InitializeComponent();
  105. //dw = new Debug();
  106. //dw.Show();
  107. Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
  108. //Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
  109. //Thread.CurrentThread.CurrentCulture = ci;
  110. //OBInterface obInterface = new OBInterface(comport);
  111. /*
  112. _debugWindow = new Debug();
  113. _debugWindow.Topmost = true;
  114. _debugWindow.Show();
  115. */
  116. // comment for testing
  117. LoginWindow loginWindow = new LoginWindow();
  118. var r = loginWindow.ShowDialog();
  119. if (r == false)
  120. return;
  121. //this.Hide();
  122. //loginWindow.Topmost = true;
  123. initSys();
  124. //forTesting();
  125. //for old ob box
  126. //_aThread = new Thread(new ThreadStart(Sender));
  127. //no need for mitutoyo
  128. // _aThread = new Thread(new ThreadStart(Sender2));
  129. // _aThread.Start();
  130. //DispatcherTimer _timer = new DispatcherTimer();
  131. lotNo.Focus();
  132. }
  133. public void ResetHeaderUsage()
  134. {
  135. _isOver = false;
  136. if (header == "OB")
  137. {
  138. _obCount = 0;
  139. }
  140. else if (header == "OC")
  141. {
  142. _ocCount = 0;
  143. }
  144. else if (header == "RH")
  145. {
  146. _rhCount = 0;
  147. }
  148. }
  149. public void Sender2()
  150. {
  151. while (comport.IsOpen && _clearThread == false)
  152. {
  153. //Console.WriteLine("Hello");
  154. //string readCommand = String.Format("{0}{1}{2}{3}",0x002, 0x052, 0x031, 0x00D);
  155. string readCommand = encAscii.GetString(new byte[] { 0x02, 0x52, 0x31, 0x0D });
  156. if (_canSent == true)
  157. {
  158. try
  159. {
  160. comport.Write(readCommand);
  161. Thread.Sleep(500);
  162. }
  163. catch
  164. {
  165. Thread.Sleep(1000);
  166. }
  167. }
  168. /*
  169. if (!_debugWindow.Dispatcher.CheckAccess())
  170. {
  171. _debugWindow.Dispatcher.Invoke(
  172. System.Windows.Threading.DispatcherPriority.Normal,
  173. new Action(
  174. delegate()
  175. {
  176. _debugWindow.debugTextBox.AppendText("Sending\n");
  177. }
  178. ));
  179. }
  180. else
  181. {
  182. _debugWindow.debugTextBox.AppendText("Sending\n");
  183. }*/
  184. }
  185. }
  186. public void Sender()
  187. {
  188. while (comport.IsOpen && _clearThread == false)
  189. {
  190. //Console.WriteLine("Hello");
  191. comport.Write("S");
  192. Thread.Sleep(500);
  193. /*
  194. if (!_debugWindow.Dispatcher.CheckAccess())
  195. {
  196. _debugWindow.Dispatcher.Invoke(
  197. System.Windows.Threading.DispatcherPriority.Normal,
  198. new Action(
  199. delegate()
  200. {
  201. _debugWindow.debugTextBox.AppendText("Sending\n");
  202. }
  203. ));
  204. }
  205. else
  206. {
  207. _debugWindow.debugTextBox.AppendText("Sending\n");
  208. }*/
  209. }
  210. }
  211. public void AutoSaveData()
  212. {
  213. //Thread.Sleep(1500);
  214. if (_prevValue == null)
  215. {
  216. _prevValue = _currentValue;
  217. }
  218. TimeSpan ts = DateTime.Now - _lastTimeDataPort;
  219. //if (ts.Seconds >= 1 && _lastTimeDataPort != DateTime.MinValue)
  220. if (_lastTimeDataPort != DateTime.MinValue)
  221. {
  222. _lastTimeDataPort = DateTime.MinValue;
  223. if (_prevValue == _currentValue)
  224. {
  225. saveCellBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, saveCellBtn));
  226. }
  227. else
  228. {
  229. _prevValue = null;
  230. }
  231. }
  232. }
  233. private void forTesting()
  234. {
  235. var r = GetRecordType("114-78469F");
  236. Console.WriteLine(r);
  237. }
  238. private void initSys()
  239. {
  240. initDatabaseConnection();
  241. initCOMPort();
  242. //initMachineList();
  243. SqlDataReader reader = Utils.Query(proConn, "select * from sys_configs");
  244. string title;
  245. resetMenu();
  246. while (reader.Read())
  247. {
  248. title = reader["title"].ToString();
  249. //value = reader["value"];
  250. switch (title)
  251. {
  252. case "ob_limit":
  253. _obLimit = Convert.ToInt32(reader["value"]);
  254. break;
  255. case "oc_limit":
  256. _ocLimit = Convert.ToInt32(reader["value"]);
  257. break;
  258. case "rh_limit":
  259. _rhLimit = Convert.ToInt32(reader["value"]);
  260. break;
  261. default:
  262. //MessageBox.Show("Bad config variable :"+title);
  263. break;
  264. }
  265. }
  266. reader.Close();
  267. }
  268. private void resetMenu()
  269. {
  270. if (GlobalVars.user.empid == "root" ||
  271. GlobalVars.user.roles.Find(
  272. delegate(string s)
  273. {
  274. return s == "admin";
  275. }) != null)
  276. {
  277. configMenu.Visibility = Visibility.Visible;
  278. }
  279. else
  280. {
  281. configMenu.Visibility = Visibility.Collapsed;
  282. }
  283. }
  284. public void setFilterLogData(string q)
  285. {
  286. _isExisting = true;
  287. this._updated_at = q;
  288. }
  289. private List<string> GetRecordType(string pro2)
  290. {
  291. foreach (var view in masViews)
  292. {
  293. SqlCommand cmd = proConn.CreateCommand();
  294. string sql = @"
  295. select * from [" + view + "] v where v.PRO2='" + pro2 + "'";
  296. cmd.CommandText = sql;
  297. //Console.WriteLine(sql);
  298. SqlDataReader reader = cmd.ExecuteReader();
  299. if (!reader.HasRows)
  300. {
  301. reader.Close();
  302. continue;
  303. }
  304. bool hasIn, hasOut;
  305. while (reader.Read())
  306. {
  307. var mi17 = reader["MI17"].ToString();
  308. if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
  309. {
  310. hasOut = false;
  311. }
  312. else
  313. {
  314. hasOut = true;
  315. }
  316. string mi21 = reader["MI21"].ToString();
  317. if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
  318. {
  319. hasIn = false;
  320. }
  321. else
  322. {
  323. hasIn = true;
  324. }
  325. List<string> rList = new List<string>();
  326. if (_isTkx == true)
  327. {
  328. rList.Add("FA1");
  329. rList.Add("FA2");
  330. //rList.Add("MID");
  331. //rList.Add("IN*");
  332. reader.Close();
  333. point1Label.Content = "FA";
  334. point2Label.Content = "None";
  335. return rList;
  336. }
  337. if (view == "bel_master_view" || view == "e_master_view" || view == "mg_master_view")
  338. {
  339. if (reader["MP45"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP45"].ToString().Trim()))
  340. {
  341. rList.Add(reader["MP45"].ToString().ToUpper());
  342. }
  343. point1Label.Content = reader["MP45"].ToString().ToUpper();
  344. //rList.Add("MID");
  345. //rList.Add("IN*");
  346. if (reader["MP49"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP49"].ToString().Trim()))
  347. {
  348. rList.Add(reader["MP49"].ToString().ToUpper());
  349. point2Label.Content = reader["MP49"].ToString().ToUpper();
  350. }
  351. else
  352. {
  353. if (hasIn == true)
  354. {
  355. var side = reader["MP45"].ToString().ToLower();
  356. rList.Add(_sideMap[side].ToUpper());
  357. point2Label.Content = _sideMap[side].ToUpper();
  358. }
  359. }
  360. reader.Close();
  361. return rList;
  362. }
  363. else
  364. {
  365. if (reader["MP34"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP34"].ToString().Trim()))
  366. {
  367. rList.Add(reader["MP34"].ToString().ToUpper());
  368. }
  369. point1Label.Content = reader["MP34"].ToString().ToUpper();
  370. //rList.Add("MID");
  371. //rList.Add("IN*");
  372. if (reader["MP39"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP39"].ToString().Trim()))
  373. {
  374. rList.Add(reader["MP39"].ToString().ToUpper());
  375. point2Label.Content = reader["MP39"].ToString().ToUpper();
  376. }
  377. else
  378. {
  379. if (hasIn == true)
  380. {
  381. var side = reader["MP34"].ToString().ToLower();
  382. rList.Add(_sideMap[side].ToUpper());
  383. point2Label.Content = _sideMap[side].ToUpper();
  384. }
  385. }
  386. reader.Close();
  387. return rList;
  388. }
  389. }
  390. }
  391. return null;
  392. }
  393. //for old ob box
  394. void DataReceivedHandler(
  395. object sender,
  396. SerialDataReceivedEventArgs e)
  397. {
  398. SerialPort sp = (SerialPort)sender;
  399. byte[] data = new byte[2];
  400. data[0] = (byte)sp.ReadByte();
  401. data[1] = (byte)sp.ReadByte();
  402. //byte[] data = new byte[2];
  403. //int nByteRead = sp.Read(data, 0, 2);
  404. _lastTimeDataPort = DateTime.Now;
  405. byte[] bcddata = new byte[4];
  406. byte anddata = 240;
  407. byte tempdata;
  408. if (_pattern == 1)
  409. {
  410. anddata = (byte)240;
  411. bcddata[1] = (byte)(data[0] & anddata);
  412. bcddata[1] = (byte)(bcddata[1] >> 4);
  413. bcddata[3] = (byte)(data[1] & anddata);
  414. bcddata[3] = (byte)(bcddata[3] >> 4);
  415. anddata = (byte)1;
  416. bcddata[0] = (byte)(data[0] & (byte)anddata);
  417. anddata = (byte)15;
  418. bcddata[2] = (byte)(data[1] & (byte)anddata);
  419. tempdata = bcddata[3];
  420. bcddata[3] = (byte)(tempdata & (byte)1);
  421. bcddata[3] = (byte)(bcddata[3] << 1);
  422. tempdata = (byte)(tempdata >> 1);
  423. bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
  424. bcddata[3] = (byte)(bcddata[3] << 1);
  425. tempdata = (byte)(tempdata >> 1);
  426. bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
  427. bcddata[3] = (byte)(bcddata[3] << 1);
  428. tempdata = (byte)(tempdata >> 1);
  429. bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
  430. tempdata = bcddata[2];
  431. bcddata[2] = (byte)(tempdata & (byte)1);
  432. bcddata[2] = (byte)(bcddata[2] << 1);
  433. tempdata = (byte)(tempdata >> 1);
  434. bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
  435. bcddata[2] = (byte)(bcddata[2] << 1);
  436. tempdata = (byte)(tempdata >> 1);
  437. bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
  438. bcddata[2] = (byte)(bcddata[2] << 1);
  439. tempdata = (byte)(tempdata >> 1);
  440. bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
  441. }
  442. else
  443. {
  444. anddata = (byte)240;
  445. bcddata[1] = (byte)(data[0] & anddata);
  446. bcddata[1] = (byte)(bcddata[1] >> 4);
  447. bcddata[3] = (byte)(data[1] & anddata);
  448. bcddata[3] = (byte)(bcddata[3] >> 4);
  449. anddata = (byte)1;
  450. bcddata[0] = (byte)(data[0] & anddata);
  451. anddata = (byte)15;
  452. bcddata[2] = (byte)(data[1] & anddata);
  453. }
  454. Console.WriteLine("Data Received: {0}", data.Length);
  455. foreach (byte element in data)
  456. {
  457. Console.WriteLine("{0} = {1}", element, (char)element);
  458. }
  459. foreach (byte element in bcddata)
  460. {
  461. Console.WriteLine("oo {0} = {1}", element, element);
  462. }
  463. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  464. string outputString = string.Format("{0}.{1}{2}", bcddata[1], bcddata[2], bcddata[3]);
  465. //_currentValue = outputString;
  466. //_currentValue = outputString;
  467. if (!readingBox.Dispatcher.CheckAccess())
  468. {
  469. readingBox.Dispatcher.Invoke(
  470. System.Windows.Threading.DispatcherPriority.Normal,
  471. new Action(
  472. delegate()
  473. {
  474. readingBox.Text = outputString;
  475. if (_dc != null)
  476. {
  477. _dc.measureBlock.Text = outputString;
  478. }
  479. if(_rlWindow != null)
  480. {
  481. _rlWindow.readingBox.Text = outputString;
  482. }
  483. //_dc.measureBlock.Text = outputString;
  484. }
  485. ));
  486. }
  487. //readingBox.Text = outputString;
  488. }
  489. //for new ob box
  490. void DataReceivedHandler2(
  491. object sender,
  492. SerialDataReceivedEventArgs e)
  493. {
  494. _canSent = false;
  495. SerialPort sp = (SerialPort)sender;
  496. byte[] data = new byte[11];
  497. bool readError = false;
  498. for (int i = 0; i < 11; i++)
  499. {
  500. try
  501. {
  502. data[i] = (byte)sp.ReadByte();
  503. }
  504. catch
  505. {
  506. readError = true;
  507. break;
  508. }
  509. }
  510. Console.WriteLine(data);
  511. //data[0] = (byte)sp.ReadByte();
  512. //data[1] = (byte)sp.ReadByte();
  513. if (readError == true)
  514. return;
  515. //byte[] data = new byte[2];
  516. //int nByteRead = sp.Read(data, 0, 2);
  517. _lastTimeDataPort = DateTime.Now;
  518. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  519. //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
  520. string outputString = encAscii.GetString(new byte[] { data[3], data[4], data[5], data[6], data[7] });
  521. //_currentValue = outputString;
  522. //_currentValue = outputString;
  523. if (!readingBox.Dispatcher.CheckAccess())
  524. {
  525. readingBox.Dispatcher.Invoke(
  526. System.Windows.Threading.DispatcherPriority.Normal,
  527. new Action(
  528. delegate()
  529. {
  530. if (data[9] == '1')
  531. {
  532. readingBox.Text = "Error";
  533. }
  534. else
  535. {
  536. readingBox.Text = outputString;
  537. }
  538. if (_dc != null)
  539. {
  540. _dc.measureBlock.Text = outputString;
  541. }
  542. //_dc.measureBlock.Text = outputString;
  543. }
  544. ));
  545. }
  546. _canSent = true;
  547. //readingBox.Text = outputString;
  548. }
  549. void DataReceivedHandler3(
  550. object sender,
  551. SerialDataReceivedEventArgs e)
  552. {
  553. _canSent = false;
  554. Console.WriteLine("data rec = "+e.ToString());
  555. SerialPort sp = (SerialPort)sender;
  556. int nByte = 40;
  557. byte[] data = new byte[nByte];
  558. Console.WriteLine("Handler3");
  559. bool readError = false;
  560. //Console.WriteLine("Front mit "+ sp.ReadLine());
  561. var temp = sp.ReadLine();
  562. //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
  563. //return;
  564. for (int i = 0; i < temp.Length; i++)
  565. {
  566. //Console.WriteLine(sp.ReadByte().ToString());
  567. //data[i] = (byte)sp.ReadByte();
  568. data[i] = (byte)temp[i];
  569. Console.WriteLine(data[i]);
  570. }
  571. //data[0] = (byte)sp.ReadByte();
  572. //data[1] = (byte)sp.ReadByte();
  573. //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
  574. if (readError == true)
  575. return;
  576. //byte[] data = new byte[2];
  577. //int nByteRead = sp.Read(data, 0, 2);
  578. _lastTimeDataPort = DateTime.Now;
  579. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  580. //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
  581. string outputString = encAscii.GetString(new byte[] { data[5], data[6], data[7], data[8], data[9], data[10], data[11] });
  582. //_currentValue = outputString;
  583. //_currentValue = outputString;
  584. if (!readingBox.Dispatcher.CheckAccess())
  585. {
  586. readingBox.Dispatcher.Invoke(
  587. System.Windows.Threading.DispatcherPriority.Normal,
  588. new Action(
  589. delegate()
  590. {
  591. //if (data[9] == '1')
  592. //{
  593. // readingBox.Text = "Error";
  594. //}
  595. //else
  596. //{
  597. readingBox.Text = outputString;
  598. //}
  599. if (_dc != null)
  600. {
  601. _dc.measureBlock.Text = outputString;
  602. }
  603. if (_rlWindow != null)
  604. {
  605. _rlWindow.readingBox.Text = outputString;
  606. }
  607. //_dc.measureBlock.Text = outputString;
  608. }
  609. ));
  610. }
  611. _canSent = true;
  612. //readingBox.Text = outputString;
  613. //Console.WriteLine("port data " + temp);
  614. }
  615. //for temporary rh2
  616. void DataReceivedHandler5(
  617. object sender,
  618. SerialDataReceivedEventArgs e)
  619. {
  620. _canSent = false;
  621. Console.WriteLine("data rec = " + e.ToString());
  622. SerialPort sp = (SerialPort)sender;
  623. int nByte = 40;
  624. byte[] data = new byte[nByte];
  625. Console.WriteLine("Handler3");
  626. bool readError = false;
  627. //Console.WriteLine("Front mit "+ sp.ReadLine());
  628. var temp = sp.ReadLine();
  629. //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
  630. //return;
  631. //data[0] = (byte)sp.ReadByte();
  632. //data[1] = (byte)sp.ReadByte();
  633. //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
  634. if (readError == true)
  635. return;
  636. //byte[] data = new byte[2];
  637. //int nByteRead = sp.Read(data, 0, 2);
  638. _lastTimeDataPort = DateTime.Now;
  639. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  640. //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
  641. string outputString = temp.Substring(7, 5).Trim();
  642. float o = float.Parse(outputString, CultureInfo.InvariantCulture.NumberFormat);
  643. string rawString = o.ToString("0.##");
  644. o = o - 70;
  645. outputString = o.ToString("0.##");
  646. //_currentValue = outputString;
  647. //_currentValue = outputString;
  648. if (!readingBox.Dispatcher.CheckAccess())
  649. {
  650. readingBox.Dispatcher.Invoke(
  651. System.Windows.Threading.DispatcherPriority.Normal,
  652. new Action(
  653. delegate ()
  654. {
  655. //if (data[9] == '1')
  656. //{
  657. // readingBox.Text = "Error";
  658. //}
  659. //else
  660. //{
  661. readingBox.Text = outputString;
  662. processedBox.Text = rawString;
  663. //}
  664. if (_dc != null)
  665. {
  666. _dc.measureBlock.Text = outputString;
  667. }
  668. if (_rlWindow != null)
  669. {
  670. _rlWindow.readingBox.Text = outputString;
  671. }
  672. //_dc.measureBlock.Text = outputString;
  673. }
  674. ));
  675. }
  676. _canSent = true;
  677. //readingBox.Text = outputString;
  678. //Console.WriteLine("port data " + temp);
  679. }
  680. //new HRH
  681. void DataReceivedHandler6(
  682. object sender,
  683. SerialDataReceivedEventArgs e)
  684. {
  685. _canSent = false;
  686. Console.WriteLine("data rec = " + e.ToString());
  687. SerialPort sp = (SerialPort)sender;
  688. int nByte = 40;
  689. byte[] data = new byte[nByte];
  690. Console.WriteLine("Handler6");
  691. bool readError = false;
  692. //Console.WriteLine("Front mit "+ sp.ReadLine());
  693. var temp = sp.ReadLine();
  694. //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
  695. //return;
  696. //data[0] = (byte)sp.ReadByte();
  697. //data[1] = (byte)sp.ReadByte();
  698. //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
  699. if (readError == true)
  700. return;
  701. //byte[] data = new byte[2];
  702. //int nByteRead = sp.Read(data, 0, 2);
  703. _lastTimeDataPort = DateTime.Now;
  704. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  705. //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
  706. //string outputString = temp.Substring(8, 4).Trim();
  707. string outputString = temp.Substring(6, 6).Trim().Replace(" ", "");
  708. float o = float.Parse(outputString, CultureInfo.InvariantCulture.NumberFormat);
  709. string rawString = o.ToString("0.##");
  710. //o = o - 70;
  711. outputString = o.ToString("0.##");
  712. //_currentValue = outputString;
  713. //_currentValue = outputString;
  714. if (!readingBox.Dispatcher.CheckAccess())
  715. {
  716. readingBox.Dispatcher.Invoke(
  717. System.Windows.Threading.DispatcherPriority.Normal,
  718. new Action(
  719. delegate ()
  720. {
  721. //if (data[9] == '1')
  722. //{
  723. // readingBox.Text = "Error";
  724. //}
  725. //else
  726. //{
  727. readingBox.Text = outputString;
  728. processedBox.Text = rawString;
  729. //}
  730. if (_dc != null)
  731. {
  732. _dc.measureBlock.Text = outputString;
  733. }
  734. if (_rlWindow != null)
  735. {
  736. _rlWindow.readingBox.Text = outputString;
  737. }
  738. //_dc.measureBlock.Text = outputString;
  739. }
  740. ));
  741. }
  742. _canSent = true;
  743. //readingBox.Text = outputString;
  744. //Console.WriteLine("port data " + temp);
  745. }
  746. // rh3
  747. void DataReceivedHandler4(
  748. object sender,
  749. SerialDataReceivedEventArgs e)
  750. {
  751. _canSent = false;
  752. Console.WriteLine("data rec = " + e.ToString());
  753. SerialPort sp = (SerialPort)sender;
  754. byte[] data = new byte[54];
  755. Console.WriteLine("Handler3");
  756. bool readError = false;
  757. //Console.WriteLine("Front mit "+ sp.ReadLine());
  758. var temp = sp.ReadLine();
  759. //var temp = sp.ReadLine();
  760. Console.WriteLine("data from machine :" + temp);
  761. if (temp == "\r" || (temp.IndexOf("Dbar") != -1) || temp[0] == '-')
  762. return;
  763. for (int i = 0; i < 54; i++)
  764. {
  765. //Console.WriteLine(sp.ReadByte().ToString());
  766. //data[i] = (byte)sp.ReadByte();
  767. data[i] = (byte)temp[i];
  768. Console.WriteLine(data[i]);
  769. }
  770. //data[0] = (byte)sp.ReadByte();
  771. //data[1] = (byte)sp.ReadByte();
  772. //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
  773. if (readError == true)
  774. return;
  775. //byte[] data = new byte[2];
  776. //int nByteRead = sp.Read(data, 0, 2);
  777. _lastTimeDataPort = DateTime.Now;
  778. //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
  779. //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
  780. string outputString = encAscii.GetString(new byte[] { data[16], data[17], data[18], data[19], data[20] });
  781. //_currentValue = outputString;
  782. //_currentValue = outputString;
  783. if (!readingBox.Dispatcher.CheckAccess())
  784. {
  785. readingBox.Dispatcher.Invoke(
  786. System.Windows.Threading.DispatcherPriority.Normal,
  787. new Action(
  788. delegate ()
  789. {
  790. //if (data[9] == '1')
  791. //{
  792. // readingBox.Text = "Error";
  793. //}
  794. //else
  795. //{
  796. readingBox.Text = outputString;
  797. //}
  798. if (_dc != null)
  799. {
  800. _dc.measureBlock.Text = outputString;
  801. }
  802. if (_rlWindow != null)
  803. {
  804. _rlWindow.readingBox.Text = outputString;
  805. }
  806. //_dc.measureBlock.Text = outputString;
  807. }
  808. ));
  809. }
  810. _canSent = true;
  811. //readingBox.Text = outputString;
  812. //Console.WriteLine("port data " + temp);
  813. }
  814. void DataErrorHandler3(
  815. object sender,
  816. SerialErrorReceivedEventArgs e)
  817. {
  818. Console.WriteLine("data error "+e.ToString());
  819. }
  820. private void initCOMPort()
  821. {
  822. Console.WriteLine("Comport is Call");
  823. if (comport.IsOpen)
  824. comport.Close();
  825. //else
  826. //{
  827. comport.PortName = Utils.getSetting("machinePort");
  828. /*
  829. comport.BaudRate = int.Parse(Utils.getSetting("baudRate"));
  830. comport.DataBits = int.Parse(Utils.getSetting("dataBits"));
  831. comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Utils.getSetting("stopBits"));
  832. comport.Parity = (Parity)Enum.Parse(typeof(Parity), Utils.getSetting("parity"));
  833. */
  834. // for old ob box version
  835. //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
  836. comport.StopBits = StopBits.Two;
  837. Console.WriteLine("Comport data "+comport.BaudRate+" "+comport.PortName+ " "+comport.Parity+ " "+comport.DataBits+" "+comport.StopBits);
  838. //rh 2
  839. //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler3);
  840. //rh2 temporary measurement
  841. //# 1: 129.9 HRH Tol:HI
  842. //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler5);
  843. comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler6);
  844. //rh 3 maybe
  845. //handler 2 for ob3
  846. //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler4);
  847. //comport.ErrorReceived += new SerialErrorReceivedEventHandler(DataErrorHandler3);
  848. //comport.ErrorReceived += new SerialErrorReceivedEventHandler(DataErrorHandler3);
  849. bool error = false;
  850. try
  851. {
  852. comport.RtsEnable = true;
  853. comport.DtrEnable = true;
  854. Console.WriteLine("Openning Comport");
  855. comport.Open();
  856. if (comport.IsOpen == true)
  857. {
  858. Console.WriteLine("Open .. Done ");
  859. }
  860. //Thread.Sleep(1000);
  861. //comport.Close();
  862. //MessageBox.Show("Open Port Success");
  863. }
  864. catch (UnauthorizedAccessException) { error = true; }
  865. catch (IOException) { error = true; }
  866. catch (ArgumentException) { error = true; }
  867. if (error)
  868. {
  869. MessageBox.Show("Open Port Fail");
  870. }
  871. //}
  872. }
  873. private void initDatabaseConnection()
  874. {
  875. try
  876. {
  877. _opConn = Utils.createSqlCeConnection("operatingDbCS");
  878. // Sample usage
  879. /*
  880. SqlCeDataReader reader;
  881. reader = Utils.Query(_opConn, "select * from UsingTime");
  882. while(reader.Read()){
  883. Console.WriteLine("hello");
  884. }
  885. reader.Close();
  886. */
  887. }
  888. catch (SqlCeException se)
  889. {
  890. MessageBox.Show("operatingDbCS : ", se.Message);
  891. }
  892. /*
  893. try
  894. {
  895. configConn = Utils.createSqlConnection("configDbCS");
  896. }
  897. catch (SqlException se)
  898. {
  899. MessageBox.Show("configDbCS : ", se.Message);
  900. }
  901. try
  902. {
  903. masterConn = Utils.createSqlConnection("masterDbCS");
  904. }
  905. catch (SqlException se)
  906. {
  907. MessageBox.Show("masterDbCS : ", se.Message);
  908. }
  909. try
  910. {
  911. transConn = Utils.createSqlConnection("tranDbCS");
  912. }
  913. catch (SqlException se)
  914. {
  915. MessageBox.Show("tranDbCS : ", se.Message);
  916. }
  917. */
  918. try
  919. {
  920. proConn = Utils.createSqlConnection("productionDbCS");
  921. transConn = Utils.createSqlConnection("productionDbCS");
  922. masterConn = Utils.createSqlConnection("productionDbCS");
  923. configConn = Utils.createSqlConnection("productionDbCS");
  924. }
  925. catch (SqlException se)
  926. {
  927. MessageBox.Show("productionDbCS : ", se.Message);
  928. }
  929. //mod: change config by move every table alias
  930. //transConn = masterConn = configConn = proConn;
  931. /*
  932. try
  933. {
  934. accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
  935. accessConnEMASTER.Open();
  936. }
  937. catch (Exception ex)
  938. {
  939. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  940. }
  941. try
  942. {
  943. accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
  944. accessConnBELMASTER.Open();
  945. }
  946. catch (Exception ex)
  947. {
  948. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  949. }
  950. try
  951. {
  952. accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
  953. accessConnMGMASTER.Open();
  954. }
  955. catch (Exception ex)
  956. {
  957. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  958. }
  959. try
  960. {
  961. accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
  962. accessConnVMASTER.Open();
  963. }
  964. catch (Exception ex)
  965. {
  966. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  967. }*/
  968. }
  969. private void testDB()
  970. {
  971. /*
  972. string server = Utils.getSetting("dbServer");
  973. string user = Utils.getSetting("dbUser");
  974. string passwd = Utils.getSetting("dbPassword");
  975. string dbName = Utils.getSetting("dbName");
  976. var connectionString = "Data Source=" + server + ";User ID=" + user + ";Password=" + passwd + "; Initial Catalog=" + dbName;
  977. Console.WriteLine("cs = {0}", connectionString);
  978. SqlConnection sqlConnection = new SqlConnection(connectionString);
  979. SqlCommand catCMD = sqlConnection.CreateCommand();
  980. catCMD.CommandText = "SELECT count(*) as c FROM [V-MAS-3]";
  981. sqlConnection.Open();
  982. reader = catCMD.ExecuteReader();
  983. while (reader.Read())
  984. {
  985. Console.WriteLine("{0}", reader["c"]);
  986. }
  987. reader.Close();
  988. */
  989. }
  990. private void MenuItem_Click(object sender, RoutedEventArgs e)
  991. {
  992. Settings w = new Settings();
  993. w.Show();
  994. }
  995. private void closeWindows(object sender, EventArgs e)
  996. {
  997. //sqlConnection.Close();
  998. //_aThread.Join();
  999. // comport.Close();
  1000. //_clearThread = true;
  1001. //_debugWindow.Close();
  1002. //_bThread.Abort();
  1003. //dw.Close();
  1004. }
  1005. private void button1_Click(object sender, RoutedEventArgs e)
  1006. {
  1007. testDB();
  1008. }
  1009. private bool isAlreadyCheck(string ln)
  1010. {
  1011. SqlCommand catCMD = proConn.CreateCommand();
  1012. string sql = @"SELECT * FROM lot_summary where lot_no = '" + ln + "'";
  1013. catCMD.CommandText = sql;
  1014. SqlDataReader reader = catCMD.ExecuteReader();
  1015. bool r = reader.HasRows;
  1016. reader.Close();
  1017. return r;
  1018. }
  1019. private void find_Click(object sender, RoutedEventArgs e)
  1020. {
  1021. string ln = lotNo.Text;
  1022. _startUsing = DateTime.Now;
  1023. bool isFound = false;
  1024. isMiddle = _isIn = false;
  1025. _isExisting = false;
  1026. _isCheck = false;
  1027. _isTkx = false;
  1028. midGS = "";
  1029. inStarGS = "";
  1030. measureGrid.ItemsSource = null;
  1031. measureGrid.Items.Clear();
  1032. nextCol = 3;
  1033. middleText.Text = "Add Middle";
  1034. inText.Text = "Add IN*";
  1035. foreach (var view in masViews)
  1036. {
  1037. isFound = fillProData(ln, view);
  1038. if (isFound == true)
  1039. break;
  1040. }
  1041. if (isFound == false)
  1042. {
  1043. MessageBox.Show("Lot No.:" + ln + " Not Founded");
  1044. return;
  1045. }
  1046. mps = new ObservableCollection<MeasurePoint>();
  1047. list = GetRecordType(ln);
  1048. if (list.Count == 0)
  1049. {
  1050. list.Add("OUT");
  1051. list.Add("IN");
  1052. point1Label.Content = "OUT";
  1053. point2Label.Content = "IN";
  1054. }
  1055. if (isAlreadyCheck(ln))
  1056. {
  1057. //ChooseRecord cr = new ChooseRecord(ln);
  1058. //cr.ShowDialog();
  1059. _isCheck = true;
  1060. ChooseRecord2 cr = new ChooseRecord2(ln);
  1061. cr.ShowDialog();
  1062. SqlDataReader reader = Utils.Query(proConn, "select * from data where lot_no = '" + ln + "' and updated_at = '" + this._updated_at + "' order by id");
  1063. isMiddle = false;
  1064. _haveMiddle = false;
  1065. while (reader.Read())
  1066. {
  1067. var mp = new MeasurePoint();
  1068. nextCol = Convert.ToInt32(reader["ndata"]);
  1069. mp.Count = Convert.ToInt16(reader["row_no"]);
  1070. mp.Type = reader["r_type"].ToString();
  1071. if (mp.Type == "MID")
  1072. {
  1073. isMiddle = true;
  1074. _haveMiddle = true;
  1075. middleText.Text = "Remove Middle";
  1076. }
  1077. mp.SubOrder = Convert.ToInt16(reader["sub_order"]);
  1078. mp.P1 = Math.Round(Convert.ToDouble(reader["p1"]), 2);
  1079. mp.P2 = Math.Round(Convert.ToDouble(reader["p2"]), 2);
  1080. mp.P3 = Math.Round(Convert.ToDouble(reader["p3"]), 2);
  1081. mp.P4 = Math.Round(Convert.ToDouble(reader["p4"]), 2);
  1082. mp.P5 = Math.Round(Convert.ToDouble(reader["p5"]), 2);
  1083. mp.P6 = Math.Round(Convert.ToDouble(reader["p6"]), 2);
  1084. mp.P7 = Math.Round(Convert.ToDouble(reader["p7"]), 2);
  1085. mp.P8 = Math.Round(Convert.ToDouble(reader["p8"]), 2);
  1086. mp.P9 = Math.Round(Convert.ToDouble(reader["p9"]), 2);
  1087. mp.P10 = Math.Round(Convert.ToDouble(reader["p10"]), 2);
  1088. mp.Avg = Math.Round(Convert.ToDouble(reader["avg"]), 2);
  1089. mp.Grade = reader["grade"].ToString();
  1090. mp.ResultGrade = reader["rgrade"].ToString();
  1091. mp.Type = reader["r_type"].ToString();
  1092. mps.Add(mp);
  1093. // if row['sub_order'] == 1 and not have middle
  1094. //add dummy mid row
  1095. //if (Convert.ToInt32(reader["sub_order"]) == 1 && _haveMiddle == false)
  1096. // mps.Add(new MeasurePoint() { Count = mp.Count, Type = "MID", SubOrder = 2 });
  1097. }
  1098. reader.Close();
  1099. }
  1100. else
  1101. {
  1102. for (int i = 0; i < 3; i++)
  1103. {
  1104. int count = 1;
  1105. foreach (var l in list)
  1106. {
  1107. mps.Add(new MeasurePoint() { Count = i + 1, Type = l, SubOrder = count });
  1108. count++;
  1109. }
  1110. }
  1111. if (_isTkx == true)
  1112. {
  1113. measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;
  1114. }
  1115. }
  1116. measureGrid.ItemsSource = mps;
  1117. for (int i = 1; i < 10; i++)
  1118. {
  1119. measureGrid.Columns.ElementAt(i).Visibility = Visibility.Hidden;
  1120. }
  1121. for (int i = 1; i <= nextCol; i++)
  1122. {
  1123. measureGrid.Columns.ElementAt(i).Visibility = Visibility.Visible;
  1124. }
  1125. measureGrid.Focus();
  1126. try
  1127. {
  1128. measureGrid.SelectedItem = measureGrid.Items[0];
  1129. measureGrid.CurrentCell = new DataGridCellInfo(
  1130. measureGrid.Items[0], measureGrid.Columns[1]);
  1131. measureGrid.BeginEdit();
  1132. }
  1133. catch { }
  1134. }
  1135. private string getConditionRef(string id)
  1136. {
  1137. if (string.IsNullOrEmpty(id))
  1138. {
  1139. return "None";
  1140. }
  1141. SqlCommand cmd = configConn.CreateCommand();
  1142. string sql = $"select * from [TABLE_TI-T4] t4 where t4.TIT4 = '{id}'";
  1143. cmd.CommandText = sql;
  1144. Console.WriteLine(sql);
  1145. SqlDataReader reader = cmd.ExecuteReader();
  1146. string condition = "";
  1147. while (reader.Read())
  1148. {
  1149. condition = reader["TIT4NE"].ToString();
  1150. }
  1151. reader.Close();
  1152. return condition;
  1153. }
  1154. private bool fillProData(string ln, string viewName)
  1155. {
  1156. /*
  1157. join [V-MAS-3] v
  1158. on p.PRO1 = v.TC
  1159. left outer join [TABLE_TI-T4] t4
  1160. on v.MI5 = t4.TIT4
  1161. */
  1162. string sql = @"
  1163. SELECT * FROM " + viewName + " p " +
  1164. "where p.PRO2 = '" + ln + "'";
  1165. SqlDataReader reader = Utils.Query(proConn, sql);
  1166. string pro1 = "";
  1167. if (!reader.HasRows)
  1168. {
  1169. reader.Close();
  1170. return false;
  1171. }
  1172. while (reader.Read())
  1173. {
  1174. string[] t = reader["MC20"].ToString().Split('/');
  1175. string mc24 = reader["MC24"].ToString();
  1176. string kind = reader["PRO17"].ToString();
  1177. int gainSize;
  1178. try
  1179. {
  1180. gainSize = Convert.ToInt32(t[0]);
  1181. }
  1182. catch (FormatException fe)
  1183. {
  1184. gainSize = 0;
  1185. }
  1186. if (gainSize >= 10 && gainSize <= 100 && kind == "V")
  1187. header = "OB";
  1188. if (gainSize >= 120 && gainSize <= 220 && kind == "V")
  1189. header = "OC";
  1190. if (gainSize >= 10 && gainSize <= 100 && mc24 == "MG")
  1191. header = "OB";
  1192. if (gainSize >= 10 && gainSize <= 100 && kind == "B")
  1193. header = "OB";
  1194. if (gainSize > 220 && kind == "V")
  1195. header = "RH";
  1196. if (gainSize > 120 && kind == "B")
  1197. header = "RH";
  1198. if (headerLabel.Content != header)
  1199. {
  1200. MessageBox.Show("Please Change Using Header to '" + header + "'");
  1201. }
  1202. headerLabel.Content = header;
  1203. UsingTimeTB.Text = getUsingTime(header).ToString();
  1204. Console.WriteLine("{0}", reader["PRO2"]);
  1205. string codeString = reader["PRO1"].ToString();
  1206. string temp2 = codeString[0] + "-" + codeString.Substring(1, 4) + "-" + codeString.Substring(5, 4) + "-" + codeString.Substring(9, 1);
  1207. code.Text = temp2;
  1208. pro1 = reader["PRO1"].ToString();
  1209. customer.Text = reader["PRO1C"].ToString();
  1210. if (customer.Text.Trim().ToLower().StartsWith("tkx"))
  1211. {
  1212. _isTkx = true;
  1213. }
  1214. noProduct.Text = reader["PRO5"].ToString();
  1215. shape.Text = reader["PRO8"] + " " + reader["PRO9"];
  1216. size.Text = reader["PRO10"] + "x" + reader["PRO11"] + "x" + reader["PRO12"];
  1217. spec.Text = reader["PRO13"] + " " + reader["PRO14"] + " " + reader["PRO15"] + " " + reader["PRO16"]
  1218. + " " + reader["PRO17"] + " " + reader["PRO18"];
  1219. kind = reader["PRO17"] as string;
  1220. int mi13 = Convert.ToInt32(reader["MI13"]);
  1221. string samplingText = "";
  1222. if (mi13 == 1)
  1223. {
  1224. samplingText = "All";
  1225. }
  1226. else if (mi13 == 2)
  1227. {
  1228. samplingText = "2 Pcs";
  1229. }
  1230. else if (mi13 == 3)
  1231. {
  1232. samplingText = "3 Pcs";
  1233. }
  1234. else if (mi13 == 4 || mi13 == 5)
  1235. {
  1236. samplingText = "5 Pcs";
  1237. }
  1238. sampling.Text = samplingText;
  1239. double mi18 = Convert.ToDouble(reader["MI18"]);
  1240. double mi19 = Convert.ToDouble(reader["MI19"]);
  1241. //Console.WriteLine(mi18);
  1242. double o1, o2;
  1243. if (mi18 < mi19)
  1244. {
  1245. o1 = mi18;
  1246. o2 = mi19;
  1247. }
  1248. else
  1249. {
  1250. o1 = mi19;
  1251. o2 = mi18;
  1252. }
  1253. this.out0 = Math.Round(o1, 2);
  1254. this.out1 = Math.Round(o2, 2);
  1255. var mi16 = reader["MI16"].ToString();
  1256. sMi16 = reader["MI16"].ToString();
  1257. sMi16 = sMi16.Replace("\\", "");
  1258. Console.WriteLine("mi16 = " + sMi16);
  1259. //sMi20 = sMi20.Replace("\\", "");
  1260. var mi17 = reader["MI17"].ToString();
  1261. if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
  1262. {
  1263. mi17 = "None";
  1264. }
  1265. string temp = String.Format("{0:f} - {1:f} ({2}) {3}", o1, o2, mi16, mi17);
  1266. outTB.Text = temp;
  1267. _lower1 = o1;
  1268. _upper1 = o2;
  1269. double mi22 = Convert.ToDouble(reader["MI22"]);
  1270. double mi23 = Convert.ToDouble(reader["MI23"]);
  1271. var mi20 = reader["MI20"].ToString();
  1272. sMi20 = reader["MI20"].ToString();
  1273. sMi20 = sMi20.Replace("\\", "");
  1274. string mi21 = reader["MI21"].ToString();
  1275. if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
  1276. {
  1277. mi21 = "None";
  1278. }
  1279. //Console.WriteLine(mi18);
  1280. if (mi22 < mi23)
  1281. {
  1282. o1 = mi22;
  1283. o2 = mi23;
  1284. }
  1285. else
  1286. {
  1287. o1 = mi23;
  1288. o2 = mi22;
  1289. }
  1290. this.in0 = Math.Round(o1, 2);
  1291. this.in1 = Math.Round(o2, 2);
  1292. _lower2 = o1;
  1293. _upper2 = o2;
  1294. temp = String.Format("{0:f} - {1:f} ({2}) {3} ", o1, o2, mi20, mi21);
  1295. inTB.Text = temp;
  1296. point.Text = getConditionRef(reader["MI14"].ToString());
  1297. condition.Text = getConditionRef(reader["MI15"].ToString());
  1298. this.obCondition = reader["ob_condition"].ToString();
  1299. }
  1300. reader.Close();
  1301. reader = initAgreementList(ln, viewName, reader);
  1302. return true;
  1303. //return pro1;
  1304. }
  1305. private SqlDataReader initAgreementList(string ln, string viewName, SqlDataReader reader)
  1306. {
  1307. var sql2 = string.Format(@"select * from (
  1308. select MI53 as ag, PRO2 from {0}
  1309. union
  1310. select MI55 as ag, PRO2 from {0}
  1311. union
  1312. select MI31 as ag, PRO2 from {0}
  1313. union
  1314. select MI33 as ag, PRO2 from {0}
  1315. union
  1316. select INSAGM as ag, PRO2 from {0}
  1317. union
  1318. select MARAGM as ag, PRO2 from {0}
  1319. )x WHERE PRO2 = '{1}'", viewName, ln);
  1320. reader = Utils.Query(proConn, sql2);
  1321. //bool isHaveAgreement = false;
  1322. agreementCB.Items.Clear();
  1323. bool isHaveAgreement = false;
  1324. while (reader.Read())
  1325. {
  1326. //_agreementList.Add(reader["ag"].ToString());
  1327. var temp = reader["ag"].ToString();
  1328. //agreementCB.Text = "hello";
  1329. if (String.IsNullOrEmpty(temp) || temp == "NULL")
  1330. continue;
  1331. isHaveAgreement = true;
  1332. var list = temp.Split(new char[] { '/', ',', '\\' });
  1333. if (list.Length > 1)
  1334. {
  1335. foreach (var l in list)
  1336. {
  1337. if (l.Trim() != "")
  1338. {
  1339. agreementCB.Items.Add(new ComboBoxItem() { Content = l });
  1340. }
  1341. }
  1342. }
  1343. else
  1344. agreementCB.Items.Add(new ComboBoxItem() { Content = temp });
  1345. }
  1346. if (isHaveAgreement == true)
  1347. {
  1348. agreementBtn.IsEnabled = true;
  1349. agreementCB.IsEnabled = true;
  1350. agreementCB.SelectedIndex = 0;
  1351. }
  1352. else
  1353. {
  1354. agreementBtn.IsEnabled = false;
  1355. agreementCB.IsEnabled = false;
  1356. }
  1357. reader.Close();
  1358. return reader;
  1359. }
  1360. private int getUsingTime(string header)
  1361. {
  1362. var reader = Utils.Query(_opConn, "select * from UsingTime");
  1363. reader.Read();
  1364. int v = 0;
  1365. switch (header)
  1366. {
  1367. case "OB":
  1368. v = Convert.ToInt32(reader["ob"]);
  1369. _obCount = v;
  1370. _obLimit = Convert.ToInt32(reader["ob_limit"]);
  1371. break;
  1372. case "OC":
  1373. v = Convert.ToInt32(reader["oc"]);
  1374. _ocCount = v;
  1375. _ocLimit = Convert.ToInt32(reader["oc_limit"]);
  1376. break;
  1377. case "RH":
  1378. v = Convert.ToInt32(reader["rh"]);
  1379. _rhCount = v;
  1380. _rhLimit = Convert.ToInt32(reader["rh_limit"]);
  1381. break;
  1382. default:
  1383. MessageBox.Show("Bad Header Name");
  1384. break;
  1385. }
  1386. reader.Close();
  1387. return v;
  1388. }
  1389. /*
  1390. private void lotNo_TextChanged(object sender, TextChangedEventArgs e)
  1391. {
  1392. //var s = lotNo.Text;
  1393. //if(lotNo.Text.IndexOf('\n') != -1)
  1394. // find_Click(null, null);
  1395. }*/
  1396. private void openScreenKB(object sender, RoutedEventArgs e)
  1397. {
  1398. Console.WriteLine("Open KB");
  1399. }
  1400. private void lotNo_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  1401. {
  1402. }
  1403. private void openScreenKB(object sender, MouseButtonEventArgs e)
  1404. {
  1405. string windir = Environment.GetEnvironmentVariable("WINDIR");
  1406. string osk = null;
  1407. if (osk == null)
  1408. {
  1409. osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "sysnative"), "osk.exe");
  1410. if (!File.Exists(osk))
  1411. {
  1412. osk = null;
  1413. }
  1414. }
  1415. if (osk == null)
  1416. {
  1417. osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "system32"), "osk.exe");
  1418. if (!File.Exists(osk))
  1419. {
  1420. osk = null;
  1421. }
  1422. }
  1423. if (osk == null)
  1424. {
  1425. osk = "osk.exe";
  1426. }
  1427. Process.Start(osk);
  1428. }
  1429. private void addRow_Click(object sender, RoutedEventArgs e)
  1430. {
  1431. if (measureGrid.ItemsSource == null)
  1432. return;
  1433. _lastAction.Push("row");
  1434. MeasurePoint m = mps.Last();
  1435. int count = 1;
  1436. foreach (var l in list)
  1437. {
  1438. mps.Add(new MeasurePoint() { Count = m.Count + 1, Type = l, SubOrder = count });
  1439. count++;
  1440. }
  1441. }
  1442. private void addMeasureColumn_Click(object sender, RoutedEventArgs e)
  1443. {
  1444. _lastAction.Push("column");
  1445. if (nextCol <= 10)
  1446. {
  1447. measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;
  1448. foreach (var item in measureGrid.Items)
  1449. {
  1450. //Console.WriteLine(item);
  1451. MeasurePoint c = item as MeasurePoint;
  1452. c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
  1453. c.Avg = Math.Round(c.Avg, 2);
  1454. if (c.SubOrder == 1)
  1455. {
  1456. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  1457. }
  1458. else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
  1459. {
  1460. if (sMi20 != "0")
  1461. c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
  1462. else
  1463. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  1464. }
  1465. }
  1466. measureGrid.Items.Refresh();
  1467. }
  1468. }
  1469. private string computeGrade(string size, double lower, string kind, string defValue, string type)
  1470. {
  1471. SqlCommand cmd = configConn.CreateCommand();
  1472. if (type == "MID")
  1473. {
  1474. size = midGS;
  1475. }
  1476. else if (type == "IN*")
  1477. {
  1478. size = inStarGS;
  1479. }
  1480. int lotKind = 0;
  1481. if (code.Text[0] == '1' || code.Text[0] == '2' || code.Text[0] == '9')
  1482. {
  1483. lotKind = 1;
  1484. }
  1485. else if (code.Text[0] == '3' || code.Text[0] == '4' || code.Text[0] == '5')
  1486. {
  1487. lotKind = 2;
  1488. }
  1489. if (double.IsNaN(lower))
  1490. {
  1491. lower = 0;
  1492. }
  1493. string sql = "";
  1494. SqlDataReader reader;
  1495. string value;
  1496. if (lotKind == 1)
  1497. {
  1498. sql = string.Format(@"SELECT * FROM [TABLE_TI-T3] WHERE (TIT3R1 <= '{0}') AND (TIT3R2 >= '{0}') AND (round(TIT3U,2) <= '{1}') AND (round(TIT3D,2) >= '{2}')", size, lower, lower);
  1499. cmd.CommandText = sql;
  1500. reader = cmd.ExecuteReader();
  1501. value = defValue;
  1502. Console.WriteLine(sql);
  1503. while (reader.Read())
  1504. {
  1505. value = reader["TIT3G"].ToString();
  1506. break;
  1507. }
  1508. reader.Close();
  1509. return value;
  1510. }
  1511. else if (lotKind == 2)
  1512. {
  1513. sql = string.Format(@"SELECT * FROM [TABLE_TI-T3] WHERE (TIT3R1 <= '{0}') AND (TIT3R2 >= '{0}') AND (round(TIT3U,2) <= '{1}') AND (round(TIT3D,2) >= '{2}')", size, lower, lower);
  1514. cmd.CommandText = sql;
  1515. Console.WriteLine(sql);
  1516. //reader.Close();
  1517. reader = cmd.ExecuteReader();
  1518. value = defValue;
  1519. while (reader.Read())
  1520. {
  1521. value = reader["TIT3G"].ToString();
  1522. break;
  1523. }
  1524. reader.Close();
  1525. return value;
  1526. }
  1527. else
  1528. {
  1529. return "-";
  1530. }
  1531. //return value;
  1532. }
  1533. //int row;
  1534. private void measureGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
  1535. {
  1536. //MessageBox.Show("refresh");
  1537. int row = e.Row.GetIndex();
  1538. (sender as DataGrid).RowEditEnding -= measureGrid_RowEditEnding;
  1539. (sender as DataGrid).CommitEdit();
  1540. var c = mps[row];
  1541. computeValues(c, true);
  1542. measureGrid.Items.Refresh();
  1543. (sender as DataGrid).RowEditEnding += measureGrid_RowEditEnding;
  1544. }
  1545. private void computeValues(MeasurePoint c, bool isCompGrade = false)
  1546. {
  1547. c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P5 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
  1548. c.Avg = Math.Round(c.Avg, 2);
  1549. if (isCompGrade == true)
  1550. {
  1551. if (c.SubOrder == 1)
  1552. {
  1553. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  1554. }
  1555. else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
  1556. {
  1557. if (sMi20 != "0")
  1558. c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
  1559. else
  1560. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  1561. }
  1562. else if (c.Type == "MID" || c.Type == "IN*")
  1563. {
  1564. c.Grade = computeGrade("0", c.Avg, kind, "-", c.Type);
  1565. }
  1566. }
  1567. if (c.SubOrder == 1 || c.Type == "IN*" || c.Type == "MID" || c.Type == "FA1" || c.Type == "FA2")
  1568. {
  1569. if (this.header == "OB" || this.header == "OC")
  1570. {
  1571. if (c.Avg >= this.out0 && c.Avg <= this.out1)
  1572. {
  1573. c.ResultGrade = "OK";
  1574. }
  1575. else if (c.Avg < this.out0)
  1576. {
  1577. c.ResultGrade = "Hard";
  1578. }
  1579. else if (c.Avg > this.out1)
  1580. {
  1581. c.ResultGrade = "Soft";
  1582. }
  1583. }
  1584. else
  1585. {
  1586. if (c.Avg >= this.out0 && c.Avg <= this.out1)
  1587. {
  1588. c.ResultGrade = "OK";
  1589. }
  1590. else if (c.Avg < this.out0)
  1591. {
  1592. c.ResultGrade = "Soft";
  1593. }
  1594. else if (c.Avg > this.out1)
  1595. {
  1596. c.ResultGrade = "Hard";
  1597. }
  1598. }
  1599. }
  1600. else if (c.SubOrder != 1)
  1601. {
  1602. if (this.header == "OB" || this.header == "OC")
  1603. {
  1604. if (c.Avg >= this.in0 && c.Avg <= this.in1)
  1605. {
  1606. c.ResultGrade = "OK";
  1607. }
  1608. else if (c.Avg < this.in0)
  1609. {
  1610. c.ResultGrade = "Hard";
  1611. }
  1612. else if (c.Avg > this.in1)
  1613. {
  1614. c.ResultGrade = "Soft";
  1615. }
  1616. }
  1617. else
  1618. {
  1619. if (c.Avg >= this.in0 && c.Avg <= this.in1)
  1620. {
  1621. c.ResultGrade = "OK";
  1622. }
  1623. else if (c.Avg < this.in0)
  1624. {
  1625. c.ResultGrade = "Soft";
  1626. }
  1627. else if (c.Avg > this.in1)
  1628. {
  1629. c.ResultGrade = "Hard";
  1630. }
  1631. }
  1632. }
  1633. }
  1634. private void measureGrid_KeyUp(object sender, KeyEventArgs e)
  1635. {
  1636. Console.WriteLine("hello");
  1637. //MessageBox.Show(e.Key.ToString());
  1638. var info = measureGrid.CurrentColumn;
  1639. var item = measureGrid.CurrentItem as MeasurePoint;
  1640. int col = info.DisplayIndex;
  1641. var mp = (MeasurePoint)measureGrid.CurrentItem;
  1642. int row = mps.IndexOf(mp);
  1643. if (e.Key == Key.Tab)
  1644. {
  1645. //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
  1646. //MessageBox.Show("row " + item.Count.ToString());
  1647. //MessageBox.Show("row " + mps.IndexOf(mp).ToString());
  1648. //MessageBox.Show("col " + info.DisplayIndex.ToString());
  1649. if (col < nextCol)
  1650. {
  1651. measureGrid.CurrentCell = new DataGridCellInfo(
  1652. measureGrid.Items[row], measureGrid.Columns[col + 1]);
  1653. measureGrid.BeginEdit();
  1654. }
  1655. else
  1656. {
  1657. try
  1658. {
  1659. measureGrid.CurrentCell = new DataGridCellInfo(
  1660. measureGrid.Items[row + 1], measureGrid.Columns[1]);
  1661. measureGrid.BeginEdit();
  1662. }
  1663. catch
  1664. {
  1665. measureGrid.CurrentCell = new DataGridCellInfo(
  1666. measureGrid.Items[0], measureGrid.Columns[1]);
  1667. measureGrid.BeginEdit();
  1668. }
  1669. }
  1670. }
  1671. if (e.Key == Key.Return)
  1672. {
  1673. if (isMiddle == false)
  1674. row += 2;
  1675. if (row > measureGrid.Items.Count)
  1676. {
  1677. measureGrid.CurrentCell = new DataGridCellInfo(
  1678. measureGrid.Items[0], measureGrid.Columns[1]);
  1679. measureGrid.BeginEdit();
  1680. }
  1681. }
  1682. }
  1683. private void measureGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
  1684. {
  1685. /*
  1686. row = e.Row.GetIndex();
  1687. (sender as DataGrid).CellEditEnding -= measureGrid_CellEditEnding;
  1688. (sender as DataGrid).CommitEdit();
  1689. var c = mps[row];
  1690. c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol - 1);
  1691. c.Grade = computeGrade(sMi16, c.Avg, kind, "-");
  1692. (sender as DataGrid).CellEditEnding += measureGrid_CellEditEnding;
  1693. */
  1694. }
  1695. private void measureGrid_LostFocus(object sender, RoutedEventArgs e)
  1696. {
  1697. /*
  1698. measureGrid.LostFocus -= measureGrid_LostFocus;
  1699. measureGrid.Items.Refresh();
  1700. measureGrid.LostFocus += measureGrid_LostFocus;
  1701. */
  1702. }
  1703. private void measureGrid_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
  1704. {
  1705. //measureGrid.Items.Refresh();
  1706. }
  1707. private void commitBtn_Click(object sender, RoutedEventArgs e)
  1708. {
  1709. if (measureGrid.ItemsSource == null)
  1710. return;
  1711. var now = DateTime.Now;
  1712. var id = Utils.getSetting("currentMachine");
  1713. double sum = 0;
  1714. int count = 0;
  1715. List<List<float>> s = new List<List<float>>();
  1716. _isExisting = true;
  1717. Dictionary<string, List<double>> sumType = new Dictionary<string, List<double>>();
  1718. foreach (var item in measureGrid.Items)
  1719. {
  1720. //Console.WriteLine(item);
  1721. MeasurePoint mp = item as MeasurePoint;
  1722. if (mp.Avg == null)
  1723. {
  1724. mp.Avg = 0;
  1725. }
  1726. if (mp.Avg == 0)
  1727. continue;
  1728. if (mp.Grade == null)
  1729. {
  1730. mp.Grade = "-";
  1731. }
  1732. if (mp.ResultGrade == null)
  1733. {
  1734. mp.ResultGrade = "-";
  1735. }
  1736. /*
  1737. if (mp.Type == "MID" && this.isMiddle == false)
  1738. continue;
  1739. if (mp.Type == "IN*" && _isIn == false)
  1740. continue;
  1741. */
  1742. if (sumType.ContainsKey(mp.Type.Trim()) == false)
  1743. {
  1744. sumType[mp.Type.Trim()] = new List<double>();
  1745. }
  1746. (sumType[mp.Type.Trim()] as List<double>).Add(mp.Avg);
  1747. try
  1748. {
  1749. string sql = string.Format(" insert into data(lot_no, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, row_no, avg, grade, rgrade, r_type, created_at, updated_at, ndata, sub_order, machine_id, code, header) " +
  1750. " values ('{0}', {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, '{13}', '{14}', '{15}', '{16}', '{17}', {18}, {19}, {20}, '{21}', '{22}' )"
  1751. , lotNo.Text.Trim(), mp.P1, mp.P2, mp.P3, mp.P4, mp.P5, mp.P6, mp.P7, mp.P8, mp.P9, mp.P10, mp.Count, mp.Avg, mp.Grade.Trim(), mp.ResultGrade.Trim(), mp.Type.Trim(), now, now, nextCol, mp.SubOrder, id, code.Text.Trim(), this.header);
  1752. sum += mp.Avg;
  1753. //var s0 = lotNo.Text.Trim();
  1754. /*
  1755. var tempList = new List<float>();
  1756. for(int i = 1; i < nextCol; i++){
  1757. tempList.Add(mp.GetValue("P"+i));
  1758. }
  1759. s.Add(tempList);
  1760. */
  1761. count++;
  1762. using (SqlCommand command = new SqlCommand(sql, proConn))
  1763. {
  1764. command.ExecuteNonQuery();
  1765. }
  1766. }
  1767. catch (Exception exc)
  1768. {
  1769. MessageBox.Show("This here 1");
  1770. }
  1771. }
  1772. //Math.Round(
  1773. int i = 0;
  1774. string[] keys = new string[sumType.Keys.Count];
  1775. sumType.Keys.CopyTo(keys, 0);
  1776. for (int k = 0; k < keys.Length; k++)
  1777. {
  1778. keys[k] = "'" + keys[k] + "'";
  1779. }
  1780. //List<string> avgValues = new List<string>();
  1781. string[] values = new string[sumType.Keys.Count];
  1782. int j = 0;
  1783. string[] columns = new string[sumType.Keys.Count];
  1784. string[] columnValues = new string[sumType.Keys.Count];
  1785. foreach (var name in sumType)
  1786. {
  1787. var temp = name.Value as List<double>;
  1788. double st = 0.0;
  1789. foreach (double n in temp)
  1790. {
  1791. st += n;
  1792. }
  1793. values[j] = Math.Round((double)(st / temp.Count), 2).ToString();
  1794. columns[j] = "avg" + j + "_name";
  1795. columnValues[j] = "avg" + j;
  1796. j++;
  1797. }
  1798. double avg = Math.Round(sum / count, 2);
  1799. string grade = "-";
  1800. try
  1801. {
  1802. int a, b;
  1803. //if (Convert.ToInt32(sMi16) <= Convert.ToInt32(sMi20))
  1804. Int32.TryParse(sMi16, out a);
  1805. Int32.TryParse(sMi20, out b);
  1806. if (a <= b)
  1807. {
  1808. grade = computeGrade(sMi16, avg, kind, "-", "OUT");
  1809. }
  1810. else
  1811. {
  1812. if (Convert.ToInt32(sMi20) == 0)
  1813. grade = computeGrade(sMi16, avg, kind, "-", "OUT");
  1814. else
  1815. grade = computeGrade(sMi20, avg, kind, "-", "OUT");
  1816. }
  1817. }
  1818. catch (Exception exc)
  1819. {
  1820. MessageBox.Show("Here 2 "+ sMi16 + " , " + sMi20);
  1821. }
  1822. try
  1823. {
  1824. string sql2 = string.Format("insert into lot_summary(lot_no, created_at, avg, code, start_time, end_time, grade, machine_id, " + String.Join(",", columns) + "," + String.Join(",", columnValues) + ") values('{0}', '{1}', {2}, '{3}', '{4}', '{5}', '{6}', {7}, {8}, {9})",
  1825. lotNo.Text.Trim(), now, avg, code.Text.Trim(), _startUsing, now, grade.Trim(), id, String.Join(",", keys), String.Join(",", values
  1826. ));
  1827. using (SqlCommand command = new SqlCommand(sql2, proConn))
  1828. {
  1829. command.ExecuteNonQuery();
  1830. }
  1831. _updated_at = now.ToString();
  1832. PrintLabel(lotNo.Text, now);
  1833. MessageBox.Show("Commit Complete");
  1834. lotNo.Focus();
  1835. lotNo.SelectAll();
  1836. }
  1837. catch (Exception ex)
  1838. {
  1839. MessageBox.Show("Data Input Error "+ ex.Message);
  1840. }
  1841. }
  1842. private void PrintLabel(string lotNo, DateTime dt)
  1843. {
  1844. string sql = string.Format("select * from data where lot_no = '{0}' and created_at = '{1}' order by id", lotNo, dt);
  1845. SqlDataReader reader = Utils.Query(proConn, sql);
  1846. string s = "";
  1847. int n = 0;
  1848. List<double> outs = new List<double>();
  1849. List<double> ins = new List<double>();
  1850. bool outValid = false;
  1851. bool inValid = false;
  1852. string inAvg = "";
  1853. string outAvg = "";
  1854. int row = 0;
  1855. int nrow = 0;
  1856. while (reader.Read())
  1857. {
  1858. nrow++;
  1859. n = Convert.ToInt32(reader["ndata"]);
  1860. string r_type = reader["r_type"].ToString();
  1861. try
  1862. {
  1863. r_type = r_type.Substring(0, 3);
  1864. }
  1865. catch
  1866. {
  1867. ;
  1868. }
  1869. s += string.Format("{0,3}", r_type.ToUpper()) + " ";
  1870. for (int i = 1; i <= n; i++)
  1871. {
  1872. if (n > 3)
  1873. {
  1874. s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
  1875. }
  1876. else
  1877. {
  1878. s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
  1879. }
  1880. row++;
  1881. }
  1882. //s = s.Trim();
  1883. var grade = reader["grade"].ToString().Trim();
  1884. var rgrade = reader["rgrade"].ToString().Trim();
  1885. try
  1886. {
  1887. if (n >= 5)
  1888. rgrade = rgrade.Substring(0, 2);
  1889. }
  1890. catch
  1891. {
  1892. ;
  1893. }
  1894. //if (reader["rgrade"].ToString().ToLower() != "ok")
  1895. //{
  1896. // s += string.Format(" {0,-6:*0.00*}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}",grade) + " " + rgrade;
  1897. //}
  1898. //else
  1899. //{
  1900. if (n >= 5)
  1901. {
  1902. s += string.Format("{0,5:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;
  1903. }
  1904. else
  1905. {
  1906. s += string.Format("{0,7:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;
  1907. }
  1908. //}
  1909. //s = s.Trim();
  1910. s += "\n";
  1911. /*
  1912. UPP,UPPE = Out
  1913. LOW,LOWE = In
  1914. Rim = Out
  1915. Base =In
  1916. Soko = In
  1917. IN* = In
  1918. */
  1919. if (r_type.ToUpper() == "OUT" || r_type.ToUpper() == "TOP" || r_type.ToUpper() == "FA1" || r_type.ToUpper() == "UPP" || r_type.ToUpper() == "UPPE" || r_type.ToUpper() == "RIM")
  1920. {
  1921. outs.Add(Convert.ToDouble(reader["avg"]));
  1922. }
  1923. if (r_type.ToUpper() == "IN" || r_type.ToUpper() == "UNDER" || r_type.ToUpper() == "FA2" || r_type.ToUpper() == "UND" || r_type.ToUpper() == "LOW" || r_type.ToUpper() == "LOWE" || r_type.ToUpper() == "BASE" || r_type.ToUpper() == "SOKO" || r_type.ToUpper() == "IN*")
  1924. {
  1925. ins.Add(Convert.ToDouble(reader["avg"]));
  1926. }
  1927. }
  1928. //string avg = string.Format("{0.00}", Convert.ToDouble(reader["avg"]));
  1929. double[] inArray = new double[] {
  1930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1933. double[] outArray = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  1936. double sumIns = 0;
  1937. double sumOuts = 0;
  1938. for (int i = 0; i < ins.Count; i++)
  1939. {
  1940. inArray[i] = ins[i];
  1941. sumIns += ins[i];
  1942. }
  1943. for (int i = 0; i < outs.Count; i++)
  1944. {
  1945. outArray[i] = outs[i];
  1946. sumOuts += outs[i];
  1947. }
  1948. double avgIns = 0;
  1949. if (ins.Count == 0)
  1950. avgIns = 0;
  1951. else
  1952. avgIns = sumIns / ins.Count;
  1953. double avgOut = 0;
  1954. if (outs.Count == 0)
  1955. avgOut = 0;
  1956. else
  1957. avgOut = sumOuts / outs.Count;
  1958. reader.Close();
  1959. sql = string.Format("select m.name , ls.avg, ls.grade, ls.start_time, ls.end_time, ls.code from lot_summary ls, machines m where ls.lot_no = '{0}' and ls.created_at = '{1}' and ls.machine_id = m.id", lotNo, dt);
  1960. reader = Utils.Query(proConn, sql);
  1961. var temp = list;
  1962. var types = string.Join("/", temp.ToArray());
  1963. string code = "";
  1964. string et = "";
  1965. while (reader.Read())
  1966. {
  1967. code = reader["code"].ToString();
  1968. s += string.Format("{0} Use {1}Times {2} AVG {3:0.00} {4}\n", reader["name"].ToString(), UsingTimeTB.Text.Trim(), types, Convert.ToDouble(reader["avg"]), reader["grade"].ToString());
  1969. var startTime = Convert.ToDateTime(reader["start_time"]);
  1970. var endTime = Convert.ToDateTime(reader["end_time"]);
  1971. et = string.Format("{0:dd/MM/yyyy HH:mm:ss}", endTime);
  1972. s += string.Format("Date:{0:dd/MM/yyyy} Time:{1:HH:mm}-{2:HH:mm}\n", startTime, startTime, endTime);
  1973. }
  1974. code = code.Replace("-", "");
  1975. string tableName = "";
  1976. try
  1977. {
  1978. accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
  1979. accessConnEMASTER.Open();
  1980. }
  1981. catch (Exception ex)
  1982. {
  1983. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  1984. }
  1985. try
  1986. {
  1987. accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
  1988. accessConnBELMASTER.Open();
  1989. }
  1990. catch (Exception ex)
  1991. {
  1992. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  1993. }
  1994. try
  1995. {
  1996. accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
  1997. accessConnMGMASTER.Open();
  1998. }
  1999. catch (Exception ex)
  2000. {
  2001. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  2002. }
  2003. try
  2004. {
  2005. accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
  2006. accessConnVMASTER.Open();
  2007. }
  2008. catch (Exception ex)
  2009. {
  2010. MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);
  2011. }
  2012. if (code[0] == '1' || code[0] == '9')
  2013. {
  2014. tempConn = accessConnVMASTER;
  2015. tableName = "V-REREKI";
  2016. }
  2017. if (code[0] == '2')
  2018. {
  2019. tempConn = accessConnMGMASTER;
  2020. tableName = "MG-REREKI";
  2021. }
  2022. if (code[0] == '3' || code[0] == '4')
  2023. {
  2024. tempConn = accessConnEMASTER;
  2025. tableName = "E-REREKI";
  2026. }
  2027. if (code[0] == '5')
  2028. {
  2029. tempConn = accessConnBELMASTER;
  2030. tableName = "BEL-REREKI";
  2031. }
  2032. OleDbCommand deleteCommand = new OleDbCommand("delete from [" + tableName + "] where RE01 = '" + code + "' and RE02 = '" + lotNo + "'", tempConn);
  2033. deleteCommand.ExecuteNonQuery();
  2034. //int lotCount = (int)selectCountCommand.ExecuteScalar();
  2035. //if (lotCount == 0)
  2036. //{
  2037. string rereki = string.Format("insert into [" + tableName + "](RE01, RE02, RE03,RE04, [OB-O1], [OB-O2], [OB-O3], [OB-O4], [OB-O5], [OB-O6], [OB-O7], [OB-O8],[OB-O9], [OB-O10], [OB-O11], [OB-O12], [OB-O13], [OB-O14], [OB-O15],[OB-O16], [OB-O17], [OB-O18], [OB-O19], [OB-O20], [OB-O21], [OB-O22], [OB-O23], [OB-O24], [OB-O25],[OB-O26], [OB-O27],[OB-O28],[OB-O29],[OB-O30], [OB-I1], [OB-I2], [OB-I3], [OB-I4], [OB-I5], [OB-I6], [OB-I7], [OB-I8], [OB-I9], [OB-I10], [OB-I11], [OB-I12], [OB-I13], [OB-I14], [OB-I15], [OB-I16], [OB-I17], [OB-I18], [OB-I19], [OB-I20], [OB-I21], [OB-I22], [OB-I23], [OB-I24], [OB-I25], [OB-I26], [OB-I27], [OB-I28], [OB-I29], [OB-I30], [OB-O], [OB-I])"
  2038. + "values('{0}', '{1}', '{2}', {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12},{13}, {14}, {15},{16}, {17}, {18},{19},{20},{21},{22}, {23},{24}, {25}, {26}, {27}, {28},{29},{30},{31},{32},{33},{34},{35},{36}, {37},{38}, {39},{40}, {41},{42},{43},{44},{45},{46},{47},{48}, {49},{50}, {51}, {52}, {53}, {54}, {55}, {56}, {57}, {58}, {59},{60},{61},{62},{63},{64}, {65})", code, lotNo, et, nrow, outArray[0], outArray[1], outArray[2], outArray[3], outArray[4], outArray[5], outArray[6], outArray[7], outArray[8], outArray[9], outArray[10], outArray[11], outArray[12], outArray[13], outArray[14], outArray[15], outArray[16], outArray[17], outArray[18], outArray[19], outArray[20], outArray[21], outArray[22], outArray[23], outArray[24], outArray[25], outArray[26], outArray[27], outArray[28], outArray[29], inArray[0], inArray[1], inArray[2], inArray[3], inArray[4], inArray[5], inArray[6], inArray[7], inArray[8], inArray[9], inArray[10], inArray[11], inArray[12], inArray[13], inArray[14], inArray[15], inArray[16], inArray[17], inArray[18], inArray[19], inArray[20], inArray[21], inArray[22], inArray[23], inArray[24], inArray[25], inArray[26], inArray[27], inArray[28], inArray[29], avgOut, avgIns);
  2039. OleDbCommand insertCmd = new OleDbCommand(rereki, tempConn);
  2040. //MessageBox.Show("re = " + rereki);
  2041. insertCmd.ExecuteNonQuery();
  2042. //}
  2043. accessConnBELMASTER.Close();
  2044. accessConnEMASTER.Close();
  2045. accessConnMGMASTER.Close();
  2046. accessConnVMASTER.Close();
  2047. reader.Close();
  2048. //Utils.Query(proConn, "select P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 from lot_summary where lot_no =
  2049. //Printer.Print(s, n);
  2050. //Printer.Print(s);
  2051. printMultipage(s, n);
  2052. //var p = new Printer();
  2053. }
  2054. void printMultipage(string s, int n)
  2055. {
  2056. var lines = s.Split('\n');
  2057. const int NL = 8;
  2058. var el = lines.Count() / NL;
  2059. string postFix = "";
  2060. for (var i = 0; i < el; i++)
  2061. {
  2062. var pages = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
  2063. //pages += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
  2064. for (var j = 0; j < NL; j++)
  2065. {
  2066. pages += lines[j + (i * NL)] + "\n";
  2067. }
  2068. Printer.Print(pages);
  2069. }
  2070. /*
  2071. Printer p = new Printer();
  2072. Console.WriteLine("printer print");
  2073. p.PrintDoc(s);*/
  2074. var remain = lines.Count() % NL;
  2075. if (remain == 0)
  2076. return;
  2077. var pager = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
  2078. //pager += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
  2079. for (var j = el * NL; j < lines.Count(); j++)
  2080. {
  2081. if (lines[j] == "")
  2082. continue;
  2083. pager += lines[j] + "\n";
  2084. }
  2085. Printer.Print(pager);
  2086. }
  2087. private void measureGrid_LoadingRow(object sender, DataGridRowEventArgs e)
  2088. {
  2089. /*
  2090. DataGridRow c = e.Row;
  2091. MeasurePoint mp = e.Row.Item as MeasurePoint;
  2092. if (mp.Type == "MID" && this.isMiddle == false)
  2093. {
  2094. c.Visibility = Visibility.Collapsed;
  2095. }
  2096. if (mp.Type == "IN*" && _isIn == false)
  2097. {
  2098. c.Visibility = Visibility.Collapsed;
  2099. }
  2100. */
  2101. }
  2102. private void addMiddleBtn_Click(object sender, RoutedEventArgs e)
  2103. {
  2104. if (measureGrid.ItemsSource == null)
  2105. return;
  2106. _lastAction.Push("middle");
  2107. this.isMiddle = !this.isMiddle;
  2108. if (this.isMiddle == false)
  2109. {
  2110. middleText.Text = "Add Middle";
  2111. RemoveMid();
  2112. }
  2113. else
  2114. {
  2115. middleText.Text = "Remove Middle";
  2116. EditMIDWindow w = new EditMIDWindow();
  2117. w.ShowDialog();
  2118. AddMid();
  2119. }
  2120. //this.measureGrid.CommitEdit();
  2121. measureGrid.Items.Refresh();
  2122. }
  2123. private void RemoveMid()
  2124. {
  2125. list.Remove("MID");
  2126. ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
  2127. foreach (var m in mps)
  2128. {
  2129. if (m.Type != "MID")
  2130. {
  2131. temp.Add(m);
  2132. }
  2133. }
  2134. mps = temp;
  2135. measureGrid.ItemsSource = null;
  2136. measureGrid.ItemsSource = mps;
  2137. }
  2138. private void AddMid()
  2139. {
  2140. list.Insert(1, "MID");
  2141. ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
  2142. foreach (var m in mps)
  2143. {
  2144. temp.Add(m);
  2145. if (m.SubOrder == 1)
  2146. {
  2147. temp.Add(new MeasurePoint() { Type = "MID", SubOrder = m.SubOrder + 1, Count = m.Count });
  2148. }
  2149. }
  2150. mps = temp;
  2151. measureGrid.ItemsSource = null;
  2152. measureGrid.ItemsSource = mps;
  2153. }
  2154. private void deleteData_Click(object sender, RoutedEventArgs e)
  2155. {
  2156. this.currentMP.setValue(currentColumn, 0);
  2157. this.computeValues(currentMP, true);
  2158. measureGrid.Items.Refresh();
  2159. }
  2160. private void measureGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
  2161. {
  2162. this.currentColumn = e.Column.Header.ToString();
  2163. this.currentMP = (MeasurePoint)e.Row.Item;
  2164. cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";
  2165. }
  2166. private void measureGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
  2167. {
  2168. //this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
  2169. //this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
  2170. //cellIndicattor.Text = "("+currentMP.Type + "-" +currentMP.Count+", "+currentColumn+")";
  2171. }
  2172. private void measureGrid_CurrentCellChanged(object sender, EventArgs e)
  2173. {
  2174. try
  2175. {
  2176. this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
  2177. this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
  2178. cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";
  2179. //this.computeValues(currentMP);
  2180. }
  2181. catch (NullReferenceException ne) { }
  2182. }
  2183. private void saveCellBtn_Click(object sender, RoutedEventArgs e)
  2184. {
  2185. measureGrid.Focus();
  2186. if (currentColumn == null)
  2187. return;
  2188. if (_isOver == true)
  2189. return;
  2190. /*
  2191. if(_isFirstMeasure == true){
  2192. _startUsing = DateTime.Now;
  2193. _isFirstMeasure = false;
  2194. }*/
  2195. if (currentColumn != "Average" && currentColumn != "Grade" && currentColumn != "Result Grade")
  2196. {
  2197. Console.WriteLine("reading box"+readingBox.Text);
  2198. this.currentMP.setValue(currentColumn, Convert.ToDouble(readingBox.Text.Replace(" ", "")));
  2199. //var c = measureGrid.SelectedValue;
  2200. this.computeValues(currentMP, true);
  2201. }
  2202. try
  2203. {
  2204. var info = measureGrid.CurrentColumn;
  2205. var item = measureGrid.CurrentItem as MeasurePoint;
  2206. int col = info.DisplayIndex;
  2207. var mp = (MeasurePoint)measureGrid.CurrentItem;
  2208. int row = mps.IndexOf(mp);
  2209. //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
  2210. //MessageBox.Show("row " + item.Count.ToString());
  2211. //MessageBox.Show("row " + mps.IndexOf(mp).ToString());
  2212. //MessageBox.Show("col " + info.DisplayIndex.ToString());
  2213. measureGrid.Items.Refresh();
  2214. measureGrid.Focus();
  2215. if (col < nextCol)
  2216. {
  2217. measureGrid.CurrentCell = new DataGridCellInfo(
  2218. measureGrid.Items[row], measureGrid.Columns[col + 1]);
  2219. measureGrid.BeginEdit();
  2220. }
  2221. else
  2222. {
  2223. try
  2224. {
  2225. //this.computeValues(currentMP, true);
  2226. measureGrid.CurrentCell = new DataGridCellInfo(
  2227. measureGrid.Items[row + 1], measureGrid.Columns[1]);
  2228. measureGrid.SelectedItem = measureGrid.Items[row + 1];
  2229. measureGrid.BeginEdit();
  2230. }
  2231. catch
  2232. {
  2233. measureGrid.CurrentCell = new DataGridCellInfo(
  2234. measureGrid.Items[0], measureGrid.Columns[1]);
  2235. measureGrid.SelectedItem = measureGrid.Items[0];
  2236. measureGrid.BeginEdit();
  2237. }
  2238. }
  2239. }
  2240. catch
  2241. {
  2242. ;
  2243. }
  2244. updateUsingTime(this.header);
  2245. }
  2246. private void updateUsingTime(string p, int n = -1)
  2247. {
  2248. switch (p)
  2249. {
  2250. case "OB":
  2251. _obCount++;
  2252. _usingTime = _obCount;
  2253. if (_obCount > _obLimit)
  2254. {
  2255. _obCount = _obLimit;
  2256. Alert alert = new Alert();
  2257. alert.SetAlertMsg("OB Header Exceeds Usage Limit");
  2258. alert.ShowDialog();
  2259. _isOver = true;
  2260. }
  2261. _isOver = false;
  2262. if (n == -1)
  2263. {
  2264. Utils.Query(_opConn, "update UsingTime set ob = " + _obCount);
  2265. UsingTimeTB.Text = _obCount.ToString();
  2266. }
  2267. else
  2268. {
  2269. Utils.Query(_opConn, "update UsingTime set ob = " + n);
  2270. UsingTimeTB.Text = n.ToString();
  2271. _obCount = n;
  2272. }
  2273. break;
  2274. case "OC":
  2275. _ocCount++;
  2276. _usingTime = _ocCount;
  2277. if (_ocCount > _ocLimit)
  2278. {
  2279. _ocCount = _ocLimit;
  2280. Alert alert = new Alert();
  2281. alert.SetAlertMsg("OC Header Exceeds Usage Limit");
  2282. alert.ShowDialog();
  2283. _isOver = true;
  2284. }
  2285. _isOver = false;
  2286. if (n == -1)
  2287. {
  2288. Utils.Query(_opConn, "update UsingTime set oc = " + _ocCount);
  2289. UsingTimeTB.Text = _ocCount.ToString();
  2290. }
  2291. else
  2292. {
  2293. Utils.Query(_opConn, "update UsingTime set oc = " + n);
  2294. UsingTimeTB.Text = n.ToString();
  2295. _ocCount = n;
  2296. }
  2297. break;
  2298. case "RH":
  2299. _rhCount++;
  2300. _usingTime = _rhCount;
  2301. if (_rhCount > _rhLimit)
  2302. {
  2303. _rhCount = _rhLimit;
  2304. Alert alert = new Alert();
  2305. alert.SetAlertMsg("RH Header Exceeds Usage Limit");
  2306. alert.ShowDialog();
  2307. _isOver = true;
  2308. }
  2309. _isOver = false;
  2310. if (n == -1)
  2311. {
  2312. Utils.Query(_opConn, "update UsingTime set rh = " + _rhCount);
  2313. UsingTimeTB.Text = _rhCount.ToString();
  2314. }
  2315. else
  2316. {
  2317. Utils.Query(_opConn, "update UsingTime set rh = " + n);
  2318. UsingTimeTB.Text = n.ToString();
  2319. _rhCount = n;
  2320. }
  2321. break;
  2322. default:
  2323. //MessageBox.Show("Please Find a Lot NO First");
  2324. break;
  2325. }
  2326. }
  2327. public void refreshUsingTime()
  2328. {
  2329. string p = this.header;
  2330. string sql = string.Format("select {0} as n from UsingTime", this.header.ToLower());
  2331. var reader = Utils.Query(_opConn, sql);
  2332. reader.Read();
  2333. UsingTimeTB.Text = reader["n"].ToString();
  2334. if (p == "OB")
  2335. {
  2336. _obCount = Convert.ToInt32(reader["n"]);
  2337. }
  2338. else if (p == "OC")
  2339. {
  2340. _ocCount = Convert.ToInt32(reader["n"]);
  2341. }
  2342. }
  2343. private void IntranetBtn_Click(object sender, RoutedEventArgs e)
  2344. {
  2345. SqlDataReader reader = Utils.Query(proConn, "select value from sys_configs where title = 'internal_url'");
  2346. reader.Read();
  2347. string target = reader["value"].ToString();
  2348. //string target = reader["value"].Read().ToString();
  2349. try
  2350. {
  2351. System.Diagnostics.Process.Start(target);
  2352. }
  2353. catch (System.ComponentModel.Win32Exception noBrowser)
  2354. {
  2355. if (noBrowser.ErrorCode == -2147467259)
  2356. MessageBox.Show(noBrowser.Message);
  2357. }
  2358. catch (System.Exception other)
  2359. {
  2360. MessageBox.Show(other.Message);
  2361. }
  2362. reader.Close();
  2363. }
  2364. private void undoBtn_Click(object sender, RoutedEventArgs e)
  2365. {
  2366. if (_lastAction.Count == 0)
  2367. return;
  2368. string action = _lastAction.Pop();
  2369. if (action == "middle")
  2370. {
  2371. this.isMiddle = !this.isMiddle;
  2372. if (this.isMiddle == false)
  2373. {
  2374. middleText.Text = "Add Middle";
  2375. RemoveMid();
  2376. }
  2377. else
  2378. {
  2379. middleText.Text = "Remove Middle";
  2380. AddMid();
  2381. }
  2382. }
  2383. if (action == "in")
  2384. {
  2385. _isIn = !_isIn;
  2386. if (_isIn == false)
  2387. {
  2388. inText.Text = "Add IN*";
  2389. RemoveIn();
  2390. }
  2391. else
  2392. {
  2393. inText.Text = "Remove IN*";
  2394. AddIn();
  2395. }
  2396. }
  2397. else if (action == "row")
  2398. {
  2399. for (int i = 0; i < list.Count; i++)
  2400. {
  2401. mps.RemoveAt(mps.Count - 1);
  2402. }
  2403. }
  2404. else if (action == "column")
  2405. {
  2406. measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;
  2407. foreach (var item in measureGrid.Items)
  2408. {
  2409. //Console.WriteLine(item);
  2410. MeasurePoint c = item as MeasurePoint;
  2411. c.setValue((nextCol + 1).ToString(), (float)0.0);
  2412. c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol);
  2413. c.Avg = Math.Round(c.Avg, 2);
  2414. if (c.SubOrder == 1)
  2415. {
  2416. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  2417. }
  2418. else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
  2419. {
  2420. if (sMi20 != "0")
  2421. c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
  2422. else
  2423. c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
  2424. }
  2425. }
  2426. }
  2427. else if (action == "remove_column")
  2428. {
  2429. measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;
  2430. foreach (var item in measureGrid.Items)
  2431. {
  2432. //Console.WriteLine(item);
  2433. MeasurePoint c = item as MeasurePoint;
  2434. c.setValue((nextCol).ToString(), (float)0.0);
  2435. computeValues(c, true);
  2436. }
  2437. }
  2438. measureGrid.Items.Refresh();
  2439. }
  2440. private void printBtn_Click(object sender, RoutedEventArgs e)
  2441. {
  2442. if (_isExisting == true)
  2443. {
  2444. PrintLabel(lotNo.Text, Convert.ToDateTime(_updated_at));
  2445. }
  2446. else
  2447. {
  2448. MessageBox.Show("You can print when you have commited data");
  2449. }
  2450. }
  2451. private void agreementBtn_Click(object sender, RoutedEventArgs e)
  2452. {
  2453. var fileName = agreementCB.Text;
  2454. try
  2455. {
  2456. //System.Diagnostics.Process.Start(@"agreements\" + fileName);
  2457. var server = Utils.getSetting("webServerURL");
  2458. string data = string.Format(@"title={0}&empid={1}&password={2}", fileName, GlobalVars.user.empid, GlobalVars.user.password);
  2459. WebAppConnector wp = new WebAppConnector()
  2460. {
  2461. Uri = Utils.getSetting("webServerURL") + "/agreements/title.json",
  2462. Method = "POST",
  2463. PostData = data
  2464. };
  2465. Response r = null;
  2466. try
  2467. {
  2468. r = wp.sendRequest();
  2469. }
  2470. catch
  2471. {
  2472. MessageBox.Show("Cannot connect to webserver :" + server);
  2473. return;
  2474. }
  2475. string ans = (string)r.jsonBody["msg"];
  2476. //Console.WriteLine((JArray)r.jsonBody["roles"]);
  2477. if (r.status == "OK" && ans == "y")
  2478. {
  2479. System.Diagnostics.Process.Start(server + (string)r.jsonBody["url"]);
  2480. }
  2481. else
  2482. {
  2483. MessageBox.Show("Cannot find agreement file");
  2484. }
  2485. }
  2486. catch (Win32Exception ew)
  2487. {
  2488. MessageBox.Show(ew.Message);
  2489. }
  2490. }
  2491. private void thaiMenu_Checked(object sender, RoutedEventArgs e)
  2492. {
  2493. engMenu.IsChecked = false;
  2494. //var selectedItem = comboBoxLanguage.SelectedItem as ComboBoxItem;
  2495. var culture = CultureInfo.GetCultureInfo("th-TH");
  2496. Dispatcher.Thread.CurrentCulture = culture;
  2497. Dispatcher.Thread.CurrentUICulture = culture;
  2498. LocalizationManager.UpdateValues();
  2499. }
  2500. private void engMenu_Checked(object sender, RoutedEventArgs e)
  2501. {
  2502. thaiMenu.IsChecked = false;
  2503. var culture = CultureInfo.GetCultureInfo("en-US");
  2504. Dispatcher.Thread.CurrentCulture = culture;
  2505. Dispatcher.Thread.CurrentUICulture = culture;
  2506. LocalizationManager.UpdateValues();
  2507. }
  2508. private void windowItem_Checked(object sender, RoutedEventArgs e)
  2509. {
  2510. this.WindowStyle = WindowStyle.SingleBorderWindow;
  2511. this.WindowState = WindowState.Normal;
  2512. this.isFullScreen = false;
  2513. fullScreenItem.IsChecked = false;
  2514. }
  2515. private void fullScreenItem_Checked(object sender, RoutedEventArgs e)
  2516. {
  2517. this.WindowStyle = WindowStyle.None;
  2518. this.WindowState = WindowState.Maximized;
  2519. this.isFullScreen = true;
  2520. windowItem.IsChecked = false;
  2521. }
  2522. private void measureGrid_KeyDown(object sender, KeyEventArgs e)
  2523. {
  2524. }
  2525. private void measureGrid_Loaded(object sender, RoutedEventArgs e)
  2526. {
  2527. //MessageBox.Show("Refresh Finish");
  2528. }
  2529. private void measureGrid_SourceUpdated(object sender, DataTransferEventArgs e)
  2530. {
  2531. MessageBox.Show("refresh finish");
  2532. }
  2533. private void measureGrid_ColumnDisplayIndexChanged(object sender, DataGridColumnEventArgs e)
  2534. {
  2535. }
  2536. private void measureGrid_PreviewKeyDown(object sender, KeyEventArgs e)
  2537. {
  2538. }
  2539. private void rlChick(object sender, RoutedEventArgs e)
  2540. {
  2541. _rlWindow = new RLWindow();
  2542. //_dc.Show();
  2543. _rlWindow.Show();
  2544. //_dc.ShowDialog();
  2545. }
  2546. private void lotNo_MouseDown(object sender, MouseButtonEventArgs e)
  2547. {
  2548. //lotNo.SelectAll();
  2549. }
  2550. private void lotNo_GotFocus(object sender, RoutedEventArgs e)
  2551. {
  2552. //lotNo.SelectAll();
  2553. }
  2554. private void lotNo_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
  2555. {
  2556. lotNo.SelectAll();
  2557. }
  2558. private void lotNo_GotMouseCapture(object sender, MouseEventArgs e)
  2559. {
  2560. lotNo.SelectAll();
  2561. }
  2562. private void resetBtn_Click(object sender, RoutedEventArgs e)
  2563. {
  2564. updateUsingTime(this.header, 0);
  2565. measureGrid.Focus();
  2566. try
  2567. {
  2568. measureGrid.CurrentCell = new DataGridCellInfo(
  2569. measureGrid.Items[0], measureGrid.Columns[1]);
  2570. measureGrid.SelectedItem = measureGrid.Items[0];
  2571. measureGrid.BeginEdit();
  2572. }
  2573. catch
  2574. {
  2575. }
  2576. }
  2577. private void editUsingTime_Click(object sender, RoutedEventArgs e)
  2578. {
  2579. EditUsingTime editUsingTime = new EditUsingTime();
  2580. editUsingTime.ShowDialog();
  2581. }
  2582. private void addInBtn_Click(object sender, RoutedEventArgs e)
  2583. {
  2584. //measureGrid.ItemsSource = null;
  2585. if (measureGrid.ItemsSource == null)
  2586. return;
  2587. _isIn = !_isIn;
  2588. if (_isIn == false)
  2589. {
  2590. inText.Text = "Add IN*";
  2591. RemoveIn();
  2592. }
  2593. else
  2594. {
  2595. inText.Text = "Remove IN*";
  2596. EditINWindow w = new EditINWindow();
  2597. w.ShowDialog();
  2598. AddIn();
  2599. }
  2600. //ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
  2601. _lastAction.Push("in");
  2602. measureGrid.Items.Refresh();
  2603. /*
  2604. for(int i = 0; i < mps.Count; i++){
  2605. var mp = mps[i];
  2606. if(mp.SubOrder == 1){
  2607. mps.Insert(mps.IndexOf(mp) + 1, new MeasurePoint() { Count = mp.Count, Type = "IN*", SubOrder = 3});
  2608. }
  2609. }
  2610. measureGrid.ItemsSource = mps;
  2611. */
  2612. //measureGrid.ItemsSource = null;
  2613. //measureGrid.Items.Add(0, new MeasurePoint() { Count = 1, Type = "In"});
  2614. }
  2615. private void RemoveIn()
  2616. {
  2617. list.Remove("IN*");
  2618. ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
  2619. foreach (var m in mps)
  2620. {
  2621. if (m.Type != "IN*")
  2622. {
  2623. temp.Add(m);
  2624. }
  2625. }
  2626. mps = temp;
  2627. measureGrid.ItemsSource = null;
  2628. measureGrid.ItemsSource = mps;
  2629. }
  2630. private void AddIn()
  2631. {
  2632. list.Insert(1, "IN*");
  2633. ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
  2634. foreach (var m in mps)
  2635. {
  2636. temp.Add(m);
  2637. if (m.SubOrder == 1)
  2638. {
  2639. temp.Add(new MeasurePoint() { Type = "IN*", SubOrder = m.SubOrder + 1, Count = m.Count });
  2640. }
  2641. }
  2642. mps = temp;
  2643. measureGrid.ItemsSource = null;
  2644. measureGrid.ItemsSource = mps;
  2645. }
  2646. private void dailyCheckBtn_Click(object sender, RoutedEventArgs e)
  2647. {
  2648. _dc = new DailyCheck();
  2649. //_dc.Show();
  2650. _dc.ShowDialog();
  2651. //_dc.ShowDialog();
  2652. }
  2653. private void removeMeasureColumn_Click(object sender, RoutedEventArgs e)
  2654. {
  2655. _lastAction.Push("remove_column");
  2656. measureGrid.Columns.ElementAt(nextCol).Visibility = Visibility.Hidden;
  2657. if (nextCol <= 10)
  2658. {
  2659. measureGrid.Columns.ElementAt(--nextCol).Visibility = Visibility.Visible;
  2660. foreach (var item in measureGrid.Items)
  2661. {
  2662. //Console.WriteLine(item);
  2663. MeasurePoint c = item as MeasurePoint;
  2664. c.setValue((nextCol + 1).ToString(), 0);
  2665. computeValues(c, true);
  2666. }
  2667. measureGrid.Items.Refresh();
  2668. }
  2669. }
  2670. private void lotNo_KeyDown(object sender, KeyEventArgs e)
  2671. {
  2672. if (e.Key == Key.Return)
  2673. {
  2674. //MessageBox.Show("Hello");
  2675. find_Click(null, null);
  2676. }
  2677. }
  2678. private void checkLogin_Click(object sender, RoutedEventArgs e)
  2679. {
  2680. var server = Utils.getSetting("webServerURL");
  2681. //string data = string.Format(@"title={0}", fileName);
  2682. WebAppConnector wp = new WebAppConnector()
  2683. {
  2684. Uri = Utils.getSetting("webServerURL") + "/sites/get_current_user.json",
  2685. Method = "POST",
  2686. PostData = ""
  2687. };
  2688. Response r = null;
  2689. try
  2690. {
  2691. r = wp.sendRequest();
  2692. }
  2693. catch
  2694. {
  2695. MessageBox.Show("Cannot connect to webserver :" + server);
  2696. }
  2697. string ans = (string)r.jsonBody["u"];
  2698. //Console.WriteLine((JArray)r.jsonBody["roles"]);
  2699. }
  2700. private void searchAgreementBtn_Click(object sender, RoutedEventArgs e)
  2701. {
  2702. SearchAgreement sa = new SearchAgreement();
  2703. sa.ShowDialog();
  2704. }
  2705. private void editINStar_Click(object sender, RoutedEventArgs e)
  2706. {
  2707. EditINWindow w = new EditINWindow();
  2708. w.ShowDialog();
  2709. foreach (var item in measureGrid.Items)
  2710. {
  2711. MeasurePoint c = item as MeasurePoint;
  2712. computeValues(c, true);
  2713. }
  2714. measureGrid.Items.Refresh();
  2715. }
  2716. private void editMID_Click(object sender, RoutedEventArgs e)
  2717. {
  2718. EditMIDWindow w = new EditMIDWindow();
  2719. w.ShowDialog();
  2720. foreach (var item in measureGrid.Items)
  2721. {
  2722. MeasurePoint c = item as MeasurePoint;
  2723. computeValues(c, true);
  2724. }
  2725. measureGrid.Items.Refresh();
  2726. }
  2727. private void logoutMenu_Click(object sender, RoutedEventArgs e)
  2728. {
  2729. this.Hide();
  2730. LoginWindow lw = new LoginWindow();
  2731. var r = lw.ShowDialog();
  2732. resetMenu();
  2733. }
  2734. private void about_Click(object sender, RoutedEventArgs e)
  2735. {
  2736. Window1 w = new Window1();
  2737. w.ShowDialog();
  2738. }
  2739. private void Window_Closing(object sender, CancelEventArgs e)
  2740. {
  2741. if (comport.IsOpen)
  2742. {
  2743. comport.Close();
  2744. _clearThread = true;
  2745. }
  2746. }
  2747. }
  2748. }