Exemplo n.º 1
0
        public string UpdateBOM(JObject jo)
        {
            var bom = new BOM();

            bom.BOMCode            = jo["FBOMNumber"].ToString();
            bom.MaterielCode       = jo["fshortnumber"].ToString();
            bom.Version            = jo["FVersion"].ToString();
            bom.UseState           = jo["FStatus"].ToString();
            bom.MaterielQuantity   = jo["FQty"].ToString() == "" ? 0 : double.Parse(jo["FQty"].ToString());
            bom.MaterielUnit       = jo["FunitID"].ToString();
            bom.DetailCode         = jo["FEntryID"].ToString();
            bom.DetailMaterielCode = jo["detailfshortnumber"].ToString();
            bom.DetailQuantity     = jo["detailfqty"].ToString() == "" ? 0 : double.Parse(jo["FQty"].ToString());
            bom.DetailUnit         = jo["detailFUnitID"].ToString();
            bom.Flag        = 'U';
            bom.K3TimeStamp = DateTime.Parse(jo["FEnterTime"].ToString());
            bom.SourceDb    = "XG";
            //bom.ID = Guid.NewGuid().ToString();
            var importer = new BOMImporter();

            importer.Update(bom);
            return("Update BOM Success!");
        }
Exemplo n.º 2
0
        public bool AddORUpdateBOM(BOM bom)
        {
            var sql = new StringBuilder();

            if (bom.Id == 0)
            {
                sql.Clear();
                //添加
                sql.AppendLine("insert into bom (name,number,parent_id,belong_task,type,status,is_delete,description,version)");
                sql.AppendLine("values ('" + bom.Name + "','" + bom.Number + "','" + bom.Parent_Id + "','" + bom.Belong_Task + "',");
                sql.AppendLine("'" + bom.Type + "','" + bom.Status + "','" + bom.Is_Delete + "','" + bom.Description + "','" + bom.Version + "'");
                return(true);
            }
            else
            {
                //修改
                sql.Clear();
                sql.AppendLine("update bom set name='" + bom.Name + "',number='" + bom.Number + "',parent_id=" + bom.Parent_Id + ",");
                sql.AppendLine("belong_task='" + bom.Belong_Task + "',type='" + bom.Type + "',status='" + bom.Status + "',is_delete='" + bom.Is_Delete + "',");
                sql.AppendLine("description='" + bom.Description + "',version='" + bom.Version + "' where id=" + bom.Id + "");
                return(false);
            }
        }
