public PrintLog Create(PrintReceiptModel model)
        {
            var transaction = dbContext.Database.BeginTransaction();

            try
            {
                var table   = model.TransactionTypeCode == "I" ? "PurchaseTransactions" : "SaleTransactions";
                var colName = model.TransactionTypeCode == "I" ? "PurchaseId" : "SaleId";
                var qry     = $"UPDATE {table} SET {nameof(PurchaseTransaction.PrintCount)} = " +
                              $"{nameof(PurchaseTransaction.PrintCount)}+1 WHERE {colName} ={model.TransactionId}";
                dbContext.Database.ExecuteSqlRaw(qry);

                var printLog = new PrintLog()
                {
                    DTPrinted           = DateTime.Now,
                    TransactionId       = model.TransactionId,
                    TransactionTypeCode = model.TransactionTypeCode,
                    PrintReasons        = model.ReprintRemarks,
                    ReceiptNum          = model.ReceiptNum,
                    UserAccountId       = model.UserAccoountId,
                    UserAccountName     = model.UserFullName
                };
                dbContext.PrintLogs.Add(printLog);
                dbContext.SaveChanges();

                transaction.Commit();
                return(printLog);
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw ex;
            }
        }
示例#2
0
        public async void Share(string subject, string message, ImageSource image)
        {
            //await CheckAppPermissions();
            try
            {
                var intent = new Intent(Intent.ActionSend);
                //intent.PutExtra(Intent.ExtraSubject, subject);
                intent.PutExtra(Intent.ExtraText, message);
                intent.SetType("image/png");

                var handler = new ImageLoaderSourceHandler();
                var bitmap  = await handler.LoadImageAsync(image, this);

                /*
                 * var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads + Java.IO.File.Separator + "logo.png");
                 *
                 * using (var os = new System.IO.FileStream(path.AbsolutePath, System.IO.FileMode.Create))
                 * {
                 *  bitmap.Compress(Bitmap.CompressFormat.Png, 100, os);
                 * }
                 * intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path));
                 * Forms.Context.StartActivity(Intent.CreateChooser(intent, "Share Image"));
                 *
                 */


                /*
                 * string documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
                 * string folderName = "CurrentApp";
                 * var folderPath = System.IO.Path.Combine(documentPath, folderName);
                 * System.IO.Directory.CreateDirectory(folderPath);
                 * string fName = "Download.pdf";
                 * var localPath = System.IO.Path.Combine(folderPath, fName);
                 * using (var os = new System.IO.FileStream(localPath, System.IO.FileMode.Create))
                 * {
                 *  bitmap.Compress(Bitmap.CompressFormat.Png, 100, os);
                 * }
                 * intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile((Java.IO.File)localPath));
                 * Forms.Context.StartActivity(Intent.CreateChooser(intent, "Share Image"));
                 */


                //var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads + Java.IO.File.Separator + "logo.png");

                var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads + Java.IO.File.Separator + "logo.png" + System.DateTime.Now.Ticks.ToString());

                using (var os = new System.IO.FileStream(path.AbsolutePath, System.IO.FileMode.Create))
                {
                    bitmap.Compress(Bitmap.CompressFormat.Png, 100, os);
                }
                intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.FromFile(path));
                Forms.Context.StartActivity(Intent.CreateChooser(intent, "Share Image"));
            }
            catch (System.Exception ex)
            {
                PrintLog.PublishLog(ex);
            }
        }
示例#3
0
        //运行脚本
        //运行脚本需要判断当前连接了几个串口,然后针对于每个串口需要新建一个窗口,每个串口对应一接收数据的线程。
        //所有的串口发送数据只用一个线程,先解析脚本,将所有需要发送的数据添加到list中,然后循环发送所有的CMD。
        private void RunBtn_Click(object sender, EventArgs e)
        {
            if (PortList.Count == 0)
            {
                MessageBox.Show("please open serial port first !!!", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            RunBtn.Enabled = false;
            SendToolStripButton.Enabled = false;
            //ManualFlag = -1;

            WriteDataList.Clear();
            PageLength.Clear();
            ComDataPath.Clear();

            //处理脚本
            if (!ScriptIdentify())
            {
                RunBtn.Enabled = true;
                SendToolStripButton.Enabled = true;
                return;
            }
            int i = 5, j = 5;

            //遍历每个串口
            foreach (SerialPort port in PortList.Values)
            {
                if (!SerialToPath.ContainsKey(port.PortName))
                {
                    //创建输出打印框
                    PrintLog PortLogBox = new PrintLog();
                    PortLogBox.Top  = i;
                    PortLogBox.Left = j;
                    PortLogBox.Text = port.PortName;
                    PortLogBox.Show();
                    //创建写入本地文件句柄
                    CreateFileHandle(port.PortName);
                    //接收数据线程
                    BackgroundWorker backgroundWorker = new BackgroundWorker();
                    backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.RecvData_DoWork);
                    SerialToTextBox Argument = new SerialToTextBox(port, PortLogBox.PrintLogBox);
                    backgroundWorker.RunWorkerAsync(Argument);
                    i += 20;
                    j += 20;
                }
                this.Activate();
            }

            flashToolStripMenuItem.Enabled = false;
            //发送数据线程
            BackgroundWorker SendWoker = new BackgroundWorker();

            SendWoker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.SendData_DoWork);
            IsRecvSingle      = true;
            SendWoker.RunWorkerAsync();
        }