Exemplo n.º 3
0
        private void ToggleCurrentPart()
        {
            BOM B = Main.GetBom();

            if (B == null)
            {
                return;
            }
            int i = 0;

            int pc = B.GetPartCount(new List <string>()
            {
            });

            CurrentPart = (CurrentPart + pc) % pc;

            foreach (var a in B.DeviceTree)
            {
                foreach (var v in a.Value.Values)
                {
                    if (i == CurrentPart)
                    {
                        v.Soldered = !v.Soldered;
                        if (v.Soldered)
                        {
                            Main.SolderPart(v.Combined());
                        }
                        else
                        {
                            Main.UnSolderPart(v.Combined());
                        }
                        return;
                    }
                    i++;
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 创建BOM
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddProjectBOM(object sender, EventArgs e)
        {
            if (bom != null)
            {
            }
            else
            {
                bom = new BOM
                {
                    Id          = Convert.ToInt32(txtProductName.Text),
                    Name        = txtProductName.Text,
                    Status      = "0",
                    Is_Delete   = "0",
                    Type        = "0",
                    Create_Date = Convert.ToDateTime(txtCreateDate.Text)
                };
            }
            var result = productStructService.AddORUpdateBOM(bom);

            if (result)
            {
                this.Hide();
            }
        }
Exemplo n.º 5
0
        public void FormUbahBOM_Load(object sender, EventArgs e)
        {
            comboBox2.Enabled = false;
            comboBox2.Items.Clear();
            comboBox1.Items.Clear();
            listHasilData.Clear();

            numericUpDownTotalBiaya.Value       = 0;
            numericUpDownBiayaOperasional.Value = 0;
            numericUpDownPengajuanHarga.Value   = 0;
            numericUpDownJumlahBagian.Value     = 0;
            numericUpDownJumlahSpesifik.Value   = 0;

            string hasil = BOM.BacaData("", "", listHasilData);

            if (hasil == "1")
            {
                string previd = "";
                for (int i = 0; i < listHasilData.Count; i++)
                {
                    if (listHasilData[i].Kodebarang != previd)
                    {
                        comboBox1.Items.Add(listHasilData[i].Kodebarang);
                    }

                    previd = listHasilData[i].Kodebarang;
                }
            }

            numericUpDownTotalBiaya.Enabled       = false;
            numericUpDownBiayaOperasional.Enabled = false;
            numericUpDownBiayaTukang.Enabled      = false;
            numericUpDownPengajuanHarga.Enabled   = false;
            numericUpDownJumlahBagian.Enabled     = false;
            numericUpDownJumlahSpesifik.Enabled   = false;
        }
        private void SearchSheetMetalKits(Component component)
        {
            try
            {
                AssemblyDocument assembly = (AssemblyDocument)inventorApp.Documents.Open(component.FullFileName, false);
                // Get BOM
                BOM bom = assembly.ComponentDefinition.BOM;
                bom.StructuredViewFirstLevelOnly = false;
                bom.StructuredViewEnabled        = true;
                // Set a reference to the "Structured" BOMView
                BOMView bomView = bom.BOMViews["Структурированный"];

                foreach (BOMRow row in bomView.BOMRows)
                {
                    ComponentDefinition componentDefinition = row.ComponentDefinitions[1];
                    if (!(componentDefinition is VirtualComponentDefinition))
                    {
                        if (componentDefinition is AssemblyComponentDefinition)
                        {
                            AssemblyDocument locAssembly = (AssemblyDocument)componentDefinition.Document;
                            string           filePath    = locAssembly.FullFileName;
                            // Check whether assembly in casing subdirectory
                            if (filePath.IndexOf(casingDirectory) >= 0)
                            {
                                ReNumberSheetMetalKit(locAssembly, row.ChildRows);
                            }
                        }
                    }
                }
                assembly.Close();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().Name, MessageBoxButton.OK);
            }
        }
Exemplo n.º 7
0
        private List <BOM> FillBOMModel1(ref Project pProjectModel)
        {
            List <BOM> LstObjBom = new List <BOM>();

            foreach (DataGridViewRow gvr in dataGridView1.Rows)
            {
                //string colName=gvr.Cells[0].OwningColumn.HeaderText;

                bool isAdd = false;
                for (int i = 0; i < gvr.Cells.Count; i++)
                {
                    //if (gvr.Cells[i].Value == null || gvr.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(gvr.Cells[i].Value.ToString()))
                    if (gvr.Cells[i].Value == null)
                    {
                        isAdd = false;
                    }
                    else
                    {
                        isAdd = true;
                        break;
                    }
                }

                //if (lObjBom.SORef != null && lObjBom.SerialNo != null && lObjBom.ProductCategory != null && lObjBom.Product != null && lObjBom.CostHead != null && lObjBom.CostSubHead != null
                //     && lObjBom.System != null && lObjBom.Area != null && lObjBom.Panel != null && lObjBom.Description != null && lObjBom.Qty != null && lObjBom.UnitCost != null
                //      && lObjBom.ExCost != null && lObjBom.UnitPrice != null && lObjBom.ExPrice != null)
                //if (!(string.IsNullOrEmpty( gvr.Cells[0].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[1].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[2].Value.ToString())
                //    && string.IsNullOrEmpty(gvr.Cells[3].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[4].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[5].Value.ToString())
                //    && string.IsNullOrEmpty(gvr.Cells[6].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[7].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[8].Value.ToString())
                //    && string.IsNullOrEmpty(gvr.Cells[9].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[10].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[11].Value.ToString())
                //    && string.IsNullOrEmpty(gvr.Cells[12].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[13].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[14].Value.ToString())
                //    && string.IsNullOrEmpty(gvr.Cells[15].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[16].Value.ToString()) && string.IsNullOrEmpty(gvr.Cells[17].Value.ToString())))

                if (isAdd == true)
                {
                    BOM lObjBom = new BOM();
                    //lObjBom.BOMCode = (string)gvr.Cells[0].Value;
                    lObjBom.BOMTypeCode = 1;//(string)gvr.Cells[0].Value;
                    lObjBom.ProjectCode = pProjectModel.ProjectCode;

                    lObjBom.SORef           = gvr.Cells[0].Value.ToString();
                    lObjBom.SerialNo        = gvr.Cells[1].Value.ToString();
                    lObjBom.ProductCategory = gvr.Cells[2].Value.ToString();
                    lObjBom.Product         = gvr.Cells[3].Value.ToString();
                    lObjBom.CostHead        = gvr.Cells[4].Value.ToString();
                    lObjBom.CostSubHead     = gvr.Cells[5].Value.ToString();
                    lObjBom.System          = gvr.Cells[6].Value.ToString();
                    lObjBom.Area            = gvr.Cells[7].Value.ToString();
                    lObjBom.Panel           = gvr.Cells[8].Value.ToString();
                    lObjBom.Category        = gvr.Cells[9].Value.ToString();
                    lObjBom.Manufacturer    = gvr.Cells[10].Value.ToString();
                    lObjBom.PartNo          = gvr.Cells[11].Value.ToString();
                    lObjBom.Description     = gvr.Cells[12].Value.ToString();
                    lObjBom.Qty             = gvr.Cells[13].Value.ToString();
                    lObjBom.UnitCost        = gvr.Cells[14].Value.ToString();
                    lObjBom.ExCost          = gvr.Cells[15].Value.ToString();
                    lObjBom.UnitPrice       = gvr.Cells[16].Value.ToString();
                    lObjBom.ExPrice         = gvr.Cells[17].Value.ToString();

                    LstObjBom.Add(lObjBom);
                    pProjectModel.BOMs.Add(lObjBom);
                }
            }
            return(LstObjBom);
        }
Exemplo n.º 8
0
        /// <summary>
        /// creation of a balloon. Select a linear drawing curve and run the sample
        /// </summary>
        /// <remarks></remarks>
        public void CreateBalloon()
        {
            // Set a reference to the drawing document.
            // This assumes a drawing document is active.
            DrawingDocument oDrawDoc = (DrawingDocument)_InvApplication.ActiveDocument;

            // Set a reference to the active sheet.
            Sheet oActiveSheet = oDrawDoc.ActiveSheet;

            // Set a reference to the drawing curve segment.
            // This assumes that a drwaing curve is selected.
            DrawingCurveSegment oDrawingCurveSegment = oDrawDoc.SelectSet[1];

            // Set a reference to the drawing curve.
            DrawingCurve oDrawingCurve = oDrawingCurveSegment.Parent;

            // Get the mid point of the selected curve
            // assuming that the selection curve is linear
            Point2d oMidPoint = oDrawingCurve.MidPoint;

            // Set a reference to the TransientGeometry object.
            TransientGeometry oTG = _InvApplication.TransientGeometry;

            ObjectCollection oLeaderPoints = _InvApplication.TransientObjects.CreateObjectCollection();

            // Create a couple of leader points.
            oLeaderPoints.Add(oTG.CreatePoint2d(oMidPoint.X + 10, oMidPoint.Y + 10));
            oLeaderPoints.Add(oTG.CreatePoint2d(oMidPoint.X + 10, oMidPoint.Y + 5));

            // Add the GeometryIntent to the leader points collection.
            // This is the geometry that the balloon will attach to.
            GeometryIntent oGeometryIntent = oActiveSheet.CreateGeometryIntent(oDrawingCurve);

            oLeaderPoints.Add(oGeometryIntent);

            // Set a reference to the parent drawing view of the selected curve
            DrawingView oDrawingView = oDrawingCurve.Parent;

            // Set a reference to the referenced model document
            Document oModelDoc = oDrawingView.ReferencedDocumentDescriptor.ReferencedDocument;

            // Check if a partslist or a balloon has already been created for this model
            bool IsDrawingBOMDefined = false;

            IsDrawingBOMDefined = oDrawDoc.DrawingBOMs.IsDrawingBOMDefined(oModelDoc.FullFileName);

            Balloon oBalloon = null;


            if (IsDrawingBOMDefined)
            {
                // Just create the balloon with the leader points
                // All other arguments can be ignored
                oBalloon = oDrawDoc.ActiveSheet.Balloons.Add(oLeaderPoints);
            }
            else
            {
                // First check if the 'structured' BOM view has been enabled in the model

                // Set a reference to the model's BOM object
                AssemblyDocument            oAssDoc = (AssemblyDocument)oModelDoc;
                AssemblyComponentDefinition oComDef = oAssDoc.ComponentDefinition;
                BOM oBOM = oComDef.BOM;


                if (oBOM.StructuredViewEnabled)
                {
                    // Level needs to be specified
                    // Numbering options have already been defined
                    // Get the Level ('All levels' or 'First level only')
                    // from the model BOM view - must use the same here
                    PartsListLevelEnum Level = default(PartsListLevelEnum);
                    if (oBOM.StructuredViewFirstLevelOnly)
                    {
                        Level = PartsListLevelEnum.kStructured;
                    }
                    else
                    {
                        Level = PartsListLevelEnum.kStructuredAllLevels;
                    }

                    // Create the balloon by specifying just the level
                    oBalloon = oActiveSheet.Balloons.Add(oLeaderPoints, null, Level);
                }
                else
                {
                    // Level and numbering options must be specified
                    // The corresponding model BOM view will automatically be enabled
                    NameValueMap oNumberingScheme = _InvApplication.TransientObjects.CreateNameValueMap();

                    // Add the option for a comma delimiter
                    oNumberingScheme.Add("Delimiter", ",");

                    // Create the balloon by specifying the level and numbering scheme
                    oBalloon = oActiveSheet.Balloons.Add(oLeaderPoints, null, PartsListLevelEnum.kStructuredAllLevels, oNumberingScheme);
                }
            }
        }
 public ActionResult detailMaterialFiche(BOM material)
 {
     return(RedirectToAction("materialDefinitions"));
 }
Exemplo n.º 10
0
        internal void Load(string basefile)
        {
            Text = Path.GetFileNameWithoutExtension(basefile);

            string fn         = Path.GetFileName(basefile);
            string basefolder = Path.GetDirectoryName(basefile);
            string name       = fn.Split('_')[0];

            string BOMFile    = "";
            string PnPFile    = "";
            string gerberFile = "";
            var    L          = Directory.GetFiles(basefolder, name + "_*.*");

            SolderFile = "";
            foreach (var file in L)
            {
                if (file.EndsWith("_BOM.csv"))
                {
                    BOMFile = file;
                }
                if (file.EndsWith("_gerbers.zip"))
                {
                    gerberFile = file;
                }
                if (file.EndsWith("_PNP.csv"))
                {
                    PnPFile = file;
                }
                if (file.EndsWith("_soldered.txt"))
                {
                    SolderFile = file;
                }
            }

            LayerSets.Add(new LayerSet()
            {
                Side = BoardSide.Both, Layer = BoardLayer.Outline
            });
            LayerSets.Add(new LayerSet()
            {
                Side = BoardSide.Top, Layer = BoardLayer.SolderMask
            });
            LayerSets.Add(new LayerSet()
            {
                Side = BoardSide.Top, Layer = BoardLayer.Silk
            });
            LayerSets.Add(new LayerSet()
            {
                Side = BoardSide.Bottom, Layer = BoardLayer.SolderMask
            });
            LayerSets.Add(new LayerSet()
            {
                Side = BoardSide.Bottom, Layer = BoardLayer.Silk
            });
            if (BOMFile.Length > 0 && PnPFile.Length > 0 && gerberFile.Length > 0)
            {
                BOM B = new BOM();
                B.LoadJLC(BOMFile, PnPFile);
                TheBOM = B;

                if (SolderFile.Length > 0)
                {
                    solderedlist = File.ReadAllLines(SolderFile).ToList();

                    foreach (var a in B.DeviceTree)
                    {
                        foreach (var v in a.Value.Values)
                        {
                            if (solderedlist.Contains(v.Combined()))
                            {
                                v.Soldered = true;
                            }
                        }
                    }
                }
                else
                {
                    SolderFile = Path.Combine(basefolder, name + "_soldered.txt");
                    SaveSolderedList();
                }


                GerberLibrary.GerberImageCreator GIC = new GerberLibrary.GerberImageCreator();

                List <string> res = new List <string>();
                Dictionary <string, MemoryStream> Files = new Dictionary <string, MemoryStream>();
                using (Ionic.Zip.ZipFile zip1 = Ionic.Zip.ZipFile.Read(gerberFile))
                {
                    foreach (ZipEntry e in zip1)
                    {
                        MemoryStream MS = new MemoryStream();
                        if (e.IsDirectory == false)
                        {
                            e.Extract(MS);
                            MS.Seek(0, SeekOrigin.Begin);
                            Files[e.FileName] = MS;
                        }
                    }
                }


                string[]      FileNames       = Files.Keys.ToArray();
                List <string> outlinefiles    = new List <string>();
                List <string> topsilkfiles    = new List <string>();
                List <string> bottomsilkfiles = new List <string>();

                foreach (var F in FileNames)
                {
                    BoardSide  BS = BoardSide.Unknown;
                    BoardLayer BL = BoardLayer.Unknown;
                    Files[F].Seek(0, SeekOrigin.Begin);
                    if (Gerber.FindFileTypeFromStream(new StreamReader(Files[F]), F) == BoardFileType.Gerber)
                    {
                        Gerber.DetermineBoardSideAndLayer(F, out BS, out BL);
                        foreach (var l in LayerSets)
                        {
                            if (l.Side == BS && l.Layer == BL)
                            {
                                l.Files.Add(F);
                                Files[F].Seek(0, SeekOrigin.Begin);
                                var pls = PolyLineSet.LoadGerberFileFromStream(new StandardConsoleLog(), new StreamReader(Files[F]), F, true, false, new GerberParserState()
                                {
                                    PreCombinePolygons = false
                                });
                                l.Gerbs.Add(pls);
                            }
                        }
                    }
                }
                TheBox.Reset();

                foreach (var a in LayerSets[0].Gerbs)
                {
                    TheBox.AddBox(a.BoundingBox);
                }
            }
        }
Exemplo n.º 11
0
 public ActionResult deleteBOMDefinition(BOM bom)
 {
     bom.Delete();
     return(RedirectToAction("bomDefinitions"));
 }
 public BOMController(BOM pBomModel)
 {
     interfaceObj = new ProcurementRepository <BOM>();
     _gBomModel   = pBomModel;
 }
Exemplo n.º 13
0
        public List <string> Write(string targetfolder, string basename, BOM inFiducialBom, PointD offset = null)
        {
            if (offset == null)
            {
                offset = new PointD(0, 0);
            }

            List <string> Files      = new List <string>();
            ExcellonFile  EF         = new ExcellonFile();
            int           drillcount = 0;

            foreach (var h in DrillHoles)
            {
                ExcellonTool DrillBit = new ExcellonTool();
                DrillBit.Radius = h.Key / 2.0f;

                foreach (var a in h.Value)
                {
                    DrillBit.Drills.Add(a);
                }
                EF.Tools[10 + drillcount] = DrillBit;
                drillcount++;
            }
            string DrillFile = Path.Combine(targetfolder, basename + ".txt");

            EF.Write(DrillFile, offset.X, offset.Y, 0, 0);
            Files.Add(DrillFile);

            string OutName = Path.Combine(targetfolder, basename);

            Outline.Write(OutName + ".gko", offset); Files.Add(OutName + ".gko");
            TopSilk.Write(OutName + ".gto", offset); Files.Add(OutName + ".gto");
            TopCopper.Write(OutName + ".gtl", offset); Files.Add(OutName + ".gtl");

            TopSolderMask.Write(OutName + ".gts", offset); Files.Add(OutName + ".gts");

            BottomSilk.Write(OutName + ".gbo", offset); Files.Add(OutName + ".gbo");
            BottomCopper.Write(OutName + ".gbl", offset); Files.Add(OutName + ".gbl");
            BottomSolderMask.Write(OutName + ".gbs", offset); Files.Add(OutName + ".gbs");

            BOM FiducialBom;

            if (inFiducialBom != null)
            {
                FiducialBom = inFiducialBom;
            }
            else
            {
                FiducialBom = new BOM();
            }

            BOMNumberSet set = new BOMNumberSet();
            int          fd  = 1;

            foreach (var a in Fiducials)
            {
                FiducialBom.AddBOMItemExt("FIDUCIAL_" + a.Style.ToString(), "FIDUCIAL_" + a.Style.ToString(), a.Style.ToString(), "__FD" + (fd.ToString()), set, "Frame_" + basename, a.Pos.X + offset.X, a.Pos.Y + offset.Y, 0, a.Side);
            }
            FiducialBom.WriteJLCCSV(targetfolder, basename + "_fiducials");

            return(Files);
        }
Exemplo n.º 14
0
 public AddObject()
 {
     BOM = new BOM();
 }
Exemplo n.º 15
0
        public void export()
        {
            summary.reset();

            sifAccessCRUD       sif_CRUD_Access     = new sifAccessCRUD();
            sifCRUD             sif_CRUD_APQM       = new sifCRUD();
            sifDetailCRUD       sifDetail_CRUD_APQM = new sifDetailCRUD();
            customerCRUD        customer_CRUD       = new customerCRUD();
            MarketSectorCRUD    marketSector_CRUD   = new MarketSectorCRUD();
            bomHeaderAccessCRUD bomHeaderAccess     = new bomHeaderAccessCRUD();
            bomAccessCRUD       bomAccessCRUD       = new bomAccessCRUD();
            bomCRUD             bomCRUD             = new bomCRUD();
            bomDetailCRUD       bomDetailCRUD       = new bomDetailCRUD();
            itemCRUD            item_CRUD           = new itemCRUD();

            List <SIF>          sifsInAPQM;
            List <Customer>     customersList;
            List <MarketSector> marketSectorList;
            List <Item>         itemList;

            int progress = 0;

            try
            {
                //sifsInAccess = (List<SIF>)sif_CRUD_Access.readActive();
                sifsInAPQM       = (List <SIF>)sif_CRUD_APQM.readAll();
                customersList    = (List <Customer>)customer_CRUD.readAll();
                marketSectorList = (List <MarketSector>)marketSector_CRUD.readAll();
                itemList         = (List <Item>)item_CRUD.readAll();
            }
            catch (Exception ex)
            {
                log = "ERROR: " + ex.Message + "\n\n";
                backgroundWorker1.ReportProgress(progress);
                System.Threading.Thread.Sleep(5);
                //txtLog.AppendText("ERROR: " + ex.Message + "\n");
                summary.totalErrors++;
                refreshSummary();
                return;
            }

            if (sifsInAccessToExport.Count > 0)
            {
                ConnectionManager CM = new ConnectionManager();
                Data_Base_MNG.SQL DM = CM.getDataManager();

                log = "INFO: Attempting to export " + sifsInAccessToExport.Count + " SIFs.\n\n\n";
                backgroundWorker1.ReportProgress(progress);
                System.Threading.Thread.Sleep(5);
                //txtLog.AppendText("INFO: Found " + sifsInAccessToExport.Count + " SIFs to import.\n");
                foreach (SIF sif in sifsInAccessToExport)
                {
                    //if (sif.InquiryNumber == "120629702")
                    //    MessageBox.Show("Here");

                    log = "INFO: Reading an active SIF: " + sif + "\n";
                    backgroundWorker1.ReportProgress(progress);
                    System.Threading.Thread.Sleep(5);
                    //txtLog.AppendText("INFO: Reading an active SIF: " + sif + "\n");
                    //Was this SIF imported before?:
                    if (sif_CRUD_APQM.readBySIF_IN_List(sif, sifsInAPQM) == null)
                    {
                        /*Begin Transaction*/
                        DM.Open_Connection("ImportingSIF");

                        //Persisting Customer ***********************************************************************************************************

                        Customer customer = customer_CRUD.readByNameInList(sif.CustomerName, customersList);
                        if (customer == null) //Customer does not exist
                        {
                            customer = new Customer();
                            customer.CustomerName = sif.CustomerName;
                            string idGenerated = customer_CRUD.createAndReturnIdGenerated(customer, ref DM);
                            if (idGenerated == "")
                            {
                                summary.totalErrors++;
                                log = "ERROR: Could not create Customer: " + customer.CustomerName + " for SIF with Inquiry Number: " + sif.InquiryNumber + "\n" +
                                      "Error Description: " + DM.Error_Mjs + "\n\n";
                                backgroundWorker1.ReportProgress(++progress);
                                System.Threading.Thread.Sleep(5);
                                continue;
                            }
                            else
                            {
                                customer.Id = long.Parse(idGenerated);
                                log         = "INFO: Customer created in APQM database: " + customer.CustomerName + "\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                                //txtLog.AppendText("INFO: Customer created in APQM database: " + customer.CustomerName + "\n");
                                customersList.Add(customer);
                            }
                        }
                        sif.CustomerKey = customer.Id;


                        //Persisting Market Sector ******************************************************************************************************

                        MarketSector marketSector = marketSector_CRUD.readByNameInList(sif.MarketSector, marketSectorList);
                        if (marketSector == null) //Market Sector does not exist
                        {
                            marketSector      = new MarketSector();
                            marketSector.Name = sif.MarketSector;
                            string idGenerated = marketSector_CRUD.createAndReturnIdGenerated(marketSector, ref DM);
                            if (idGenerated == "")
                            {
                                summary.totalErrors++;
                                log = "ERROR: Could not create Market Sector: " + marketSector.Name + " for SIF with Inquiry Number: " + sif.InquiryNumber + "\n" +
                                      "Error Description: " + DM.Error_Mjs + "\n\n";
                                backgroundWorker1.ReportProgress(++progress);
                                System.Threading.Thread.Sleep(5);
                                continue;
                            }
                            else
                            {
                                marketSector.Id = long.Parse(idGenerated);
                                log             = "INFO: Market Sector created in APQM database: " + marketSector.Name + "\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                                marketSectorList.Add(marketSector);
                            }
                        }
                        sif.MarketSectorID = marketSector.Id;


                        //Persisting SIF Header *********************************************************************************************************
                        log = "INFO: Attempting to export SIF: " + sif + "\n";
                        backgroundWorker1.ReportProgress(progress);
                        System.Threading.Thread.Sleep(5);
                        //txtLog.AppendText("INFO: Attempting to export SIF: " + sif + "\n");
                        string sifIDGenerated = sif_CRUD_APQM.createAndReturnIdGenerated(sif, ref DM);
                        if (sifIDGenerated == "")
                        {
                            summary.totalErrors++;
                            log = "ERROR: Could not export SIF: " + sif + "\n" +
                                  "Error Description: " + DM.Error_Mjs + "\n\n";
                            backgroundWorker1.ReportProgress(++progress);
                            System.Threading.Thread.Sleep(5);
                            continue;
                        }
                        else
                        {
                            sif.Id = long.Parse(sifIDGenerated);

                            //Persisting SIF Detail ****************************************************************************************************

                            if (sif.SifDetail.Count > 0)
                            {
                                log = "INFO: SIF exported, attempting to export its SIF Detail.\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                                if (!sifDetail_CRUD_APQM.saveSIFDetailInSIF(sif, ref DM))
                                {
                                    summary.totalErrors++;
                                    log = "ERROR: Could not export SIF Detail: " + sif.SifDetail + "\n" +
                                          "Error Description: " + DM.Error_Mjs + "\n\n";
                                    backgroundWorker1.ReportProgress(++progress);
                                    System.Threading.Thread.Sleep(5);
                                    continue;
                                }
                            }
                            else
                            {
                                log = "INFO: There are no SIF Detail items to export.\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                            }

                            log = "INFO: SIF Detail exported, reading its BOMHeader.\n";
                            backgroundWorker1.ReportProgress(progress);
                            System.Threading.Thread.Sleep(5);


                            //Persisting BOM Header *****************************************************************************************************

                            BOMHeaderAccess bomHeaderByActualSIF = bomHeaderAccess.readBySIF(sif);

                            if (bomHeaderByActualSIF != null)
                            {
                                BOM bomAPQM = new BOM();
                                bomAPQM.SifId = long.Parse(sifIDGenerated);
                                //bomAPQM.TopPartNumber = "";
                                bomAPQM.PartDescription = bomHeaderByActualSIF.PartDescription;
                                //bomAPQM.Revision = "";
                                log = "INFO: Attempting to export its BOMHeader: " + bomAPQM + "\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                                //txtLog.AppendText("INFO: Attempting to export its BOMHeader: " + bomAPQM + "\n");
                                string bomIDGenerated = bomCRUD.createAndReturnIdGenerated(bomAPQM, ref DM);

                                if (bomIDGenerated == "")
                                {
                                    summary.totalErrors++;
                                    log = "ERROR: Could not export BOMHeader: " + bomAPQM + "\n" +
                                          "Error Description: " + DM.Error_Mjs + "\n\n";
                                    backgroundWorker1.ReportProgress(++progress);
                                    System.Threading.Thread.Sleep(5);
                                    continue;
                                }
                                else
                                {
                                    log = "INFO: BOMHeader exported, reading Bom Lines.\n";
                                    backgroundWorker1.ReportProgress(progress);
                                    System.Threading.Thread.Sleep(5);



                                    //txtLog.AppendText("INFO: BOMHeader exported, reading Bom Lines.\n");
                                    List <BOMAccess> bomsByActualSIF = bomAccessCRUD.readBySIF(sif);
                                    if (bomsByActualSIF.Count > 0)
                                    {
                                        log = "INFO: Found: " + bomsByActualSIF.Count + " BOM lines, attempting to export its Item.\n";
                                        backgroundWorker1.ReportProgress(progress);
                                        System.Threading.Thread.Sleep(5);
                                        //txtLog.AppendText("INFO: Found: " + bomsByActualSIF.Count + " BOM lines, attempting to export its Item.\n");
                                        bool errorInBOM = false;
                                        foreach (BOMAccess bom in bomsByActualSIF)
                                        {
                                            if (bom.ImportComment != "")
                                            {
                                                summary.totalErrors++;
                                                log = "ERROR: " + " BOM: " + bom + "\n" +
                                                      "Error Description: " + bom.ImportComment + "\n\n";
                                                log += "INFO: Attempting to RollBack..\n";
                                                DM.RollBack();
                                                if (DM.ErrorOccur)
                                                {
                                                    log += "...Fail to RollBack.\n" + "Error Description: " + DM.Error_Mjs + "\n\n";
                                                }
                                                else
                                                {
                                                    log += "...RollBack done.\n\n";
                                                }

                                                backgroundWorker1.ReportProgress(++progress);
                                                System.Threading.Thread.Sleep(5);
                                                errorInBOM = true;

                                                break;
                                            }
                                            else
                                            {
                                                //Persisting Item Master *******************************************************************************
                                                //if (bom.PartNumber == "26-3706-c")
                                                //{
                                                //    MessageBox.Show("here");
                                                //}
                                                Item item = readByPartNumberInList(bom, itemList);
                                                if (item == null)
                                                {
                                                    item             = new Item();
                                                    item.PartNumber  = bom.PartNumber;
                                                    item.Description = bom.AssemblyDescription; //wont be used anymore
                                                    item.Cost        = bom.PartCost;
                                                    item.Um          = bom.Um;
                                                    item.Material    = bom.Material;
                                                    item.CommCode    = bom.CommCode;


                                                    string itemIDGenerated = item_CRUD.createAndReturnIdGenerated(item, ref DM);
                                                    if (itemIDGenerated == "")
                                                    {
                                                        summary.totalErrors++;
                                                        log = "ERROR: Could not export Item: " + item + "\n" +
                                                              "Error Description: " + DM.Error_Mjs + "\n\n";
                                                        backgroundWorker1.ReportProgress(++progress);
                                                        System.Threading.Thread.Sleep(5);
                                                        errorInBOM = true;
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        item.Id = long.Parse(itemIDGenerated);
                                                        log     = "INFO: Item exported: " + item + "\n" + "Attempting to export its BOMLine\n";
                                                        backgroundWorker1.ReportProgress(progress);
                                                        System.Threading.Thread.Sleep(5);
                                                        itemList.Add(item);
                                                    }
                                                }
                                                else
                                                {
                                                    log = "INFO: Item already exists.\n";
                                                    backgroundWorker1.ReportProgress(progress);
                                                    System.Threading.Thread.Sleep(5);
                                                }


                                                //Persisting BOM Detail ********************************************************************************

                                                log = "INFO: Attempting to export its BOM Line\n";
                                                backgroundWorker1.ReportProgress(progress);
                                                System.Threading.Thread.Sleep(5);

                                                BOMDetail bomDetail = new BOMDetail();
                                                bomDetail.LinePosition   = bom.MaterialPosition;
                                                bomDetail.Material       = bom.Material;
                                                bomDetail.Description    = bom.AssemblyDescription; //Wont be used anymore
                                                bomDetail.SalesStatus    = bom.Status;
                                                bomDetail.Cost           = bom.PartCost;
                                                bomDetail.Qty            = bom.NoRequired;
                                                bomDetail.Um             = bom.Um;
                                                bomDetail.PartNumber     = bom.PartNumber;
                                                bomDetail.SalesComments  = bom.SalesComments; //wont be used anymore
                                                bomDetail.VendorQuoteEst = bom.VendorQuoteEst;
                                                bomDetail.CapComAssm     = bom.CapComAssm;
                                                bomDetail.CommCode       = bom.CommCode;
                                                bomDetail.Status         = "Imported";

                                                bomDetail.BomHeaderKey = long.Parse(bomIDGenerated);

                                                bomDetail.ItemMasterkey = item.Id;
                                                if (!bomDetailCRUD.create(bomDetail, ref DM))
                                                {
                                                    summary.totalErrors++;
                                                    log = "ERROR: Could not export BOM Line: " + bomDetail.PartNumber + ", " + bomDetail + " Error: " + DM.Error_Mjs + "\n\n";
                                                    backgroundWorker1.ReportProgress(++progress);
                                                    System.Threading.Thread.Sleep(5);
                                                    errorInBOM = true;
                                                    break;
                                                }
                                                else
                                                {
                                                    log = "INFO: BOM Line exported: " + bomDetail.PartNumber + ", " + bomDetail + "\n";
                                                    backgroundWorker1.ReportProgress(progress);
                                                    System.Threading.Thread.Sleep(5);
                                                    //txtLog.AppendText("INFO: BOM Line exported: " + bomDetail + "\n");
                                                }
                                            }
                                        }
                                        if (errorInBOM)
                                        {
                                            DM.Close_Open_Connection();
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        log = "INFO: No BOM Line found for SIF: " + sif + "\n";
                                        backgroundWorker1.ReportProgress(progress);
                                        System.Threading.Thread.Sleep(5);
                                        //txtLog.AppendText("INFO: No BOM Line found for SIF: " + sif + "\n");
                                    }
                                }
                            }
                            else
                            {
                                log = "INFO: No BOM Header found for SIF: " + sif + "\n";
                                backgroundWorker1.ReportProgress(progress);
                                System.Threading.Thread.Sleep(5);
                                //txtLog.AppendText("ERROR: Could not export BOM of SIF: " + sif + "\n");
                                //summary.totalErrors++;
                            }
                        }


                        /* End Transaction */
                        DM.CommitTransaction();
                        if (DM.ErrorOccur)
                        {
                            log = "ERROR: Could not commit transaction for SIF: " + sif + "\n";
                        }
                        else
                        {
                            log = "SUCCESS: SIF exported: " + sif + "\n";
                        }
                        DM.Close_Open_Connection();
                        backgroundWorker1.ReportProgress(progress);
                        System.Threading.Thread.Sleep(5);
                        //txtLog.AppendText("SUCCESS: SIF exported: " + sif + "\n");
                        summary.totalSuccess++;
                    }
                    else
                    {
                        log = "OMITTED: SIF already exported: " + sif + "\n";
                        backgroundWorker1.ReportProgress(progress);
                        System.Threading.Thread.Sleep(5);
                        //txtLog.AppendText("OMITTED: SIF already exported: " + sif + "\n");
                        summary.totalOmitted++;
                    }
                    log = "\n";
                    backgroundWorker1.ReportProgress(++progress);
                    System.Threading.Thread.Sleep(5);
                }
            }
            else
            {
                log = "INFO: No more SIF to export.\n\n";
                backgroundWorker1.ReportProgress(progress);
                System.Threading.Thread.Sleep(5);
                //txtLog.AppendText("INFO: No more SIF to export.\n\n");
            }
        }
Exemplo n.º 16
0
        public override int InitImport(DateTime startTime, DateTime endTime)
        {
            var result = 0;
            //定义批处理的
            var models = new BaseModel[BatchNum];

            SourceConn.Open();
            RelatedConn.Open();
            var sourceCmd = new SqlCommand
            {
                Connection  = SourceConn,
                CommandText =
                    $@"select * from 
(select FBOMNumber,(select FNumber from t_icitem where t_icitem.FItemID=icbom.FItemID) fshortnumber,FVersion,FStatus,FQty, (SELECT FName FROM T_MeasureUnit where T_MeasureUnit.FMeasureUnitID=icbom.FUnitID) FUnitID
,FInterID,FEnterTime from icbom) a right join (
select FEntryID,(select FNumber from t_icitem where t_icitem.FItemID=ICBOMCHILD.FItemID) detailfshortnumber,(select (SELECT FName FROM T_MeasureUnit where T_MeasureUnit.FMeasureUnitID=t_icitem.FUnitID) from t_icitem where t_icitem.FItemID=ICBOMCHILD.FItemID) detailFUnitID,FQty as detailfqty,FInterID from  ICBOMCHILD ) b on a.FInterID=b.FInterID where fshortnumber like '30%' and detailfshortnumber like '30%'
                       and FEnterTime between CONVERT(datetime, '{startTime}') and CONVERT(datetime, '{endTime}')"
            };
            var reader     = sourceCmd.ExecuteReader();
            var relatedCmd = new OracleCommand
            {
                Connection  = RelatedConn,
                CommandText = GetInsertCmdText()
            };
            var i = 0;

            try
            {
                while (reader.Read())
                {
                    var bom = new BOM();
                    if (reader["FBOMNumber"] == DBNull.Value)
                    {
                        continue;
                    }
                    bom.BOMCode            = reader["FBOMNumber"].ToString();
                    bom.MaterielCode       = reader["fshortnumber"].ToString();
                    bom.Version            = reader["FVersion"].ToString();
                    bom.UseState           = reader["FStatus"].ToString();
                    bom.MaterielQuantity   = reader["FQty"] == DBNull.Value ? 0 : double.Parse(reader["FQty"].ToString());
                    bom.MaterielUnit       = reader["FunitID"].ToString();
                    bom.DetailCode         = reader["FEntryID"].ToString();
                    bom.DetailMaterielCode = reader["detailfshortnumber"].ToString();
                    bom.DetailQuantity     = reader["detailfqty"] == DBNull.Value ? 0 : double.Parse(reader["FQty"].ToString());
                    bom.DetailUnit         = reader["detailFUnitID"].ToString();
                    bom.Flag        = 'C';
                    bom.K3TimeStamp = DateTime.Parse(reader["FEnterTime"].ToString());
                    bom.SourceDb    = "XG";
                    bom.ID          = Guid.NewGuid().ToString();
                    models[i]       = bom;
                    i++;
                    if (i == BatchNum)
                    {
                        CommitBatch(relatedCmd, models);
                        result += i;
                        i       = 0;
                        models  = new BaseModel[BatchNum];//重置批
                    }
                }
                if (i > 0)
                {
                    var oddModels = new BaseModel[i];
                    for (int j = 0; j < i; j++)
                    {
                        oddModels[j] = models[j];
                    }
                    CommitBatch(relatedCmd, oddModels);
                    result += i;
                }
                reader.Close();
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("Logger").Error(e.Message + "\r\n" + sourceCmd.CommandText + "\r\n" + relatedCmd.CommandText);
                throw;
            }
            finally
            {
                SourceConn.Close();
                RelatedConn.Close();
            }
            return(result);
        }
Exemplo n.º 17
0
        public override int Update(DateTime startTime, DateTime endTime)
        {
            var result = 0;

            SourceConn.Open();
            RelatedConn.Open();
            //定义批处理的
            var insertModels = new BaseModel[BatchNum];
            var updateModels = new BaseModel[BatchNum];
            var sourceCmd    = new SqlCommand
            {
                Connection  = SourceConn,
                CommandText =
                    $@"select * from 
(select FBOMNumber,(select FNumber from t_icitem where t_icitem.FItemID=icbom.FItemID) fshortnumber,FVersion,FStatus,FQty, (SELECT FName FROM T_MeasureUnit where T_MeasureUnit.FMeasureUnitID=icbom.FUnitID) FUnitID
,FInterID,FEnterTime from icbom) a right join (
select FEntryID,(select FNumber from t_icitem where t_icitem.FItemID=ICBOMCHILD.FItemID) detailfshortnumber,(select (SELECT FName FROM T_MeasureUnit where T_MeasureUnit.FMeasureUnitID=t_icitem.FUnitID) from t_icitem where t_icitem.FItemID=ICBOMCHILD.FItemID) detailFUnitID,FQty as detailfqty,FInterID from  ICBOMCHILD ) b on a.FInterID=b.FInterID where fshortnumber like '30%' and detailfshortnumber like '30%'
                       ",
                CommandTimeout = 0
                                 //and FEnterTime between CONVERT(datetime, '{startTime}') and CONVERT(datetime, '{endTime}'),
            };
            var relatedCmd = new OracleCommand
            {
                Connection  = RelatedConn,
                CommandText = "select ID||','||HashCode||','||SourceDb from BOM where BOMCode=:BOMCode and DetailCode=:DetailCode and Version=:Version"
            };

            relatedCmd.Parameters.Add(new OracleParameter("BOMCode", OracleDbType.Char));
            relatedCmd.Parameters.Add(new OracleParameter("DetailCode", OracleDbType.Char));
            relatedCmd.Parameters.Add(new OracleParameter("Version", OracleDbType.Char));
            relatedCmd.Prepare();
            var reader    = sourceCmd.ExecuteReader();
            var insertCmd = new OracleCommand()
            {
                Connection  = RelatedConn,
                CommandText = GetInsertCmdText()
            };
            var updateCmd = new OracleCommand()
            {
                Connection  = RelatedConn,
                CommandText = GetUpdateCmdText() + $@" where BOMCode=:BOMCode and DetailCode=:DetailCode and Version=:Version"
            };

            try
            {
                var i = 0;
                var j = 0;
                while (reader.Read())
                {
                    var bom = new BOM();
                    if (reader["FBOMNumber"] == DBNull.Value || reader["FVersion"].ToString() == "")
                    {
                        continue;
                    }
                    bom.BOMCode            = reader["FBOMNumber"].ToString();
                    bom.MaterielCode       = reader["fshortnumber"].ToString();
                    bom.Version            = reader["FVersion"].ToString();
                    bom.UseState           = reader["FStatus"].ToString();
                    bom.MaterielQuantity   = reader["FQty"] == DBNull.Value ? 0 : double.Parse(reader["FQty"].ToString());
                    bom.MaterielUnit       = reader["FunitID"].ToString();
                    bom.DetailCode         = reader["FEntryID"].ToString();
                    bom.DetailMaterielCode = reader["detailfshortnumber"].ToString();
                    bom.DetailQuantity     = reader["detailfqty"] == DBNull.Value ? 0 : double.Parse(reader["FQty"].ToString());
                    bom.DetailUnit         = reader["detailFUnitID"].ToString();
                    bom.Flag        = 'C';
                    bom.K3TimeStamp = DateTime.Parse(reader["FEnterTime"].ToString());
                    bom.K3WriteTime = DateTime.Now;
                    bom.SourceDb    = Source.Name;
                    bom.CalculateHashCode();
                    relatedCmd.Parameters[0].Value = bom.BOMCode;
                    relatedCmd.Parameters[1].Value = bom.DetailCode;
                    relatedCmd.Parameters[2].Value = bom.Version;
                    var obj = relatedCmd.ExecuteScalar();
                    if (obj == null)
                    {
                        bom.ID          = Guid.NewGuid().ToString();
                        insertModels[i] = bom;
                        i++;
                        if (i == BatchNum)
                        {
                            CommitBatch(insertCmd, insertModels);
                            result      += i;
                            i            = 0;
                            insertModels = new BaseModel[BatchNum];//重置批
                        }
                    }
                    else
                    {
                        var arr = obj.ToString().Split(',');
                        if (bom.HashCode != arr[1])
                        {
                            if (arr[2] != Source.Name && Source.Name != Configuration.Current.MainData)
                            {
                                continue;
                            }
                            log4net.LogManager.GetLogger("Logger").Info($"检测到BOM更新【{bom.BOMCode}】");
                            bom.ID          = obj.ToString().Split(',')[0].ToString();
                            bom.Flag        = 'U';
                            updateModels[j] = bom;
                            j++;
                            if (j == BatchNum)
                            {
                                CommitBatch(updateCmd, updateModels);
                                result      += j;
                                j            = 0;
                                updateModels = new BaseModel[BatchNum];//重置批
                            }
                        }
                    }
                }
                if (i > 0)
                {
                    var oddModels = new BaseModel[i];
                    for (int k = 0; k < i; k++)
                    {
                        oddModels[k] = insertModels[k];
                    }
                    CommitBatch(insertCmd, oddModels);
                    result += i;
                }
                if (j > 0)
                {
                    var oddModels = new BaseModel[j];
                    for (int k = 0; k < j; k++)
                    {
                        oddModels[k] = updateModels[k];
                    }
                    CommitBatch(updateCmd, oddModels);
                    result += j;
                }
                reader.Close();
            }
            catch (Exception e)
            {
                log4net.LogManager.GetLogger("Logger").Error(e.ToString() + "\r\n" + sourceCmd.CommandText + "\r\n" + insertCmd.CommandText);
                throw;
            }
            finally
            {
                SourceConn.Close();
                RelatedConn.Close();
            }
            return(result);
        }
 public ActionResult receipts(BOM material)
 {
     return(RedirectToAction("materialDefinitions"));
 }
Exemplo n.º 19
0
        public void TestQuiltDeleteCreate()
        {
            using (var db = new QulltContext())
            {
                bool bFoundQuilt = false;
                var  find_query  = from query_quilts in db.Quilts
                                   orderby query_quilts.Name
                                   select query_quilts;
                foreach (var item in find_query)
                {
                    if (item.Name == "CreateQuiltTest Name")
                    {
                        bFoundQuilt = true;
                    }
                }

                if (bFoundQuilt == true)
                {
                    Quilt       xq = db.Quilts.First(i => i.Name == "CreateQuiltTest Name");
                    DesignBlock xb = xq.DesignBlock;
                    Order       xo = xq.Order;
                    Recipient   xr = xo.Recipient;

                    List <Award> listAward = xq.Awards.ToList();
                    foreach (var item in listAward)
                    {
                        db.Awards.Remove(item);
                    }

                    List <BOM> listBom = xq.BOMs.ToList();
                    foreach (var item in listBom)
                    {
                        db.BOMs.Remove(item);
                    }

                    db.Quilts.Remove(xq);
                    db.DesignBlocks.Remove(xb);
                    db.Orders.Remove(xo);
                    db.Recipients.Remove(xr);

                    db.SaveChanges();
                }

                // Create and save a new quilt et al
                // Quilt
                var quilt_desc = "CreateQuiltTest Description";
                var quilt_name = "CreateQuiltTest Name";
                // Order
                var order_desc  = "CreateQuiltTest Order Description";
                var order_start = "05/01/2013";
                var order_end   = "05/21/2013";
                // Recipient
                var rec_fn   = "Fred";
                var rec_ln   = "Smith";
                var rec_a1   = "123";
                var rec_a2   = "Elm";
                var rec_type = "Individual";
                // Design Block
                var dblock_desc    = "sunflower";
                var dblock_genesis = "CreateQuiltTest Name";
                //
                var order = new Order {
                    Description = order_desc, StartDate = order_start, EndDate = order_end
                };
                var quilt = new Quilt {
                    Name = quilt_name, Description = quilt_desc
                };
                var recipient = new Recipient {
                    FirstName = rec_fn, LastName = rec_ln, Address1 = rec_a1, Address2 = rec_a2, Type = rec_type
                };
                var dblock = new DesignBlock {
                    Genesis = dblock_genesis, Description = dblock_desc
                };
                //
                var qid = quilt.QuiltId;        // do I have to mess with these ?
                var oid = order.OrderId;
                var rid = recipient.RecipientId;
                var bib = dblock.DesignBlockId;
                //
                quilt.Order       = order;
                order.Quilt       = quilt;
                order.Recipient   = recipient;      // this seems clumsy
                quilt.DesignBlock = dblock;
                //
                db.Orders.Add(order);
                db.Quilts.Add(quilt);
                db.Recipients.Add(recipient);
                db.DesignBlocks.Add(dblock);
                //
                var awd = new Award();
                awd.AwardingBody = "Hancock Fabric";
                awd.DateOfAward  = "5/22/2008";
                awd.Description  = "Blue Ribbon";

                quilt.Awards.Add(awd);
                db.Awards.Add(awd);
                //
                var bom = new BOM();
                bom.TypeOfItem  = "Border Squares";
                bom.Count       = "35";
                bom.Description = "Yellow fabric with orange edges";

                quilt.BOMs.Add(bom);
                db.BOMs.Add(bom);
                //
                //
                db.SaveChanges();
                //
                // Display all Quilts from the database
                bool bFoundName = false;
                var  query      = from q in db.Quilts
                                  orderby q.Name
                                  select q;
                // it should be there
                foreach (var item in query)
                {
                    if (item.Name == "CreateQuiltTest Name")
                    {
                        bFoundName = true;
                    }
                }
                Assert.IsTrue(bFoundName);
            }
        }
Exemplo n.º 20
0
 public void AddPart(Part newPart, uint positionNumber, uint quantity)
 {
     BOM.Add(new BOMItem(newPart, positionNumber, quantity));
 }
Exemplo n.º 21
0
        public override Asset Import(string path)
        {
            BOM   bom   = BOM.Load(path);
            Model model = new Model();

            model.SupportingDocuments["Source"] = bom;

            for (int i = 0; i < bom.Meshes.Count; i++)
            {
                var           bommesh  = bom.Meshes[i];
                ModelMesh     mesh     = new ModelMesh();
                ModelMeshPart meshpart = new ModelMeshPart();

                if (i < 4)
                {
                    for (int j = 0; j < bommesh.IndexBuffer.Count; j += 3)
                    {
                        int p0 = bommesh.IndexBuffer[j + 0];
                        int p1 = bommesh.IndexBuffer[j + 1];
                        int p2 = bommesh.IndexBuffer[j + 2];

                        meshpart.AddFace(
                            new Vector3[] {
                            new Vector3(bom.Verts[p0].Position.X, bom.Verts[p0].Position.Y, bom.Verts[p0].Position.Z),
                            new Vector3(bom.Verts[p1].Position.X, bom.Verts[p1].Position.Y, bom.Verts[p1].Position.Z),
                            new Vector3(bom.Verts[p2].Position.X, bom.Verts[p2].Position.Y, bom.Verts[p2].Position.Z),
                        },
                            new Vector3[] {
                            new Vector3(bom.Verts[p0].Normal.X, bom.Verts[p0].Normal.Y, bom.Verts[p0].Normal.Z),
                            new Vector3(bom.Verts[p1].Normal.X, bom.Verts[p1].Normal.Y, bom.Verts[p1].Normal.Z),
                            new Vector3(bom.Verts[p2].Normal.X, bom.Verts[p2].Normal.Y, bom.Verts[p2].Normal.Z),
                        },
                            new Vector2[] {
                            Vector2.Zero,
                            Vector2.Zero,
                            Vector2.Zero
                        }
                            );
                    }
                }
                else
                {
                    // Process triangle strip
                    for (int j = 0; j < bommesh.IndexBuffer.Count - 2; j++)
                    {
                        BOMVertex v0, v1, v2;

                        v0 = bom.Verts[bommesh.IndexBuffer[j + 0]];

                        if (j % 2 != 0)
                        {
                            v1 = bom.Verts[bommesh.IndexBuffer[j + 1]];
                            v2 = bom.Verts[bommesh.IndexBuffer[j + 2]];
                        }
                        else
                        {
                            v1 = bom.Verts[bommesh.IndexBuffer[j + 2]];
                            v2 = bom.Verts[bommesh.IndexBuffer[j + 1]];
                        }

                        meshpart.AddFace(
                            new Vector3[] {
                            new Vector3(v0.Position.X, v0.Position.Y, v0.Position.Z),
                            new Vector3(v1.Position.X, v1.Position.Y, v1.Position.Z),
                            new Vector3(v2.Position.X, v2.Position.Y, v2.Position.Z)
                        },
                            new Vector3[] {
                            new Vector3(v0.Normal.X, v0.Normal.Y, v0.Normal.Z),
                            new Vector3(v1.Normal.X, v1.Normal.Y, v1.Normal.Z),
                            new Vector3(v2.Normal.X, v2.Normal.Y, v2.Normal.Z)
                        },
                            new Vector2[] {
                            Vector2.Zero,
                            Vector2.Zero,
                            Vector2.Zero
                        }
                            );
                    }
                }

                mesh.AddModelMeshPart(meshpart);

                mesh.Name = bom.Name + "_" + i;
                model.SetName(bom.Name, model.AddMesh(mesh));
            }

            return(model);
        }
Exemplo n.º 22
0
 /*
  * string file: 파일 경로
  * string[][2] replacers: 문자열 쌍
  * return string[4]: 원본 / 원본 미리보기 / 결과 / 결과 미리보기
  * ... 사실 string 4개짜리 class 만들기 귀찮아서 string[4]로 처리한 거임
  */
 public string[] GetReplaced(string file, string[][] replacers)
 {
     return(GetReplaced(file, BOM.DetectEncoding(file), replacers));
 }
Exemplo n.º 23
0
        public static List <string> WriteSideEdgeFrame(PolyLine pl, FrameSettings FS, string basefile, BOM output = null)
        {
            List <string> Files = new List <string>();

            try
            {
                int    polyid     = 0;
                string fname      = System.IO.Path.GetFileName(basefile);
                string fnamenoext = System.IO.Path.GetFileNameWithoutExtension(basefile);
                string OutName    = Path.Combine(System.IO.Path.GetDirectoryName(basefile), fnamenoext);
                Console.WriteLine("writing frame files to {0}", OutName);
                //   Bounds B = new Bounds();
                // B.AddPolyLine(pl);
                //                FS.innerHeight = B.Height();
                //              FS.innerWidth = B.Width();


                double W  = (double)FS.innerWidth;
                double H  = (double)FS.innerHeight;
                double TE = (double)FS.topEdge;
                double LE = (double)FS.leftEdge;

                double OuterWidth  = W + LE * 2.0;
                double OuterHeight = H + TE * 2.0;
                double InnerWidth  = W;
                double InnerHeight = H;


                PCBWriterSet PCB = new PCBWriterSet();

                double mountholediameter = (double)FS.holeDiameter;



                // board outline
                PolyLine PL = new PolyLine(polyid++);
                PL.MakeRoundedRect(new PointD(0, 0), new PointD(OuterWidth, OuterHeight), (double)FS.roundedOuterCorners);
                PCB.AddOutline(PL);

                if (FS.InsideEdgeMode == FrameSettings.InsideMode.RegularEdge)
                {
                    PolyLine PL2 = new PolyLine(polyid++);
                    PL2.MakeRoundedRect(new PointD(LE, TE), new PointD(InnerWidth + LE, InnerHeight + TE), (double)FS.roundedInnerCorners);
                    PCB.AddOutline(PL2);
                }

                if (FS.InsideEdgeMode == FrameSettings.InsideMode.FormFitting && pl != null)
                {
                    PolyLine PP = pl.Copy();
                    PP.Translate(-FS.offset.X, -FS.offset.Y);
                    List <PolyLine> PL2 = PP.Offset(FS.margin, polyid++);
                    foreach (var l in PL2)
                    {
                        PCB.AddOutline(l);
                    }

                    polyid += PL2.Count;
                }

                #region fiducials

                List <PointD> Fiducials = new List <PointD>();

                foreach (var P in FS.fiducialsListData)
                {
                    PointD fiducialPoint = P.pos;
                    PCB.Fiducial(fiducialPoint, P.CopperDiameter, P.MaskDiameter, P.Top ? BoardSide.Top : BoardSide.Bottom);
                }

                #endregion

                string FrameTitle = FS.FrameTitle;

                string FrameTopTitle            = FrameTitle + " - Top";
                string FrameBottomTitle         = FrameTitle + " - Bottom";
                double verticaltitleclearance   = 0;
                double horizontaltitleclearance = 0;
                if (FrameTitle.Length > 0)
                {
                    FontSet fnt = FontSet.Load("Font.xml");
                    horizontaltitleclearance = fnt.StringWidth(FrameBottomTitle, TE / 4) + mountholediameter * 2 + FS.topEdge;
                    verticaltitleclearance   = fnt.StringWidth(FrameBottomTitle, TE / 4) + mountholediameter * 2 + FS.topEdge;

                    PCB.Label(fnt, new PointD(OuterWidth / 2.0, OuterHeight - TE / 4.0), FrameTopTitle, TE / 4, StringAlign.CenterCenter, 0.1, true, true, 0);
                    PCB.Label(fnt, new PointD(OuterWidth - LE / 4, OuterHeight / 2), FrameTopTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, -90);
                    PCB.Label(fnt, new PointD(LE / 4, OuterHeight / 2), FrameTopTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, 90);
                    PCB.Label(fnt, new PointD(OuterWidth / 2.0, TE - TE / 4.0), FrameTopTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, 0);


                    PCB.Label(fnt, new PointD(OuterWidth / 2.0, OuterHeight - TE / 4.0), FrameBottomTitle, TE / 4, StringAlign.CenterCenter, 0.1, true, true, 0, true, true, true);
                    PCB.Label(fnt, new PointD(OuterWidth - LE / 4, OuterHeight / 2), FrameBottomTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, -90, true);
                    PCB.Label(fnt, new PointD(LE / 4, OuterHeight / 2), FrameBottomTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, 90, true);
                    PCB.Label(fnt, new PointD(OuterWidth / 2.0, TE - TE / 4.0), FrameBottomTitle, TE / 4.0, StringAlign.CenterCenter, 0.1, true, true, 0, true);
                }

                if (FS.addHoles)
                {
                    double side = LE / 2.0;
                    double top  = TE / 2.0;

                    PCB.Drill(new PointD(side, top), mountholediameter, 1);
                    PCB.Drill(new PointD(OuterWidth - side, top), mountholediameter, 1);
                    PCB.Drill(new PointD(OuterWidth - side, OuterHeight - top), mountholediameter, 1);
                    PCB.Drill(new PointD(side, OuterHeight - top), mountholediameter, 1);

                    double dx = (OuterWidth - side) - side;
                    double dy = (OuterHeight - top) - top;

                    dx -= horizontaltitleclearance;
                    dy -= verticaltitleclearance;
                    dx /= 2;
                    dy /= 2;

                    int horiz = (int)Math.Ceiling((dx / 2) / FS.MaxMountHoleSpacingMM);
                    int vert  = (int)Math.Ceiling((dy / 2) / FS.MaxMountHoleSpacingMM);

                    dx /= (float)horiz;
                    dy /= (float)vert;

                    if (dx < FS.MinMountHoleSpacingMM)
                    {
                        horiz = 0;
                    }
                    if (dy < FS.MinMountHoleSpacingMM)
                    {
                        vert = 0;
                    }

                    for (int i = 1; i <= horiz; i++)
                    {
                        PCB.Drill(new PointD(side + (dx) * i, top), mountholediameter, 1);
                        PCB.Drill(new PointD((OuterWidth - side) - (dx) * i, top), mountholediameter, 1);
                        PCB.Drill(new PointD(side + (dx) * i, OuterHeight - top), mountholediameter, 1);
                        PCB.Drill(new PointD((OuterWidth - side) - (dx) * i, OuterHeight - top), mountholediameter, 1);
                    }


                    for (int i = 1; i <= vert; i++)
                    {
                        PCB.Drill(new PointD(side, top + (dy) * i), mountholediameter, 1);
                        PCB.Drill(new PointD(side, (OuterHeight - top) - (dy) * i), mountholediameter, 1);
                        PCB.Drill(new PointD((OuterWidth - side), top + (dy) * i), mountholediameter, 1);
                        PCB.Drill(new PointD((OuterWidth - side), (OuterHeight - top) - (dy) * i), mountholediameter, 1);
                    }
                }
                if (FS.DefaultFiducials)
                {
                    double side = LE / 2.0;
                    double top  = TE / 2.0;

                    PCB.Fiducial(new PointD(side + mountholediameter * 2, top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Square);
                    PCB.Fiducial(new PointD(side + mountholediameter * 3, top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Round);


                    PCB.Fiducial(new PointD(OuterWidth - (side + mountholediameter * 2), top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Square);
                    PCB.Fiducial(new PointD(OuterWidth - (side + mountholediameter * 3), top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Round);


                    PCB.Fiducial(new PointD(side + mountholediameter * 2, OuterHeight - top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Round);
                    PCB.Fiducial(new PointD(side + mountholediameter * 3, OuterHeight - top), 1, 2, FS.FiducialSide, PCBWriterSet.FiducialStyle.Square);
                }
                if (FS.RenderDirectionArrow)
                {
                    double side = LE / 2.0;
                    double top  = TE / 2.0;
                    double dy   = (OuterHeight - top) - top;

                    dy -= verticaltitleclearance;
                    dy /= 2;
                    int vert = (int)Math.Ceiling((dy / 2) / FS.MaxMountHoleSpacingMM);
                    dy /= (float)vert;

                    PCB.Arrow(new PointD(side, (OuterHeight - top) - (dy) * 1 + mountholediameter * 1.5), new PointD(side, (OuterHeight - top) - (dy) * 0 - mountholediameter * 1.5), FS.DirectionArrowSide);
                    PCB.Arrow(new PointD(OuterWidth - side, (OuterHeight - top) - (dy) * 1 + mountholediameter * 1.5), new PointD(OuterWidth - side, (OuterHeight - top) - (dy) * 0 - mountholediameter * 1.5), FS.DirectionArrowSide);

                    PCB.Arrow(new PointD(side, (top) + (dy) * 0 + mountholediameter * 1.5), new PointD(side, (top) + (dy) * 1 - mountholediameter * 1.5), FS.DirectionArrowSide);
                    PCB.Arrow(new PointD(OuterWidth - side, (top) + (dy) * 0 + mountholediameter * 1.5), new PointD(OuterWidth - side, (top) + (dy) * 1 - mountholediameter * 1.5), FS.DirectionArrowSide);
                }

                PolyLine Left   = new PolyLine();
                PolyLine Right  = new PolyLine();
                PolyLine Top    = new PolyLine();
                PolyLine Bottom = new PolyLine();


                Top.MakePRectangle(OuterWidth + 1, FS.topEdge + 1, -1, -1);
                Bottom.MakePRectangle(OuterWidth, FS.topEdge, 0, OuterHeight - FS.topEdge);
                Left.MakePRectangle(FS.leftEdge + 1, OuterHeight + 1, -1, -1);
                Right.MakePRectangle(FS.leftEdge, OuterHeight, OuterWidth - FS.leftEdge, 0);
                PCB.ArtInclusions.Add(Left);
                PCB.ArtInclusions.Add(Right);
                PCB.ArtInclusions.Add(Top);
                PCB.ArtInclusions.Add(Bottom);



                //PCB.CellularArt();


                Files.AddRange(PCB.Write(Path.GetDirectoryName(basefile), Path.GetFileNameWithoutExtension(basefile), output, FS.offset));;



                if (FS.RenderSample)
                {
                    GerberImageCreator GIC = new GerberImageCreator();
                    GIC.AddBoardsToSet(Files, new SilentLog());
                    GIC.WriteImageFiles(OutName, 200, true, false, true, null);
                }
            }
            catch (Exception e)
            {
                Console.Write(" Exception while making frames:{0}", e.Message);
            }
            foreach (var s in Files)
            {
                Console.WriteLine("Writen edge file {0} succesfully", s);
            }
            return(Files);
        }
Exemplo n.º 24
0
        public ActionResult ImportBomRecord(HttpPostedFileBase bomFile)
        {
            if (bomFile == null)
            {
                //TODO: Bom Import 优化上传失败界面
                throw new Exception("No file is uploaded to system");
            }

            var appData  = Server.MapPath("~/TmpFile/");
            var filename = Path.Combine(appData,
                                        DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(bomFile.FileName));

            bomFile.SaveAs(filename);
            string ex = Path.GetExtension(filename);

            List <BomImportModel> records = new List <BomImportModel>();

            if (ex.Equals(".csv"))
            {
                CsvConfiguration configuration = new CsvConfiguration();
                configuration.Delimiter        = Settings.Default.csvDelimiter;
                configuration.HasHeaderRecord  = true;
                configuration.SkipEmptyRecords = true;
                configuration.RegisterClassMap <BomCsvModelMap>();
                configuration.TrimHeaders = true;
                configuration.TrimFields  = true;

                try
                {
                    using (TextReader treader = System.IO.File.OpenText(filename))
                    {
                        CsvReader csvReader = new CsvReader(treader, configuration);
                        records = csvReader.GetRecords <BomImportModel>().ToList();
                    }
                }
                catch (Exception e)
                {
                    //ViewBag.TextExpMsg = "<-------------Read Csv File Exception!,Please Check.------------->" + e;
                    ViewBag.TextExpMsg = "<-------------读取CSV文件异常,请查看原因:------------->" + e;
                }

                List <Dictionary <string, string> > CreateErrorDic     = new List <Dictionary <string, string> >();
                List <Dictionary <string, string> > UpdateErrorDic     = new List <Dictionary <string, string> >();
                List <Dictionary <string, string> > DeleteErrorDic     = new List <Dictionary <string, string> >();
                List <Dictionary <string, string> > ActionNullErrorDic = new List <Dictionary <string, string> >();
                List <Dictionary <string, string> > OtherErrorDic      = new List <Dictionary <string, string> >();

                if (records.Count > 0)
                {
                    int AllQty           = records.Count;
                    int CreateSuccessQty = 0;
                    int CreateFailureQty = 0;
                    int UpdateSuccessQty = 0;
                    int UpdateFailureQty = 0;
                    int DeleteSuccessQty = 0;
                    int DeleteFailureQty = 0;
                    int ActionNullQty    = 0;
                    int OtherQty         = 0;

                    IBomService ps = new BomService(Settings.Default.db);

                    foreach (BomImportModel record in records)
                    {
                        if (string.IsNullOrWhiteSpace(record.Action))
                        {
                            ActionNullQty++;

                            Dictionary <string, string> ActionNullErrorList = new Dictionary <string, string>();

                            ActionNullErrorList.Add("ID", record.ID);
                            ActionNullErrorList.Add("PartNr", record.PartNr);
                            ActionNullErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                            ActionNullErrorList.Add("ValidTo", record.ValidTo.ToString());
                            ActionNullErrorList.Add("VersionId", record.VersionId);
                            ActionNullErrorList.Add("BomDesc", record.BomDesc);
                            ActionNullErrorList.Add("Action", record.Action);

                            ActionNullErrorDic.Add(ActionNullErrorList);
                            ViewData["actionNullErrorDic"] = ActionNullErrorDic;
                        }
                        else
                        {
                            //新建
                            BOM bom = new BOM()
                            {
                                id        = record.ID,
                                partNr    = record.PartNr,
                                validFrom = record.ValidFrom,
                                validTo   = record.ValidTo,
                                versionId = record.VersionId,
                                bomDesc   = record.BomDesc
                            };

                            if (record.Action.Trim().ToLower().Equals("create"))
                            {
                                try
                                {
                                    ps.Create(bom);
                                    CreateSuccessQty++;
                                }
                                catch (Exception)
                                {
                                    CreateFailureQty++;

                                    Dictionary <string, string> CreateErrorList = new Dictionary <string, string>();

                                    CreateErrorList.Add("ID", record.ID);
                                    CreateErrorList.Add("PartNr", record.PartNr);
                                    CreateErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                    CreateErrorList.Add("ValidTo", record.ValidTo.ToString());
                                    CreateErrorList.Add("VersionId", record.VersionId);
                                    CreateErrorList.Add("BomDesc", record.BomDesc);
                                    CreateErrorList.Add("Action", record.Action);

                                    CreateErrorDic.Add(CreateErrorList);
                                    ViewData["createErrorDic"] = CreateErrorDic;
                                }
                            }
                            else if (record.Action.Trim().ToLower().Equals("update"))
                            {
                                //更新
                                try
                                {
                                    bool result = ps.Update(bom);
                                    if (result)
                                    {
                                        UpdateSuccessQty++;
                                    }
                                    else
                                    {
                                        UpdateFailureQty++;

                                        Dictionary <string, string> UpdateErrorList = new Dictionary <string, string>();

                                        UpdateErrorList.Add("ID", record.ID);
                                        UpdateErrorList.Add("PartNr", record.PartNr);
                                        UpdateErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                        UpdateErrorList.Add("ValidTo", record.ValidTo.ToString());
                                        UpdateErrorList.Add("VersionId", record.VersionId);
                                        UpdateErrorList.Add("BomDesc", record.BomDesc);
                                        UpdateErrorList.Add("Action", record.Action);

                                        UpdateErrorDic.Add(UpdateErrorList);
                                        ViewData["updateErrorDic"] = UpdateErrorDic;
                                    }
                                }
                                catch (Exception)
                                {
                                    UpdateFailureQty++;

                                    Dictionary <string, string> UpdateErrorList = new Dictionary <string, string>();

                                    UpdateErrorList.Add("ID", record.ID);
                                    UpdateErrorList.Add("PartNr", record.PartNr);
                                    UpdateErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                    UpdateErrorList.Add("ValidTo", record.ValidTo.ToString());
                                    UpdateErrorList.Add("VersionId", record.VersionId);
                                    UpdateErrorList.Add("BomDesc", record.BomDesc);
                                    UpdateErrorList.Add("Action", record.Action);

                                    UpdateErrorDic.Add(UpdateErrorList);
                                    ViewData["updateErrorDic"] = UpdateErrorDic;
                                }
                            }
                            else if (record.Action.Trim().ToLower().Equals("delete"))
                            {
                                try
                                {
                                    //删除
                                    bool result = ps.Delete(bom);

                                    if (result)
                                    {
                                        DeleteSuccessQty++;
                                    }
                                    else
                                    {
                                        DeleteFailureQty++;

                                        Dictionary <string, string> DeleteErrorList = new Dictionary <string, string>();

                                        DeleteErrorList.Add("ID", record.ID);
                                        DeleteErrorList.Add("PartNr", record.PartNr);
                                        DeleteErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                        DeleteErrorList.Add("ValidTo", record.ValidTo.ToString());
                                        DeleteErrorList.Add("VersionId", record.VersionId);
                                        DeleteErrorList.Add("BomDesc", record.BomDesc);
                                        DeleteErrorList.Add("Action", record.Action);

                                        DeleteErrorDic.Add(DeleteErrorList);
                                        ViewData["deleteErrorDic"] = DeleteErrorDic;
                                    }
                                }
                                catch (Exception)
                                {
                                    DeleteFailureQty++;
                                    Dictionary <string, string> DeleteErrorList = new Dictionary <string, string>();

                                    DeleteErrorList.Add("ID", record.ID);
                                    DeleteErrorList.Add("PartNr", record.PartNr);
                                    DeleteErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                    DeleteErrorList.Add("ValidTo", record.ValidTo.ToString());
                                    DeleteErrorList.Add("VersionId", record.VersionId);
                                    DeleteErrorList.Add("BomDesc", record.BomDesc);
                                    DeleteErrorList.Add("Action", record.Action);

                                    DeleteErrorDic.Add(DeleteErrorList);
                                    ViewData["deleteErrorDic"] = DeleteErrorDic;
                                }
                            }
                            else
                            {
                                //错误 忽略
                                Dictionary <string, string> OtherErrorList = new Dictionary <string, string>();

                                OtherErrorList.Add("ID", record.ID);
                                OtherErrorList.Add("PartNr", record.PartNr);
                                OtherErrorList.Add("ValidFrom", record.ValidFrom.ToString());
                                OtherErrorList.Add("ValidTo", record.ValidTo.ToString());
                                OtherErrorList.Add("VersionId", record.VersionId);
                                OtherErrorList.Add("BomDesc", record.BomDesc);
                                OtherErrorList.Add("Action", record.Action);

                                OtherErrorDic.Add(OtherErrorList);
                                ViewData["otherErrorDic"] = OtherErrorDic;
                            }
                        }
                    }

                    OtherQty = AllQty - CreateSuccessQty - CreateFailureQty - UpdateSuccessQty - UpdateFailureQty - DeleteSuccessQty - DeleteFailureQty - ActionNullQty;
                    Dictionary <string, int> Qty = new Dictionary <string, int>();
                    Qty.Add("AllQty", AllQty);
                    Qty.Add("CreateSuccessQty", CreateSuccessQty);
                    Qty.Add("CreateFailureQty", CreateFailureQty);
                    Qty.Add("UpdateSuccessQty", UpdateSuccessQty);
                    Qty.Add("UpdateFailureQty", UpdateFailureQty);
                    Qty.Add("DeleteSuccessQty", DeleteSuccessQty);
                    Qty.Add("DeleteFailureQty", DeleteFailureQty);
                    Qty.Add("ActionNullQty", ActionNullQty);
                    Qty.Add("OtherQty", OtherQty);
                    ViewData["Qty"] = Qty;
                }
                else
                {
                    //ViewBag.NotCheckedData = "No Data Checked. Please Check Delimiter or Column Name.";
                    ViewBag.NotCheckedData = "没有检测到数据。请检查分隔符和列名。";
                }
            }
            else
            {
                //ViewBag.NotCsv = "Your File is not .Csv File, Please Check FileName.";
                ViewBag.NotCsv = "你上传的文件不是.CSV格式。请检查文件名。";
            }

            if (ViewBag.NotCsv == null)
            {
                //ViewBag.NotCsv = "CSV File is OK.";
                ViewBag.NotCsv = "上传CSV文件正确!";
            }

            if (ViewBag.NotCheckedData == null)
            {
                //ViewBag.NotCheckedData = "Check Data is OK.";
                ViewBag.NotCheckedData = "检查数据完成!";
            }

            return(View());
        }
Exemplo n.º 25
0
 public ActionResult editBOMDefinition(BOM bom)
 {
     //  bom.Save();
     return(RedirectToAction("bomDefinitions"));
 }
Exemplo n.º 26
0
        private DataTable GetDataTable(Component specComponent)
        {
            DataTable resultTable = new DataTable();

            // Format table
            resultTable.Columns.Add("VPNumber", typeof(string));             // Code from purchase roll
            resultTable.Columns.Add("PartNumber", typeof(string));
            resultTable.Columns.Add("Description", typeof(string));
            resultTable.Columns.Add("Quantity", typeof(string));
            resultTable.Columns.Add("IsConsumable", typeof(bool));
            resultTable.Columns.Add("UnitOfMeasure", typeof(string));
            try
            {
                AssemblyDocument assembly = (AssemblyDocument)inventorApp.Documents.Open(specComponent.FullFileName, false);
                // Get BOM
                BOM bom = assembly.ComponentDefinition.BOM;
                bom.StructuredViewFirstLevelOnly = false;
                bom.StructuredViewEnabled        = true;
                // Get merge settings
                bool     mergeEnabled     = false;
                string[] mergeExcludeList = new string[] { "жопа" };
                bom.GetPartNumberMergeSettings(out mergeEnabled, out mergeExcludeList);
                // Set merge settings to false temporarily
                bom.SetPartNumberMergeSettings(false, mergeExcludeList);
                // Set a reference to the "Structured" BOMView
                BOMView bomView = bom.BOMViews["Структурированный"];


                foreach (BOMRow BOMrow in bomView.BOMRows)
                {
                    DataRow             row = resultTable.NewRow();
                    ComponentDefinition componentDefinition = BOMrow.ComponentDefinitions[1];
                    Document            locDoc   = (Document)componentDefinition.Document;
                    PropertySet         oPropSet = locDoc.PropertySets["Design Tracking Properties"];
                    row["PartNumber"]  = oPropSet["Part Number"].Value.ToString();
                    row["Description"] = oPropSet["Description"].Value.ToString();
                    oPropSet           = locDoc.PropertySets["Inventor User Defined Properties"];
                    if (Library.HasInventorProperty(oPropSet, "Расходник"))
                    {
                        row["IsConsumable"] = oPropSet["Расходник"].Value;
                    }
                    else
                    {
                        row["IsConsumable"] = false;
                    }
                    row["Quantity"] = BOMrow.TotalQuantity;
                    // Add row
                    resultTable.Rows.Add(row);
                }

                // Restore BOM merge settings
                bom.SetPartNumberMergeSettings(mergeEnabled, mergeExcludeList);
                if (specComponent.FullFileName != mainComponent.FullFileName)
                {
                    assembly.Close();
                }
                return(resultTable);
            }

            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().Name, MessageBoxButton.OK);
                return(null);
            }
        }
Exemplo n.º 27
0
        private void LoadStuff()
        {
            if (stock.Length > 0 && File.Exists(stock))
            {
                try
                {
                    log.PushActivity("Loading stock");
                    StockDoc = StockDocument.Load(stock);
                    if (StockDoc == null)
                    {
                        StockDoc = new StockDocument();
                    }
                }
                catch (Exception)
                {
                    StockDoc = new StockDocument();
                }
                log.PopActivity();
            }
            else
            {
                StockDoc = new StockDocument();
            }
            log.PushActivity("Loading document");
            B = new BOM();

            if (bom.Length > 0 && pnp.Length > 0)
            {
                String DirBaseName = Path.GetFileNameWithoutExtension(pnp);
                log.PushActivity("Processing " + DirBaseName);

                log.PushActivity("Loading BOM");
                log.AddString(String.Format("Loading BOM! {0},{1}", Path.GetFileName(bom), Path.GetFileName(pnp)));
                B.LoadJLC(bom, pnp);
                B.UpdateMountingTypesFromStock(StockDoc);
                log.PopActivity();

                if (gerberzip != null && File.Exists(gerberzip))
                {
                    Set = LoadGerberZip(gerberzip, log);
                }
                else
                {
                    Set = new GerberImageCreator();
                }
                Box = Set.BoundingBox;

                BuildPostBom();

                log.PopActivity();
            }
            else
            {
                log.AddString(String.Format("pnp and bom need to be valid! bom:{0} pnp:{1}", bom, pnp));
            }


            loaded = true;
            log.AddString("Done!");
            log.PopActivity();
        }
Exemplo n.º 28
0
        public List <INVENTORY_MOVEMENT> GetUsageByBatchAndPlantIdInPeriod(GetUsageByBatchAndPlantIdInPeriodParamInput input, List <BOM> bomMapList)
        {
            var mvtUsage = new List <string>()
            {
                EnumHelper.GetDescription(Core.Enums.MovementTypeCode.Usage261),
                EnumHelper.GetDescription(Core.Enums.MovementTypeCode.Usage262)
            };
            BOM    bom = new BOM();
            string bomMaterial;

            if (input.TrackLevel == 1)
            {
                bom         = bomMapList.Where(x => x.LEVEL1 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL1 : null;
            }
            else if (input.TrackLevel == 2)
            {
                bom         = bomMapList.Where(x => x.LEVEL2 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL2 : null;
            }
            else if (input.TrackLevel == 3)
            {
                bom         = bomMapList.Where(x => x.LEVEL3 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL3 : null;
            }
            else if (input.TrackLevel == 4)
            {
                bom         = bomMapList.Where(x => x.LEVEL4 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL4 : null;
            }
            else if (input.TrackLevel == 5)
            {
                bom         = bomMapList.Where(x => x.LEVEL5 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL5 : null;
            }
            else if (input.TrackLevel == 6)
            {
                bom         = bomMapList.Where(x => x.LEVEL6 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL6 : null;
            }
            else if (input.TrackLevel == 7)
            {
                bom         = bomMapList.Where(x => x.LEVEL7 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL7 : null;
            }
            else if (input.TrackLevel == 8)
            {
                bom         = bomMapList.Where(x => x.LEVEL8 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL8 : null;
            }
            else if (input.TrackLevel == 9)
            {
                bom         = bomMapList.Where(x => x.LEVEL9 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL9 : null;
            }
            else if (input.TrackLevel == 10)
            {
                bom         = bomMapList.Where(x => x.LEVEL10 == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.LEVEL10 : null;
            }
            else
            {
                bom         = bomMapList.Where(x => x.MATERIAL_ID == input.LastMaterialId).FirstOrDefault();
                bomMaterial = bom != null ? bom.MATERIAL_ID : null;
            }

            //if (bom != null)
            //{
            var data =
                _repository.Get(
                    c =>
                    c.BATCH == input.Batch && c.PLANT_ID == input.PlantId &&
                    mvtUsage.Contains(c.MVT) &&
                    c.MATERIAL_ID == input.LastMaterialId
                    //&& c.POSTING_DATE.HasValue
                    //&& c.POSTING_DATE.Value.Year <= input.PeriodYear && c.POSTING_DATE.Value.Month <= input.PeriodMonth
                    );


            return(data.ToList());
            //}
            //else
            //{
            //    return new List<INVENTORY_MOVEMENT>();
            //}
        }
Exemplo n.º 29
0
        protected void AddNewObject(DrawObject o)
        {
            graphicsList.UnselectAll();
            o.Selected = true;
            int    listCount = -1;
            int    maxValue = 0;
            int    left = 0, top = 0, tagid = -1, intflag = -1;
            string id   = "";
            string name = o.GetType().Name;

            switch (name)
            {
            case "BOM":
                listCount = graphicsList.BomVerify.Count;
                if (listCount > 0)
                {
                    var max = Int32.Parse(graphicsList.BomVerify.Max());
                    maxValue = Int32.Parse(listCount > 0 ? graphicsList.BomVerify.Max() : "0", System.Globalization.NumberStyles.HexNumber); //十六进制转十进制
                    if (maxValue == 255)                                                                                                     //限制只能添加两位十六进制位数
                    {
                        graphicsList.BomVerify.Remove("ff");
                        graphicsList.BomVerify.Remove("FF");
                        maxValue = Int32.Parse(graphicsList.BomVerify.Max(), System.Globalization.NumberStyles.HexNumber);     //取第二大值
                    }
                    BOM bom = (BOM)o.Clone(maxValue + 1);
                    left    = bom.RectangleLs.X;
                    top     = bom.RectangleLs.Y;
                    id      = bom.LogicIDTail;
                    tagid   = bom.TagIDBase;
                    intflag = bom.Flag;

                    if (tagid != 0)
                    {
                        //同步标志位
                        bom.TagIDBase = intflag;
                        Text bomprop = new Text();
                        bomprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        bomprop.Texttest = "";    // id;
                        bomprop.setTextDisplay(left, top - 25);
                        bomprop.ObjectID = intflag;
                        bomprop.TextType = "BOM_Logical_ID";
                        this.graphicsList.Add(bom);
                        this.graphicsList.Add(bomprop);
                    }
                    else
                    {
                        this.graphicsList.Add((BOM)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((BOM)o.Clone());
                }
                break;

            case "AGMChannel":
                listCount = graphicsList.AGMVerify.Count;
                if (listCount > 0)
                {
                    AGMChannel agmChannel = (AGMChannel)o.Clone(maxValue + 1);
                    left    = agmChannel.RectangleLs.X;
                    top     = agmChannel.RectangleLs.Y;
                    id      = agmChannel.LogicIDTail;
                    intflag = agmChannel.Flag;
                    tagid   = agmChannel.TagIDBase;
                    if (tagid != 0)
                    {
                        //同步标志位
                        agmChannel.TagIDBase = intflag;
                        Text agmChannelprop = new Text();
                        agmChannelprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        agmChannelprop.setTextDisplay(left, top - 25);
                        agmChannelprop.ObjectID = intflag;
                        agmChannelprop.TextType = "AGM_Logical_ID";
                        this.graphicsList.Add(agmChannel);
                        this.graphicsList.Add(agmChannelprop);
                    }
                    else
                    {
                        this.graphicsList.Add((AGMChannel)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((AGMChannel)o.Clone());
                }
                break;

            case "AGMChannelDual":
                listCount = graphicsList.AGMVerify.Count;
                if (listCount > 0)
                {
                    AGMChannelDual agmChannelDual = (AGMChannelDual)o.Clone(maxValue + 1);
                    left    = agmChannelDual.RectangleLs.X;
                    top     = agmChannelDual.RectangleLs.Y;
                    id      = agmChannelDual.LogicIDTail;
                    intflag = agmChannelDual.Flag;
                    tagid   = agmChannelDual.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        agmChannelDual.TagIDBase = intflag;
                        Text agmChannelDualprop = new Text();
                        agmChannelDualprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        agmChannelDualprop.setTextDisplay(left, top - 25);
                        agmChannelDualprop.ObjectID = intflag;
                        agmChannelDualprop.TextType = "AGMDual_Logical_ID";
                        this.graphicsList.Add(agmChannelDual);
                        this.graphicsList.Add(agmChannelDualprop);
                    }
                    else
                    {
                        this.graphicsList.Add((AGMChannelDual)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((AGMChannelDual)o.Clone());
                }
                break;

            case "AGMWallSingle":
                listCount = graphicsList.AGMWallSingleVerify.Count;

                if (listCount > 0)
                {
                    AGMWallSingle agmWallSingle = (AGMWallSingle)o.Clone(maxValue + 1);
                    left    = agmWallSingle.RectangleLs.X;
                    top     = agmWallSingle.RectangleLs.Y;
                    id      = agmWallSingle.LogicIDTail;
                    intflag = agmWallSingle.Flag;
                    tagid   = agmWallSingle.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        agmWallSingle.TagIDBase = intflag;
                        Text agmChannelDualprop = new Text();
                        agmChannelDualprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        agmChannelDualprop.setTextDisplay(left, top - 25);
                        agmChannelDualprop.ObjectID = intflag;
                        agmChannelDualprop.TextType = "AGMWallSingle_Logical_ID";
                        this.graphicsList.Add(agmWallSingle);
                        this.graphicsList.Add(agmChannelDualprop);
                    }
                    else
                    {
                        this.graphicsList.Add((AGMWallSingle)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((AGMWallSingle)o.Clone());
                }
                break;

            case "AGMWallDual":
                listCount = graphicsList.AGMWallDualVerify.Count;

                if (listCount > 0)
                {
                    AGMWallDual agmWallDual = (AGMWallDual)o.Clone(maxValue + 1);
                    left    = agmWallDual.RectangleLs.X;
                    top     = agmWallDual.RectangleLs.Y;
                    id      = agmWallDual.LogicIDTail;
                    intflag = agmWallDual.Flag;
                    tagid   = agmWallDual.TagIDBase;
                    if (tagid != 0)
                    {
                        //同步标志位
                        agmWallDual.TagIDBase = intflag;
                        Text agmChannelDualprop = new Text();
                        agmChannelDualprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        agmChannelDualprop.setTextDisplay(left, top - 25);
                        agmChannelDualprop.ObjectID = intflag;
                        agmChannelDualprop.TextType = "AGMWallDual_Logical_ID";
                        this.graphicsList.Add(agmWallDual);
                        this.graphicsList.Add(agmChannelDualprop);
                        if (HasInclude(graphicsList.AGMVerify, id))
                        {
                            MessageBox.Show("设备ID重复,同一车站同一设备类型不能有重复的设备ID!");
                        }
                    }
                    else
                    {
                        this.graphicsList.Add((AGMWallDual)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((AGMWallDual)o.Clone());
                }
                break;

            case "AGMWallDummy":
                listCount = graphicsList.AGMWallDummyVerify.Count;

                if (listCount > 0)
                {
                    AGMWallDummy agmWallDummy = (AGMWallDummy)o.Clone(maxValue + 1);
                    left    = agmWallDummy.RectangleLs.X;
                    top     = agmWallDummy.RectangleLs.Y;
                    id      = agmWallDummy.LogicIDTail;
                    intflag = agmWallDummy.Flag;
                    tagid   = agmWallDummy.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        agmWallDummy.TagIDBase = intflag;
                        Text agmChannelDualprop = new Text();
                        agmChannelDualprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        agmChannelDualprop.setTextDisplay(left, top - 25);
                        agmChannelDualprop.ObjectID = intflag;
                        agmChannelDualprop.TextType = "AGMWallDummy_Logical_ID";
                        this.graphicsList.Add(agmWallDummy);
                        this.graphicsList.Add(agmChannelDualprop);
                    }
                    else
                    {
                        this.graphicsList.Add((AGMWallDummy)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((AGMWallDummy)o.Clone());
                }
                break;

            case "TCM":
                listCount = graphicsList.TCMVerify.Count;
                if (listCount > 0)
                {
                    TCM tcm = (TCM)o.Clone(maxValue + 1);
                    left    = tcm.RectangleLs.X;
                    top     = tcm.RectangleLs.Y;
                    id      = tcm.LogicIDTail;
                    intflag = tcm.Flag;
                    tagid   = tcm.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        tcm.TagIDBase = intflag;
                        Text tcmprop = new Text();
                        tcmprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        tcmprop.setTextDisplay(left, top - 25);
                        tcmprop.ObjectID = intflag;
                        tcmprop.TextType = "TCM_Logical_ID";
                        this.graphicsList.Add(tcm);
                        this.graphicsList.Add(tcmprop);
                    }
                    else
                    {
                        this.graphicsList.Add((TCM)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((TCM)o.Clone());
                }
                break;

            case "TVM":
                listCount = graphicsList.TVMVerify.Count;
                if (listCount > 0)
                {
                    TVM tvm = (TVM)o.Clone(maxValue + 1);
                    left    = tvm.RectangleLs.X;
                    top     = tvm.RectangleLs.Y;
                    id      = tvm.LogicIDTail;
                    intflag = tvm.Flag;
                    tagid   = tvm.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        tvm.TagIDBase = intflag;
                        Text tvmprop = new Text();
                        tvmprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        tvmprop.setTextDisplay(left, top - 25);
                        tvmprop.ObjectID = intflag;
                        tvmprop.TextType = "TVM_Logical_ID";
                        this.graphicsList.Add(tvm);
                        this.graphicsList.Add(tvmprop);
                    }
                    else
                    {
                        this.graphicsList.Add((TVM)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((TVM)o.Clone());
                }
                break;

            case "SC":
                listCount = graphicsList.SCVerify.Count;

                if (listCount > 0)
                {
                    SC sc = (SC)o.Clone(maxValue + 1);
                    left    = sc.RectangleLs.X;
                    top     = sc.RectangleLs.Y;
                    id      = sc.LogicIDTail;
                    intflag = sc.Flag;
                    tagid   = sc.TagIDBase;

                    if (tagid != 0)
                    {
                        //同步标志位
                        sc.TagIDBase = intflag;
                        Text scprop = new Text();
                        scprop.TextFont = new Font("宋体", 9, FontStyle.Regular);
                        scprop.setTextDisplay(left, top - 25);
                        scprop.ObjectID = intflag;
                        scprop.TextType = "SC_Logical_ID";
                        this.graphicsList.Add(sc);
                        this.graphicsList.Add(scprop);
                    }
                    else
                    {
                        this.graphicsList.Add((SC)o.Clone());
                    }
                }
                else
                {
                    this.graphicsList.Add((SC)o.Clone());
                }
                break;

            default:
                this.graphicsList.Add(o.Clone());
                break;
            }
        }
Exemplo n.º 30
0
        // 변환 및 저장
        public void DoReplace()
        {
            string replacersJson = GetReplacersJson();

            string[]   replacer    = GetReplacers(replacersJson)[0];
            List <Smi> originRange = new SmiFile().FromTxt(replacer[0]).body;
            List <Smi> targetRange = new SmiFile().FromTxt(replacer[1]).body;

            bool complete = true;
            Dictionary <int, int> matches = new Dictionary <int, int>();
            {
                int i = 0, j = 0;
                for (; j < targetRange.Count; j++)
                {
                    if (targetRange[j].syncType != SyncType.frame)
                    {
                        continue;
                    }
                    while (i < originRange.Count && originRange[i].start < targetRange[j].start)
                    {
                        i++;
                    }
                    if (i >= originRange.Count)
                    {
                        break;
                    }
                    if (originRange[i].syncType != SyncType.frame)
                    {   // 목표 화면 싱크가 원본 화면 싱크와 겹치지 않으면 -1
                        matches.Add(j, -1);
                        complete = false;
                        continue;
                    }

                    if (originRange[i].start == targetRange[j].start)
                    {   // 목표 화면 싱크가 원본 화면 싱크와 겹치는 경우
                        matches.Add(j, i);
                    }
                    else
                    {   // 목표 화면 싱크가 원본 화면 싱크와 겹치지 않으면 -1
                        matches.Add(j, -1);
                        complete = false;
                    }
                }
            }

            string filesString = Script("getFiles").ToString();

            if (filesString.Length == 0)
            {
                Script("alert", new object[] { "파일이 없습니다." });
                return;
            }
            string[] files = filesString.Split('?');

            int           success = 0;
            List <string> skips   = new List <string>();

            foreach (string file in files)
            {
                Encoding encoding = BOM.DetectEncoding(file);

                bool    isChanged = false;
                SmiFile originSmi = null;
                int     i = 0, j = 0, shift = 0;

                StreamReader sr = null;
                try
                {
                    sr = new StreamReader(file, encoding);
                    string origin = sr.ReadToEnd();
                    originSmi = new SmiFile().FromTxt(origin);

                    for (; i < originSmi.body.Count; i++)
                    {
                        if (originSmi.body[i].text.Equals(originRange[0].text))
                        {
                            shift = originSmi.body[i].start - originRange[0].start;
                            bool isCorrect = true;

                            for (; j < originRange.Count; j++)
                            {
                                if (!originSmi.body[i + j].text.Equals(originRange[j].text))
                                {
                                    isCorrect = false;
                                    break;
                                }

                                if ((originSmi.body[i + j].syncType == SyncType.normal) &&
                                    (originSmi.body[i + j].start != originRange[j].start + shift))
                                {
                                    isCorrect = false;
                                    break;
                                }
                            }

                            if (isCorrect)
                            {
                                isChanged = true;
                                break;
                            }
                        }
                    }
                }
                catch { }
                finally { if (sr != null)
                          {
                              sr.Close();
                          }
                }

                if (isChanged)
                {
                    SmiFile targetSmi = new SmiFile()
                    {
                        header = originSmi.header,
                        footer = originSmi.footer
                    };

                    for (int k = 0; k < i; k++)
                    {
                        targetSmi.body.Add(originSmi.body[k]);
                    }

                    for (int k = 0; k < targetRange.Count; k++)
                    {
                        if (targetRange[k].syncType == SyncType.frame && matches[k] >= 0)
                        {
                            targetSmi.body.Add(new Smi()
                            {
                                start      = originSmi.body[i + matches[k]].start
                                , syncType = targetRange[k].syncType
                                , text     = targetRange[k].text
                            });
                        }
                        else
                        {
                            targetSmi.body.Add(new Smi()
                            {
                                start      = targetRange[k].start + shift
                                , syncType = targetRange[k].syncType
                                , text     = targetRange[k].text
                            });
                        }
                    }

                    for (int k = i + j; k < originSmi.body.Count; k++)
                    {
                        targetSmi.body.Add(originSmi.body[k]);
                    }

                    StreamWriter sw = null;
                    try
                    {
                        // 원본 파일의 인코딩대로 저장
                        sw = new StreamWriter(file, false, encoding);
                        sw.Write(targetSmi.ToTxt());
                        success++;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                    finally
                    {
                        if (sw != null)
                        {
                            sw.Close();
                        }
                    }
                }
                else
                {
                    skips.Add(file);
                }
            }

            // 변환했으면 변환 문자열 쌍을 기억해둠
            SaveDefaultReplacers(replacersJson);

            string msg = "파일 " + files.Length + "개 중 " + success + "개의 작업이 완료됐습니다.";

            if (!complete)
            {
                msg += "\n화면 싱크를 조정할 부분이 있습니다.";
            }

            if (skips.Count > 0)
            {
                msg += "\n제외 파일";
                foreach (string file in skips)
                {
                    msg += "\n" + file;
                }
            }

            Script("alert", new object[] { msg });
        }