示例#4
0
        public void Add(PrintLog log)
        {
            StringBuilder sqlBuilder = new StringBuilder()
                                       .Append("insert into {0} (pl_dtime, pl_pc, pl_mac, pl_ip, pl_advid) ")
                                       .Append("values ({1}, '{2}', '{3}', '{4}', {5}");
            string sql = string.Format(sqlBuilder.ToString(), DatabaseConf.PrintLogTable, log.PrintLogDispTime,
                                       log.PrintLogPcName, log.PrintLogMacAddr, log.PrintLogIpAddr, log.PrintLogAdvId);

            db.ExecuteUpdate(sql);
        }
        public IQueryable <PrintLog> Get(PrintLog parameters = null)
        {
            if (parameters == null)
            {
                return(new List <PrintLog>().AsQueryable());
            }

            return(dbContext.PrintLogs.Where(a =>
                                             (a.TransactionId == parameters.TransactionId &&
                                              (a.TransactionTypeCode == parameters.TransactionTypeCode))));
        }
示例#6
0
 void ConcurrentAdd(demo.App app, int count, int appId)
 {
     Task[] tasks = new Task[count];
     for (int i = 0; i < tasks.Length; ++i)
     {
         tasks[i] = global::Zeze.Util.Task.Run(app.Zeze.NewProcedure(() =>
         {
             demo.Module1.Value b = app.demo_Module1.Table1.GetOrAdd(6785);
             b.Int1      += 1;
             PrintLog log = new PrintLog(b, b, appId);
             Transaction.Current.PutLog(log); return(Procedure.Success);
         }, "ConcurrentAdd" + appId));
     }
     Task.WaitAll(tasks);
 }
示例#7
0
        public override Task <InsertLogResponse> InsertLog(InsertLogRequest request, ServerCallContext context)
        {
            InsertLogResponse response = new InsertLogResponse {
                InsertSucc = true
            };
            PrintLog log = new PrintLog
            {
                PrintLogAdvId    = request.PrintLog.AdId,
                PrintLogIpAddr   = request.PrintLog.IpAddr,
                PrintLogPcName   = request.PrintLog.PcName,
                PrintLogMacAddr  = request.PrintLog.MacAddr,
                PrintLogDispTime = request.PrintLog.Disptime
            };
            PrintLogDao dao = new PrintLogDao();

            dao.Add(log);
            return(Task.FromResult(response));
        }
        public static bool Connect(string strCom, int nBaudrate)
        {
            SerialPortUtil serialPort;

            try
            {
                string[] coms = SerialPortUtil.GetComList();
                if (!coms.Contains(strCom))
                {
                    string str = string.Format("未找到串口:{0}", strCom);
                    PrintLog.LogText(string.Format(str));
#if TEST
                    OutputDebugString(str);
#endif
                    return(false);
                }

                if (dictionarySerialPort.ContainsKey(strCom))
                {
                    serialPort = dictionarySerialPort[strCom];
                }
                else
                {
                    serialPort = new SerialPortUtil(strCom, nBaudrate.ToString(), "0", "8", "1");
                    dictionarySerialPort.Add(strCom, serialPort);
                }

                serialPort.OpenPort();
            }
            catch
            {
                return(false);
            }

            if (serialPort.IsOpen)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#9
0
        /// <summary>
        /// 保存邮箱信息
        /// </summary>
        /// <param name="SendUserName"></param>
        /// <param name="SendUserPass"></param>
        /// <param name="SendStmp"></param>
        /// <param name="SendToMail"></param>

        internal static void SaveMailInfo(string SendUserName, string SendUserPass, string SendStmp, string SendToMail)
        {
            try
            {
                SendCatMailInfo product = new SendCatMailInfo()
                {
                    UserName = SendUserName,
                    UserPass = SendUserPass,
                    Stmp     = SendStmp
                    ,
                    ToMail = SendToMail
                };

                string json = JsonConvert.SerializeObject(product);
                FileHelper.WriteUTF8Text(StaticValue.BinPath + "Mail.json", json);
            }
            catch (Exception ex) {
                PrintLog.Log(ex);
            }
        }
示例#10
0
 private void Print(string text)
 {
     if (this.richTextBox1.InvokeRequired) // 如果调用控件的线程和创建创建控件的线程不是同一个则为True
     {
         while (!this.richTextBox1.IsHandleCreated)
         {
             // 解决窗体关闭时出现“访问已释放句柄“的异常
             if (this.richTextBox1.Disposing || this.richTextBox1.IsDisposed)
             {
                 return;
             }
         }
         PrintLog d = new PrintLog(Print);
         this.richTextBox1.Invoke(d, new object[] { text });
     }
     else
     {
         string past = this.richTextBox1.Text;
         this.richTextBox1.Text = DateTime.Now + ": " + text + "\r\n" + past;
     }
 }
示例#11
0
        public SyncClient(string address, string port, string user_name, string password, string local_base_dir, Encoding encoding, string remote_sync_dir = null, bool deleteRemote = false)
        {
            PrintEventHandler = new PrintLog(PrintOut);

            try
            {
                connection.ServerAddress = address;
                connection.ServerPort = Convert.ToInt32(port);
                connection.UserName = user_name;
                connection.Password = password;
                connection.LocalDirectory = local_base_dir;
                this.local_base_dir = local_base_dir;
                connection.ConnectMode = FTPConnectMode.PASV;

                //remote_sync_dir
                if (encoding == null)
                {
                    connection.CommandEncoding = Encoding.GetEncoding("GBK");
                }
                else
                {
                    connection.CommandEncoding = encoding;
                }

                if (remote_sync_dir == null)
                {
                    remote_sync_dir = "/";
                }
                this.remote_sync_dir = remote_sync_dir;

                this.deleteRemote = deleteRemote;

                connection.AutoLogin = true;
            }
            catch (Exception e)
            {
                log.Info("配置有问题");
                log.Error(e);
            }
        }
示例#12
0
        public async Task <bool> RePrintMA(int maID, int userID)
        {
            var ma = (await _maService.FindByAsync(x => x.ID == maID)).FirstOrDefault();

            Domain.Document.Document document = null;

            if ((bool)ma?.IsNotificationType && ma?.MAStatus.MAStatusCode == "APR")
            {
                document = await _generateDocument.GenerateRegistrationPDFDocument(_nodeServices, ma.ID, "NOTAPR", userID);
            }
            else
            {
                document = await _generateDocument.GenerateRegistrationPDFDocument(_nodeServices, ma.ID, ma.MAStatus.MAStatusCode, userID);
            }
            var log = new PrintLog()
            {
                PrintedByUserID = userID,
                DocumentID      = document.ID,
                PrintedDate     = DateTime.Now
            };

            return(await _printLog.CreateAsync(log));
        }
示例#13
0
 /// <summary>
 /// 初始化扫描
 /// </summary>
 /// <param name="UserDataJson"></param>
 private static void InitScanner(string UserDataJson)
 {
     try
     {
         string ReadJson = FileHelper.ReadContextUtf8(StaticValue.UserInfoPath + UserDataJson + ".json");
         Tool.AddSite.AddHelper.UserData ALLJson = JsonConvert.DeserializeObject <Tool.AddSite.AddHelper.UserData>(ReadJson);
         string        Shtml    = WebHelper.HttpGet(ALLJson.WebLink1);
         List <string> TempList = HtmlHelper.GetLinkVlaueList(Shtml, ALLJson.Xpath1);
         foreach (string Line in TempList)
         {
             string Temptext = Line + DateTime.Now.ToString("yyyyMMdd");
             if (!StaticValue.LogList.Contains(Temptext))
             {
                 Console.WriteLine("加入{0}", Line);
                 PrintLog.ReflushLog(StaticValue.UrlLogFile, StaticValue.LogList, Temptext);
                 FileHelper.AppendUTF8Text(StaticValue.SiteLogFloderPath + UserDataJson + DateTime.Now.ToString("yyyyMMdd"), Temptext);
             }
         }
     }
     catch (Exception ex) {
         PrintLog.Log(ex);
     }
 }
示例#14
0
        public async Task <PhysicalFileResult> PrintPhysicalFile(int documentID, int userID)
        {
            try {
                var document = await base.GetAsync(documentID);

                var filePath = $"{_rootUrl}{document.FilePath}";
                //override path
                filePath = filePath.Replace('\\', Path.DirectorySeparatorChar);
                var result = new PhysicalFileResult(filePath, document.FileType);

                var printlog = new PrintLog {
                    PrintedByUserID = userID,
                    DocumentID      = documentID,
                    PrintedDate     = DateTime.UtcNow,
                };

                await _printLog.CreateAsync(printlog);

                return(result);
            } catch (Exception ex) {
                _logger.Log(ex);
            }
            return(null);
        }
 public void SetUp()
 {
     _seperationChecker = NSubstitute.Substitute.For <iSeperationChecker>();
     _uut = new PrintLog(_seperationChecker);
 }
示例#16
0
 private void writePrintLog(Session session, string beginNo, string endNo, string descr,  string templateName)
 {
       var printRep = RepositoryFactory.GetInstance().GetRepository<IPrintLogRepository, PrintLog>();  
         var item = new PrintLog
         {
             Name = "AT",
             BeginNo = beginNo,
             EndNo = endNo,
             Descr = descr,
             Station = this.Station,
             LabelTemplate = templateName,
             Cdt = DateTime.Now,
             Editor = this.Editor
         };
        
         printRep.Add(item, session.UnitOfWork);           
 }
示例#17
0
        /// <summary>
        /// 获取DCode
        /// </summary>
        /// <param name="executionContext"></param>
        /// <returns></returns>
        protected internal override ActivityExecutionStatus DoExecute(ActivityExecutionContext executionContext)
        {
            IProductRepository productRep = RepositoryFactory.GetInstance().GetRepository<IProductRepository, IProduct>();
            IDeliveryRepository deliveryRep = RepositoryFactory.GetInstance().GetRepository<IDeliveryRepository, Delivery>();
            IModelRepository modelRep = RepositoryFactory.GetInstance().GetRepository<IModelRepository, Model>();
            IPizzaRepository pizzaRep = RepositoryFactory.GetInstance().GetRepository<IPizzaRepository, Pizza>();
            ICOAStatusRepository coaRep = RepositoryFactory.GetInstance().GetRepository<ICOAStatusRepository, COAStatus>();
            IPrintLogRepository printLogRep = RepositoryFactory.GetInstance().GetRepository<IPrintLogRepository, PrintLog>();

            Product curProduct = (Product)CurrentSession.GetValue(Session.SessionKeys.Product);
            Delivery curDn = (Delivery)CurrentSession.GetValue(Session.SessionKeys.Delivery);
            string pizzaID = (string)CurrentSession.GetValue(Session.SessionKeys.PizzaID);
            string coaSN = (string)CurrentSession.GetValue(Session.SessionKeys.COASN);
            string curEditor = "";
            string curStation = "";

            if (!string.IsNullOrEmpty(this.Editor))
            {
                curEditor = this.Editor;
            }
            if (!string.IsNullOrEmpty(this.Station))
            {
                curStation = this.Station;
            }

            if (!curProduct.IsBT)
            {
                //Update Product – Combine DN
                //Product.DeliveryNo – Delivery No (from UI)
                bool bindFlag = false;
                curProduct.DeliveryNo = curDn.DeliveryNo;
                Delivery newDn = null;
                IList<string> proList = new List<string>();
                proList.Add(curProduct.ProId);
                bindFlag = productRep.BindDN(curDn.DeliveryNo, proList, curDn.Qty);
                while (!bindFlag)
                {
                    newDn = GetNextDelivery(curProduct);
                    if (newDn == null)
                    {
                        FisException fe = new FisException("PAK103", new string[] { });   //没找到可分配的delivery
                        throw fe;
                    }
                    else
                    {
                        bindFlag = productRep.BindDN(newDn.DeliveryNo, proList, newDn.Qty);
                    }
                }
                if (newDn != null)
                {
                    curDn = newDn;
                    curProduct.DeliveryNo = curDn.DeliveryNo;
                    CurrentSession.AddValue(Session.SessionKeys.Delivery, curDn);
                }

                int dvQty = productRep.GetCombinedQtyByDN(curDn.DeliveryNo);
                if (dvQty == curDn.Qty)
                {
                    curDn.Status = "87";
                    deliveryRep.Update(curDn, CurrentSession.UnitOfWork);
                }
            }

            //3.	如果有绑定COA,则需要完成如下操作
            //a)	Insert Product_Part - Combine COA 
            //b)	Update COAStatus - Update COA Status
            //      COAStatus.Status = 'A1'
            //c)	Insert COALog – Insert COA Log
            //      COASN – COA
            //      Line – 当前绑定的Customer S/N
            //      Station – 'A1'
            if (!string.IsNullOrEmpty(coaSN))
            {
                ProductPart coaPart = (ProductPart)CurrentSession.GetValue("COAPart");
                IPart bomPart = (IPart)CurrentSession.GetValue("COABOMPart");
                COAStatus reCOA = coaRep.Find(coaSN);

                IProductPart bindPart = new ProductPart();
                bindPart.ProductID = curProduct.ProId;
                bindPart.PartID = bomPart.PN;
                bindPart.PartSn = coaSN;
                bindPart.Cdt = DateTime.Now;
                bindPart.BomNodeType = "P1";
                bindPart.PartType = bomPart.Type;
                bindPart.CustomerPn = bomPart.CustPn;
                bindPart.Editor = curEditor;
                bindPart.Station = curStation;
                bindPart.CheckItemType = "";
                bindPart.Iecpn = "";
                curProduct.AddPart(bindPart);

                reCOA.Status = "A1";
                reCOA.Editor = curEditor;
                coaRep.UpdateCOAStatusDefered(CurrentSession.UnitOfWork, reCOA);

                COALog newItem = new COALog();
                newItem.COASN = coaSN;
                newItem.LineID = curProduct.CUSTSN;
                newItem.Editor = Editor;
                newItem.StationID = "A1";
                newItem.Tp = "";
                coaRep.InsertCOALogDefered(CurrentSession.UnitOfWork, newItem);
            }

            //7.Insert IMES_PAK..Pizza / IMES_PAK..PizzaStatus / 
            //IMES_PAK..Pizza.MMIID = ''
            //IMES_PAK..PizzaStatus.Station = '00'

            Pizza CurrentPizza = new Pizza();
            PizzaStatus currentPizzaStatus = new PizzaStatus();

            currentPizzaStatus.Editor = this.Editor;
            if (null == this.Line)
            {
                currentPizzaStatus.LineID = "";
            }
            else
            {
                currentPizzaStatus.LineID = this.Line;
            }
            currentPizzaStatus.PizzaID = pizzaID;
            currentPizzaStatus.StationID = "00";

            CurrentPizza.PizzaID = pizzaID;
            CurrentPizza.MMIID = "";
            CurrentPizza.Status = currentPizzaStatus;

            pizzaRep.Add(CurrentPizza, CurrentSession.UnitOfWork);

            //8.Update Product – Combine Pizza Id
            //Product.PizzaID – Pizza ID         
            curProduct.PizzaID = pizzaID;
            productRep.Update(curProduct, CurrentSession.UnitOfWork);

            //Model 的第10,11码是”29” 或者”39” 的产品是出货日本的产品;否则,是非出货日本的产品
            string jpmodel = curProduct.Model.Substring(9, 2);
            bool jpflag = false;

          //  if (jpmodel == "29" || jpmodel == "39")
            if((jpmodel == "29" || jpmodel == "39") && CheckJapanByPart(curProduct.Model))
            {
                jpflag = true;
            }

            //IMES_GetData..PrintLog
            var item = new PrintLog
            {
                Name = "PIZZA Label-1",
                BeginNo = curProduct.CUSTSN,
                EndNo = curProduct.CUSTSN,
                Descr = "PIZZA Label-1",
                Editor = this.Editor
            };

            printLogRep.Add(item, CurrentSession.UnitOfWork);

            //出货日本在列印列印Pizza Label 后,还需要列印Japan Pizza Label 
            if (jpflag)
            {
                var jitem = new PrintLog
                {
                    Name = "PIZZA Label-2",
                    BeginNo = curProduct.CUSTSN,
                    EndNo = curProduct.CUSTSN,
                    Descr = "PIZZA Label-2",
                    Editor = this.Editor
                };
                printLogRep.Add(jitem, CurrentSession.UnitOfWork);
            }
            if (curProduct.IsBT)
            {
                var btitem = new PrintLog
                {
                    Name = "BT COO Label",
                    BeginNo = curProduct.CUSTSN,
                    EndNo = curProduct.CUSTSN,
                    Descr = "BT COO Label",
                    Editor = this.Editor
                };
                printLogRep.Add(btitem, CurrentSession.UnitOfWork);
            }
            CurrentSession.AddValue("JPFlag", jpflag);

            return base.DoExecute(executionContext);
        }
示例#18
0
        /// <summary>
        /// IMES_PAK..Delivery.Status = '87'
        /// </summary>
        /// <param name="line">line</param>
        /// <param name="editor">editor</param>
        /// <param name="station">station</param>
        /// <param name="customer">customer</param>
        /// <param name="DN">DN</param>
        /// <param name="custSN">custSN</param>
        /// <param name="coaSN">coaSN</param>
        /// <param name="printItems"></param> 
        public ArrayList UpdateDeliveryStatusAndPrint(string line, string editor, string station, string customer, string DN, string custSN, string coaSN, IList<PrintItem> printItems)
        {
            ArrayList retList = new ArrayList();
            
            string keyStr = "";
            IList<string> productList = new List<string>();

			string IsBSamModel = "N";
            Session currentSession = null;
			
            try 
            {
                if (null == line)
                {
                    line = "";
                }
                if (null == station)
                {
                    station = "";
                }
                if (null == editor)
                {
                    editor = "";
                }
                if (null == customer)
                {
                    customer = "";
                }
                var currentProduct = CommonImpl.GetProductByInput(custSN, CommonImpl.InputTypeEnum.CustSN);
                if (null == currentProduct)
                {
                    List<string> errpara = new List<string>();

                    errpara.Add(custSN);
                    throw new FisException("SFC002", errpara);
                }
                productList.Add(((IProduct)currentProduct).ProId);
                
                Delivery reDelivery = currentRepository.Find(DN);
                
                S_RowData_Product productInfo = GetProductOnly(custSN);
                string sessionKey = custSN;
                keyStr = sessionKey;
                currentSession = new Session(sessionKey, SessionType, editor, station, line, customer);
                Dictionary<string, object> wfArguments = new Dictionary<string, object>();
                wfArguments.Add("Key", sessionKey);
                wfArguments.Add("Station", station);
                wfArguments.Add("CurrentFlowSession", currentSession);
                wfArguments.Add("Editor", editor);
                wfArguments.Add("PdLine", line);
                wfArguments.Add("Customer", customer);
                wfArguments.Add("SessionType", SessionType);

                string wfName, rlName;
                RouteManagementUtils.GetWorkflow(station, "CombineCOAandDNAndPrint.xoml", "combinecoaanddnandprint.rules", out wfName, out rlName);
                WorkflowInstance instance = WorkflowRuntimeManager.getInstance.CreateXomlFisWorkflow(wfName, rlName, wfArguments);
                currentSession.AddValue(Session.SessionKeys.COASN, coaSN);
                if (currentProduct.IsBT)
                {
                    currentSession.AddValue(Session.SessionKeys.IsBT, true);
                }
                else
                {
                    currentSession.AddValue(Session.SessionKeys.IsBT, false);
                }
                if (productInfo.isCDSI == "true")
                {
                    currentSession.AddValue(Session.SessionKeys.Pno, productInfo.isFactoryPo);
                }
                currentSession.AddValue(Session.SessionKeys.CustSN, custSN);
                currentSession.AddValue(Session.SessionKeys.DeliveryNo, DN);
                currentSession.AddValue(Session.SessionKeys.Product, currentProduct);
                currentSession.AddValue(Session.SessionKeys.Delivery, reDelivery);
                currentSession.AddValue(Session.SessionKeys.ReturnStation, "1");
                currentSession.AddValue(Session.SessionKeys.IsComplete, true);
                currentSession.AddValue(Session.SessionKeys.PrintItems, printItems);

                BSamModel bsamModel = bsamRepository.GetBSamModel(currentProduct.Model);
                if (bsamModel != null)
                {
                    IsBSamModel = "Y";
                }
				currentSession.AddValue(ExtendSession.SessionKeys.IsBSamModel, IsBSamModel);
                
                currentSession.SetInstance(instance);
                if (!SessionManager.GetInstance.AddSession(currentSession))
                {
                    currentSession.WorkflowInstance.Terminate("Session:" + sessionKey + " Exists.");
                    
                }
                currentSession.WorkflowInstance.Start();
                currentSession.SetHostWaitOne();
                if (currentSession.Exception != null)
                {
                    if (currentSession.GetValue(Session.SessionKeys.WFTerminated) != null)
                    {
                        currentSession.ResumeWorkFlow();
                    }

                    throw currentSession.Exception;
                }
                bool jpflag = false;
                IList<PrintItem> printList = (IList<PrintItem>)currentSession.GetValue(Session.SessionKeys.PrintItems);
                string QCIs = "noqcis";
                try
                {
                    // mantis 1945: JameStown新机型; OfflinePizzaFamily 區別是否需要Pizza Id及 PizzaID Label(不需要打印)
                    bool isOfflinePizzaFamily = "Y".Equals( currentSession.GetValue("OfflinePizzaFamily") as string);
                    if (printList != null)
                    {
                        if (isOfflinePizzaFamily) // JameStown , 不印: PIZZA Label
                        {
                            IList<PrintItem> printListWithoutPizzaLabel = new List<PrintItem>();
                            foreach (PrintItem pi in printList)
                            {
                                if (pi.LabelType.IndexOf("PIZZA Label") < 0)
                                    printListWithoutPizzaLabel.Add(pi);
                            }
                            printList = printListWithoutPizzaLabel;
                        }
                        else // 一般 , 不印: L10_LABEL
                        {
                            IList<PrintItem> printListWithoutPizzaLabel = new List<PrintItem>();
                            foreach (PrintItem pi in printList)
                            {
                                if (pi.LabelType.IndexOf("L10_LABEL") < 0)
                                    printListWithoutPizzaLabel.Add(pi);
                            }
                            printList = printListWithoutPizzaLabel;
                        }
                    }

                    IUnitOfWork uow = new UnitOfWork();
                    var repository = RepositoryFactory.GetInstance().GetRepository<IPrintLogRepository, PrintLog>();
                    if (isOfflinePizzaFamily) // JameStown
                    {
                        var item = new PrintLog
                        {
                            Name = "L10_LABEL",
                            BeginNo = custSN,
                            EndNo = custSN,
                            Descr = "",
                            Editor = editor
                        };
                        repository.Add(item, uow);
                    }
                    else // 一般
                    {
                        var item = new PrintLog
                        {
                            Name = "PIZZA Label-1",
                            BeginNo = custSN,
                            EndNo = custSN,
                            Descr = "",
                            Editor = editor
                        };
                        repository.Add(item, uow);
                    }
                    if (currentProduct.IsBT)
                    {
                        var item = new PrintLog
                        {
                            Name = "BT COO Label",
                            BeginNo = custSN,
                            EndNo = custSN,
                            Descr = "",
                            Editor = editor
                        };
                        repository.Add(item, uow);
                    }

                    string DNTemp = (string)currentSession.GetValue(Session.SessionKeys.DeliveryNo);
                    logger.Debug("(_CombineCOAandDN)UpdateDeliveryStatus DNTemp:" + DNTemp);
                    logger.Debug("(_CombineCOAandDN)UpdateDeliveryStatus DN:" + DN);

                    if (DN != DNTemp)
                    {
                        QCIs = QCIs + "#@$#" + DNTemp;
                    }


                    //Model 的第10,11码是”29” 或者”39” 的产品是出货日本的产品;否则,是非出货日本的产品
                    string jpmodel = currentProduct.Model.Substring(9, 2);

                  //  if (jpmodel == "29" || jpmodel == "39")
                    if ((jpmodel == "29" || jpmodel == "39") && CheckJapanByPart(currentProduct.Model) && (!isOfflinePizzaFamily))
                    {
                        jpflag = true;
                        var item = new PrintLog
                        {
                            Name = "PIZZA Label-2",
                            BeginNo = custSN,
                            EndNo = custSN,
                            Descr = "",
                            Editor = editor
                        };
                        repository.Add(item, uow);
                    }
                    uow.Commit();
                }
                catch (FisException e)
                {
                    logger.Error(e.Message);
                }
                catch (Exception e)
                {
                    logger.Error(e.Message);
                }
                retList.Add(printList);
                retList.Add(jpflag);
                retList.Add(QCIs);

                string locId = "";
                BSamLocation loc = currentSession.GetValue(ExtendSession.SessionKeys.BSamLoc) as BSamLocation;
                if ("Y".Equals(IsBSamModel) && (null != loc))
                {
                    locId = loc.LocationId.ToString();
                }
                retList.Add(locId);

                //MergeCode  from Add PAQC result
                var qcObj = currentSession.GetValue(Session.SessionKeys.QCStatus);
                if (qcObj != null && (bool)qcObj)
                { 
                    retList.Add("P"); 
                }
                else
                { 
                    retList.Add(""); 
                }
                //Add PAQC result

                return retList;
            }
            catch (FisException e)
            {
                productRepository.BindDN("", productList);
                logger.Error(e.mErrmsg);
				if ((null != currentSession) && "Y".Equals(IsBSamModel)) {
					BSamLocation loc = currentSession.GetValue(ExtendSession.SessionKeys.BSamLoc) as BSamLocation;
                    RollbackBsamLoc(loc, editor);
				}
                throw e;
            }
            catch (Exception e)
            {
                productRepository.BindDN("", productList);
                logger.Error(e.Message);
                if ((null != currentSession) && "Y".Equals(IsBSamModel))
                {
                    BSamLocation loc = currentSession.GetValue(ExtendSession.SessionKeys.BSamLoc) as BSamLocation;
                    RollbackBsamLoc(loc, editor);
                }
                throw e;
            }
            finally
            {
                Session sessionDelete = SessionManager.GetInstance.GetSession(keyStr, SessionType);
                if (sessionDelete != null)
                {
                    SessionManager.GetInstance.RemoveSession(sessionDelete);
                }
                logger.Debug("(_CombineCOAandDN)UpdateDeliveryStatusAndPrint end, DN:" + DN);
            }
        }
        public static string SendCMDStrToController(byte[] bytes, string strCom, int nBaudrate, int nCount = 0, int nOffset = 0)
        {
            SerialPortUtil serialPort;

            if (strCom == null)
            {
                return(null);
            }
            try
            {
                lock (ojbSend)
                {
                    //1.初始化串口
                    if (false == InitSerialPort(strCom, out serialPort, nBaudrate))
                    {
                        return(null);
                    }
                    serialPort.DiscardBuffer();

                    //2.发送数据
                    string strSendCMD = Encoding.ASCII.GetString(bytes, 0, bytes.Length);
                    PrintLog.LogText(string.Format("{0} Send: {1}", strCom, strSendCMD));

                    readstring = string.Empty; //清空接收缓冲区
                    Thread SendCmdToControllerThread = new Thread(() =>
                    {
                        try
                        {
                            if (!serialPort.IsOpen)
                            {
                                serialPort.OpenPort();
                            }
#if TEST
#else
                            serialPort.DataReceived += new DataReceivedEventHandler(serialPort_DataReceived);
#endif
                            readstring = string.Empty;
                            //写数据
                            if (nCount == 0 && nOffset == 0)
                            {
                                serialPort.WriteData(bytes);
                            }
                            else
                            {
                                serialPort.WriteData(bytes, nOffset, nCount);
                            }
                        }
                        catch (Exception ex)
                        {
                            if (serialPort != null && serialPort.IsOpen)  //关闭端口
                            {
                                serialPort.ClosePort();
                            }
                            dictionarySerialPort.Remove(strCom);
                            serialPort = null;
                        }
                        finally
                        {
                            if (serialPort != null)
                            {
                                if (serialPort.IsOpen == true)
                                {
                                    serialPort.ClosePort();
                                }
                            }

                            serialPort = null;
                        }
                    });

                    SendCmdToControllerThread.IsBackground = true;
                    SendCmdToControllerThread.Start();

                    //根据命令与底层控制器之间的繁忙时间,适当增加延时,一般不用

                    ReceiveDataTimeOut(bytes);


                    //回读数据超时,已经等到数据,返回
                    if (string.Empty == readstring)
                    {
                        return(null);
                    }
                    PrintLog.LogText(string.Format("{0} Receive :{1}", strCom, readstring));
                }
            }
            catch (System.ArgumentNullException ex)
            {
                PrintLog.LogText(string.Format("{0} Receive Error: ArgumentNullException", strCom));
                return(null);
            }
            catch (Exception e)
            {
                PrintLog.LogText(string.Format("{0} Receive Error: Exception", strCom));
                return(null);
            }
            return(readstring);
        }
示例#20
0
        public ActionResult Save(LotPrintViewModel model)
        {
            MethodReturnResult result = new MethodReturnResult();

            try
            {
                //获取批值。
                result = GetLot(model);
                if (result.Code > 0)
                {
                    return(Json(result));
                }
                //获取打印机名称
                ClientConfig printer = null;
                using (ClientConfigServiceClient client = new ClientConfigServiceClient())
                {
                    MethodReturnResult <ClientConfig> rst = client.Get(model.PrinterName);
                    if (rst.Code > 0)
                    {
                        return(Json(rst));
                    }
                    printer = rst.Data;
                }
                //获取打印条码内容
                PrintLabel label = null;
                using (PrintLabelServiceClient client = new PrintLabelServiceClient())
                {
                    MethodReturnResult <PrintLabel> rst = client.Get(model.PrintLabelCode);
                    if (rst.Code > 0)
                    {
                        return(Json(rst));
                    }
                    label = rst.Data;
                }

                IList <Lot> lst = (result as MethodReturnResult <IList <Lot> >).Data;
                //打印动态内容。
                dynamic d = new ExpandoObject();
                d.PrintQty = model.PrintQty;
                bool     bSuccess   = false;
                DateTime PrintStart = DateTime.Now;

                using (IPrintHelper helper = PrintHelperFactory.CreatePrintHelper(label.Content))
                {
                    //根据打印机类型,调用不同的打印方法。
                    if (printer.ClientType == EnumClientType.NetworkPrinter)
                    {
                        string[] vals = printer.IPAddress.Split(':');
                        string   port = "9100";

                        if (vals.Length > 1)
                        {
                            port = vals[1];
                        }

                        foreach (Lot obj in lst)
                        {
                            PrintStart = DateTime.Now;          //打印开始时间

                            d.LotNumber = obj.Key.ToString().ToUpper().Trim();
                            bSuccess    = helper.NetworkPrint(vals[0], port, label.Content, d);

                            //打印日志
                            using (PrintLogServiceClient client = new PrintLogServiceClient())
                            {
                                PrintLog logobj = new PrintLog()
                                {
                                    LotNumber      = obj.Key,                             //批次号
                                    ClientName     = Request.UserHostAddress,             //客户端
                                    PrintQty       = model.PrintQty,                      //打印数量
                                    PrintLabelCode = model.PrintLabelCode,                //打印标签代码
                                    PrinterName    = model.PrinterName,                   //打印机名称
                                    PrintType      = printer.ClientType.GetDisplayName(), //打印机类型
                                    IsSucceed      = true,                                //打印是否成功
                                    PrintData      = "",                                  //打印数据
                                    Creator        = User.Identity.Name,                  //创建人
                                    CreateTime     = PrintStart,                          //创建日期
                                    FinishTime     = DateTime.Now                         //编辑日期
                                };

                                result = client.Add(logobj);

                                if (result.Code > 0)
                                {
                                    return(Json(result));
                                }
                            }
                        }
                    }
                    else if (printer.ClientType == EnumClientType.RawPrinter)
                    {
                        foreach (Lot obj in lst)
                        {
                            PrintStart = DateTime.Now;          //打印开始时间

                            d.LotNumber = obj.Key;
                            bSuccess    = helper.RAWPrint(printer.IPAddress, label.Content, d);

                            //打印日志
                            using (PrintLogServiceClient client = new PrintLogServiceClient())
                            {
                                PrintLog logobj = new PrintLog()
                                {
                                    LotNumber      = obj.Key.ToString().ToUpper().Trim(), //批次号
                                    ClientName     = Request.UserHostAddress,             //客户端
                                    PrintQty       = model.PrintQty,                      //打印数量
                                    PrintLabelCode = model.PrintLabelCode,                //打印标签代码
                                    PrinterName    = model.PrinterName,                   //打印机名称
                                    PrintType      = printer.ClientType.GetDisplayName(), //打印机类型
                                    IsSucceed      = true,                                //打印是否成功
                                    PrintData      = "",                                  //打印数据
                                    Creator        = User.Identity.Name,                  //创建人
                                    CreateTime     = PrintStart,                          //创建日期
                                    FinishTime     = DateTime.Now                         //编辑日期
                                };

                                result = client.Add(logobj);

                                if (result.Code > 0)
                                {
                                    return(Json(result));
                                }
                            }
                        }
                    }
                    else
                    {
                        result.Code    = 1001;
                        result.Message = "打印失败,打印机类型不正确。";
                        return(Json(result));
                    }
                }

                //返回打印结果。
                if (bSuccess == false)
                {
                    result.Code    = 1001;
                    result.Message = string.Format("批次 {0} - {1} 打印失败。", model.LotNumber, model.LotNumber1);
                }
                else
                {
                    result.Message = string.Format("批次 {0} - {1} 打印操作成功。", model.LotNumber, model.LotNumber1);
                }
            }
            catch (Exception ex)
            {
                result.Code    = 1000;
                result.Message = ex.Message;
                result.Detail  = ex.ToString();
            }
            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(Json(result));
        }
示例#21
0
        public ArrayList Reprint(string mbsn, string reason, string line, string editor,
                                    string station, string customer, IList<PrintItem> printItems)
        {
            logger.Debug("(CombineCartonDNfor146MB)Reprint Start,"
                            + " [mbsn]:" + mbsn
                            + " [line]:" + line
                            + " [editor]:" + editor
                            + " [station]:" + station
                            + " [customer]:" + customer);

            try
            {
                List<string> erpara = new List<string>();
                FisException ex;

                IMBRepository mbRepository = RepositoryFactory.GetInstance().GetRepository<IMBRepository, IMB>();
                IMB mb = mbRepository.Find(mbsn);
                if (mb == null)
                {
                    throw new FisException("SFC001", new string[] { mbsn });
                }

                if (string.IsNullOrEmpty(mb.CartonSN))
                {
                    // 此 MB 的 CartonSN 為空
                    throw new FisException("CQCHK0029", new string[] {  });
                }

                string cartonSn = mb.CartonSN;

                //Check Print Log
                var repository = RepositoryFactory.GetInstance().GetRepository<IPrintLogRepository, PrintLog>();

                PrintLog condition = new PrintLog();
                condition.Name = printItems[0].LabelType;
                condition.BeginNo = cartonSn;
                condition.Descr = "MBCT";
                IList<PrintLog> printLogList = repository.GetPrintLogListByCondition(condition);
                if (printLogList.Count == 0)
                {
                    ex = new FisException("CHK270", erpara);
                    throw ex;
                }

                //Check Print Log
                string sessionKey = mbsn;
                Session currentSession = SessionManager.GetInstance.GetSession(sessionKey, TheType);
                if (currentSession == null)
                {
                    currentSession = new Session(sessionKey, TheType, editor, station, line, customer);
                    Dictionary<string, object> wfArguments = new Dictionary<string, object>();
                    wfArguments.Add("Key", sessionKey);
                    wfArguments.Add("Station", station);
                    wfArguments.Add("CurrentFlowSession", currentSession);
                    wfArguments.Add("Editor", editor);
                    wfArguments.Add("PdLine", line);
                    wfArguments.Add("Customer", customer);
                    wfArguments.Add("SessionType", TheType);
                    string wfName, rlName;
                    RouteManagementUtils.GetWorkflow(station, "RePrint.xoml", string.Empty, out wfName, out rlName);
                    WorkflowInstance instance = WorkflowRuntimeManager.getInstance.CreateXomlFisWorkflow(wfName, rlName, wfArguments);

                    currentSession.AddValue(Session.SessionKeys.PrintItems, printItems);

                    currentSession.AddValue(Session.SessionKeys.PrintLogName, printItems[0].LabelType);
                    currentSession.AddValue(Session.SessionKeys.PrintLogBegNo, cartonSn);
                    currentSession.AddValue(Session.SessionKeys.PrintLogEndNo, cartonSn);
                    currentSession.AddValue(Session.SessionKeys.PrintLogDescr, "MBCT");
                    currentSession.AddValue(Session.SessionKeys.Reason, reason);

                    //Session.AddValue(Session.SessionKeys.IsComplete, false);
                    currentSession.SetInstance(instance);

                    if (!SessionManager.GetInstance.AddSession(currentSession))
                    {
                        currentSession.WorkflowInstance.Terminate("Session:" + sessionKey + " Exists.");
                        erpara.Add(sessionKey);
                        ex = new FisException("CHK020", erpara);
                        throw ex;
                    }
                    currentSession.WorkflowInstance.Start();
                    currentSession.SetHostWaitOne();
                }
                else
                {
                    erpara.Add(sessionKey);
                    ex = new FisException("CHK020", erpara);
                    throw ex;
                }

                //check workflow exception
                if (currentSession.Exception != null)
                {
                    if (currentSession.GetValue(Session.SessionKeys.WFTerminated) != null)
                    {
                        currentSession.ResumeWorkFlow();
                    }
                    throw currentSession.Exception;
                }


                IList<PrintItem> returnList = (IList<PrintItem>)currentSession.GetValue(Session.SessionKeys.PrintItems);
                ArrayList arr = new ArrayList();
                arr.Add(returnList);
                arr.Add(cartonSn);
                return arr;

            }
            catch (FisException e)
            {
                logger.Error(e.mErrmsg);
                throw e;
            }
            catch (Exception e)
            {
                logger.Error(e.Message);
                throw new SystemException(e.Message);
            }
            finally
            {
                logger.Debug("(CombineCartonDNfor146MB)Reprint End,"
                                + " [mbsn]:" + mbsn
                                + " [line]:" + line
                                + " [editor]:" + editor
                                + " [station]:" + station
                                + " [customer]:" + customer);
            }
        }