예제 #1
0
        /// <summary>
        /// Create a new business partner
        /// </summary>
        /// <param name="sap">SAP connection</param>
        /// <param name="docDate">Document date</param>
        /// <param name="cardCode">Card name</param>
        /// <param name="items">Sales order items</param>
        /// <returns>Retrieve new object key</returns>
        public int Create(
            SAPConnection sap,
            DateTime docDate,
            string cardCode,
            List <Dictionary <string, string> > items
            )
        {
            IDocuments document = sap.Company.GetBusinessObject(BoObjectTypes.oOrders);

            document.DocDate    = docDate;
            document.DocDueDate = DateTime.Now;
            document.CardCode   = cardCode;

            for (int i = 0; i < items.Count; i++)
            {
                Dictionary <string, string> current = items[i];
                document.Lines.ItemCode  = current["ItemCode"];
                document.Lines.Quantity  = double.Parse(current["Quantity"]);
                document.Lines.UnitPrice = double.Parse(current["Price"]);

                if (i < items.Count - 1)
                {
                    document.Lines.Add();
                }
            }

            sap.CheckResponse(document.Add());
            return(int.Parse(sap.Company.GetNewObjectKey()));
        }
예제 #2
0
        private void AddClientButton_Click(object sender, EventArgs e)
        {
            IMan      man;                                          // Человек
            IDocument document;                                     // Документ
            IClient   client;                                       // Клиент

            if (_clientAfterRelinking == null)                      // Не даем создать еще одного клиента если он уже есть
            {
                man      = _man.Create();                           // Создать человек
                document = _document.Create();                      // Создать документ
                client   = _clients.Create();                       // Создать клиент

                man.Name       = clientNameTextBox.Text;            // Присвоить Имя с текстового поля
                man.Surname    = clientSurnameTextBox.Text;         // Присвоить Фамилия с текстового поля
                man.Patronymic = clientPatronymicTextBox.Text;      // Присвоить Отчество с текстового поля
                client.Address = ClientAddressTextBox.Text;

                document.Series = Convert.ToInt32(clientDocSeriesTextBox.Text);            // Присвоить Серия документа с текстового поля
                document.Number = Convert.ToInt32(clientDocNumberTextBox.Text);            // Присвоить Номер документа с текстового поля

                document.DataOfIssue = Convert.ToDateTime(clientDocDataIssueTextBox.Text); // Присвоить Дата получения документа с текстового поля

                document.PlaceOfIssue = clientDocGivesTextBox.Text;                        // Присвоить Кем выдан с текстового поля


                client.Man          = man;                          // Присвоить Клиента с текстового поля
                client.Man.Document = document;                     // Присвоить документ человеку

                _document.Add(document);                            // Добавить в базу документ
                _man.Add(man);                                      // Добавить в базу человека
                _clients.Add(client);                               // Добавить в базу клиента

                _clientAfterRelinking = client;                     // Привязывание клиента
            }
        }
        /// <summary>
        /// Add Document.
        /// Throws Exeption if failed instead of returnCode.
        /// Returns DocEntry
        /// </summary>
        /// <param name="documents"></param>
        /// <returns>Document Entry Key</returns>
        public static int AddEx(this IDocuments documents)
        {
            var returnCode = documents.Add();

            ErrorHelper.HandleErrorWithException(returnCode, "Could not Add Document");

            return(int.Parse(SboApp.Company.GetNewObjectKey()));
        }
예제 #4
0
 public static void InsertIntoNewDocument(string tmpFile, string address, string tooltip)
 {
     using (IWordApplication wordApplication = GetOrCreateWordApplication()) {
         if (wordApplication == null)
         {
             return;
         }
         wordApplication.Visible = true;
         wordApplication.Activate();
         // Create new Document
         object template        = string.Empty;
         object newTemplate     = false;
         object documentType    = 0;
         object documentVisible = true;
         using (IDocuments documents = wordApplication.Documents) {
             using (IWordDocument wordDocument = documents.Add(ref template, ref newTemplate, ref documentType, ref documentVisible)) {
                 using (ISelection selection = wordApplication.Selection) {
                     // Add Picture
                     using (IInlineShape shape = AddPictureToSelection(selection, tmpFile)) {
                         if (!string.IsNullOrEmpty(address))
                         {
                             object screentip = Type.Missing;
                             if (!string.IsNullOrEmpty(tooltip))
                             {
                                 screentip = tooltip;
                             }
                             try {
                                 using (IHyperlinks hyperlinks = wordDocument.Hyperlinks) {
                                     hyperlinks.Add(shape, screentip, Type.Missing, screentip, Type.Missing, Type.Missing);
                                 }
                             } catch (Exception e) {
                                 LOG.WarnFormat("Couldn't add hyperlink for image: {0}", e.Message);
                             }
                         }
                     }
                 }
                 try {
                     wordDocument.Activate();
                 } catch {
                 }
                 try {
                     wordDocument.ActiveWindow.Activate();
                 } catch {
                 }
             }
         }
     }
 }
예제 #5
0
        /// <summary>
        /// Метод. Создает новый документ и открывает диалоговое окно для его редактирования
        /// </summary>
        private void addButton_Click(object sender, EventArgs e)
        {
            IDocument       document;                                    // Документ
            DocumentForm    documentForm;                                // Форма редактирования документа
            DataGridViewRow selectedRow;                                 // Выделенная строка

            int  rowCount;                                               // Общее количество документов в списке
            int  selectedRowIndex;                                       // Индекс выделенной строки
            bool entityNeedSave;                                         // Флаг необходимости сохранения сущности

            rowCount = entitiesDataGridView.Rows.Count;                  // Получить общее количество документов в списке

            selectedRowIndex = 0;                                        // Задать индекс выделенной строки
            if (rowCount > 0)                                            // Проверить общее количество документов
            {
                selectedRow      = entitiesDataGridView.SelectedRows[0]; // Получить выделенную строку
                selectedRowIndex = selectedRow.Index;                    // Получить индекс выделенной строки
            }

            document = _documents.Create();                             // Создать документ

            documentForm = new DocumentForm(document);                  // Создать форму для редактирования документа

            documentForm.ShowDialog();                                  // Отобразить форму для редактирования документа

            entityNeedSave = documentForm.EntityNeedSave;               // Получить значение флага необходимости сохранения сущности

            if (entityNeedSave == true)                                 // Проверить флаг необходимости сохранения сущности
            {
                _documents.Add(document);                               // Добавить созданный документ в список
            }

            FillEntitiesDataGridView();                                 // Заполнить данными элемент отображения списка сущностей

            if (rowCount > 0)                                           // Проверить общее количество документов
            {
                SelectRow(selectedRowIndex);                            // Выделить строку
            }

            SetButtonActivity();                                        // Задать активность элементов управления
        }
예제 #6
0
        public ActionResult Create(Documents documents)
        {
            if (getCurrentUser() == null)
            {
                return(RedirectToAction("Index", "Login"));
            }
            else
            {
                try
                {
                    documents.dc_active_yn = "Y";
                    documents.dc_cre_by    = 12;
                    documents.dc_cre_date  = DateTime.Now;
                    idocuments.Add(documents);

                    return(RedirectToAction(nameof(Index)));
                }
                catch
                {
                    return(View());
                }
            }
        }
예제 #7
0
        public override async Task <TaskResponse> Execute(ISapDocumentInput input)
        {
            log.Info($"Begin to create a purchase order {((SAPOrderInput)input).Id}");

            TaskResponse response = new TaskResponse()
            {
                Success = true, Message = string.Empty
            };
            string message = string.Empty;

            try
            {
                var purchaseOrder = await _purchaseOrderService.GetAsync(((SAPOrderInput)input).Id);

                Company company = this.Connect(new SapSettingsInput {
                    Companydb = "SBO_KGT"                                                  /*tenant.SAPDatabase*/
                });

                IDocuments sapPurchaseOrder = (IDocuments)company.GetBusinessObject(BoObjectTypes.oPurchaseOrders);
                sapPurchaseOrder.DocType    = BoDocumentTypes.dDocument_Items;
                sapPurchaseOrder.DocDate    = DateTime.Now;                                      //purchaseOrder.DocDate;
                sapPurchaseOrder.DocDueDate = DateTime.Now;
                sapPurchaseOrder.CardCode   = "P000001";                                         //purchaseOrder.CardCode;
                sapPurchaseOrder.CardName   = "VAN HEUSEN DE CENTRO AMERICA, S.de R.L. de C.V."; //purchaseOrder.CardName;
                //sapPurchaseOrder.DocTotal = Convert.ToDouble(purchaseOrder.DocTotal);

                sapPurchaseOrder.DocCurrency     = purchaseOrder.DocCurrency;
                sapPurchaseOrder.Comments        = purchaseOrder.Comments;
                sapPurchaseOrder.SalesPersonCode = purchaseOrder.SlpCode;
                //sapPurchaseOrder.Series = 0;
                //sapPurchaseOrder.NumAtCard = string.Empty;

                if (sapPurchaseOrder.UserFields.Fields.Count > 0)
                {
                    sapPurchaseOrder.UserFields.Fields.Item("U_FacNom").Value           = "VAN HEUSEN DE CENTRO AMERICA, S.de R.L. de C.V.";
                    sapPurchaseOrder.UserFields.Fields.Item("U_Tipo_Facturacion").Value = "M";
                    sapPurchaseOrder.UserFields.Fields.Item("U_FacNit").Value           = string.Empty;
                    sapPurchaseOrder.UserFields.Fields.Item("U_FacFecha").Value         = purchaseOrder.DocDate.ToShortDateString();
                    sapPurchaseOrder.UserFields.Fields.Item("U_TIPO_DOCUMENTO").Value   = "FC";
                    sapPurchaseOrder.UserFields.Fields.Item("U_M2_UUID").Value          = purchaseOrder.U_M2_UUID.ToString();
                }

                foreach (var item in purchaseOrder.PurchaseOrderDetails)
                {
                    sapPurchaseOrder.Lines.ItemCode = item.ItemCode;
                    //sapPurchaseOrder.Lines.ItemDescription = item.Dscription;
                    sapPurchaseOrder.Lines.Quantity = item.Quantity;
                    sapPurchaseOrder.Lines.Price    = Convert.ToDouble(item.Price);
                    sapPurchaseOrder.Lines.Currency = item.LineCurrency;
                    sapPurchaseOrder.Lines.TaxCode  = item.TaxCode;
                    //sapPurchaseOrder.Lines.LineTotal = Convert.ToDouble(item.LineTotal);

                    //Settigs By Tenant
                    //sapPurchaseOrder.Lines.CostingCode = "303"/*tenant.CostingCode*/;
                    //sapPurchaseOrder.Lines.CostingCode2 = "3003-01"/*tenant.CostingCode2*/;
                    //sapPurchaseOrder.Lines.CostingCode3 = string.Empty;
                    //sapPurchaseOrder.Lines.AccountCode = string.Empty;
                    sapPurchaseOrder.Lines.Add();
                }

                /*foreach (var item in purchaseOrder.PurchaseOrderExpenses)
                 * {
                 *  sapPurchaseOrder.Expenses.ExpenseCode = item.ExpnsCode;
                 *  sapPurchaseOrder.Expenses.TaxCode = item.TaxCode;
                 *  sapPurchaseOrder.Expenses.DistributionMethod = BoAdEpnsDistribMethods.aedm_None;
                 *  sapPurchaseOrder.Expenses.LineTotal = Convert.ToDouble(item.LineTotal);
                 *  //sapPurchaseOrder.Expenses.UserFields.Fields.Item("U_TipoA").Value = item.U_TipoA;
                 *
                 *  sapPurchaseOrder.Expenses.Add();
                 * }*/

                if (sapPurchaseOrder.Add() == 0)
                {
                    message = $"Successfully added Purchase Order. DocEntry: {company.GetNewObjectKey()}";
                    purchaseOrder.Status   = 2;
                    purchaseOrder.RemoteId = Convert.ToInt32(company.GetNewObjectKey());
                    log.Info(message);
                }
                else
                {
                    message = $"Error Code: {company.GetLastErrorCode().ToString()} - {company.GetLastErrorDescription()}";
                    purchaseOrder.Status = 3;
                    response.Success     = false;
                    log.Error(message);
                }

                response.Message          = message;
                purchaseOrder.LastMessage = message;

                await _purchaseOrderService.UpdateAsync(purchaseOrder);

                ////recomended from http://www.appseconnect.com/di-api-memory-leak-in-sap-business-one-9-0/
                System.Runtime.InteropServices.Marshal.ReleaseComObject(purchaseOrder);
                purchaseOrder = null;
                company.Disconnect();
            }
            catch (Exception e)
            {
                response.Success = false;
                response.Message = e.Message;
                log.Error(e.Message);
            }

            return(response);
        }
예제 #8
0
        public override async Task <TaskResponse> Execute(ISapDocumentInput input)
        {
            log.Info($"Begin to create a order {((SAPOrderInput)input).Id}");

            TaskResponse response = new TaskResponse()
            {
                Success = true, Message = ""
            };
            String message = "";

            try
            {
                var order = await _orderService.GetAsync(((SAPOrderInput)input).Id);

                var tenant = await _tenantRepository.GetTenantById(order.TenantId);

                //fix for M2 dimension
                var client = await _clientService.GetByCardCodeAsync(order.CardCode);

                string dimension = client == null ? string.Empty : string.IsNullOrWhiteSpace(client.Dimension) ? string.Empty : client.Dimension;

                Company company = this.Connect(new SapSettingsInput {
                    Companydb = tenant.SAPDatabase
                });

                IDocuments salesOrder = (IDocuments)company.GetBusinessObject(BoObjectTypes.oOrders);
                salesOrder.CardCode        = order.CardCode;
                salesOrder.CardName        = client == null ? string.Empty : string.IsNullOrWhiteSpace(client.Name) ? string.Empty : client.Name;
                salesOrder.Comments        = order.Comment;
                salesOrder.Series          = order.Series;
                salesOrder.SalesPersonCode = order.AbpUser.SalesPersonId;
                salesOrder.DocDueDate      = order.CreationTime;

                if (salesOrder.UserFields.Fields.Count > 0)
                {
                    salesOrder.UserFields.Fields.Item("U_FacNit").Value  = client == null ? string.Empty : string.IsNullOrWhiteSpace(client.RTN) ? string.Empty : client.RTN;
                    salesOrder.UserFields.Fields.Item("U_M2_UUID").Value = order.U_M2_UUID.ToString();
                }

                foreach (var item in order.OrderItems.OrderBy(s => s.Code))
                {
                    salesOrder.Lines.ItemCode        = item.Code;
                    salesOrder.Lines.Quantity        = item.Quantity;
                    salesOrder.Lines.TaxCode         = item.TaxCode;
                    salesOrder.Lines.DiscountPercent = item.DiscountPercent;
                    salesOrder.Lines.WarehouseCode   = item.WarehouseCode;
                    //settigs by tenant
                    salesOrder.Lines.CostingCode = tenant.CostingCode;

                    salesOrder.Lines.CostingCode2 = tenant.CostingCode2;
                    salesOrder.Lines.CostingCode3 = dimension;
                    salesOrder.Lines.Add();
                }
                // add Sales Order
                if (salesOrder.Add() == 0)
                {
                    message      = String.Format("Successfully added Sales Order DocEntry: {0}", company.GetNewObjectKey());
                    order.Status = (int)OrderStatus.PreliminarEnSAP;
                    log.Info(message);
                }
                else
                {
                    message = "Error Code: "
                              + company.GetLastErrorCode().ToString()
                              + " - "
                              + company.GetLastErrorDescription();

                    response.Success = false;
                    response.Message = message;
                    order.Status     = (int)OrderStatus.ErrorAlCrearEnSAP;
                    log.Error(message);
                }

                order.LastMessage = message;
                await _orderService.UpdateAsync(order);

                //recomended from http://www.appseconnect.com/di-api-memory-leak-in-sap-business-one-9-0/
                System.Runtime.InteropServices.Marshal.ReleaseComObject(salesOrder);
                salesOrder = null;
                company.Disconnect();
            }catch (Exception e)
            {
                response.Success = false;
                response.Message = e.Message;
                log.Error(e.Message);
            }

            return(response);
        }
예제 #9
0
 public int Add(RoadFlow.Data.Model.Documents model)
 {
     return(dataDocuments.Add(model));
 }
예제 #10
0
        private void GenerateContourMap()
        {
            Surfer.Application app    = new Surfer.Application();
            IDocuments         docs   = app.Documents;
            IPlotDocument      Doc    = (IPlotDocument)docs.Add(SrfDocTypes.srfDocPlot); //創建一個空白繪圖文檔
            IShapes            Shapes = Doc.Shapes;

            #region 添加等值面
            IMapFrame contourMapFrame = Shapes.AddContourMap(path + "temp.grd");        //加載網格文件
            for (int i = 1; i <= contourMapFrame.Axes.Count; i++)
            {
                contourMapFrame.Axes.Item(i).Visible       = false;
                contourMapFrame.Axes.Item(i).MajorTickType = SrfTickType.srfTickNone;
                contourMapFrame.Axes.Item(i).ShowLabels    = false;
            }
            contourMapFrame.SetLimits(xMin: 140000,     //x最小值
                                      xMax: 370000,     //x最大者
                                      yMin: 2400000,    //y最小值
                                      yMax: 2800000     //y最大值
                                      );
            contourMapFrame.xMapPerPU = 23000;          //設置比例
            contourMapFrame.yMapPerPU = 20000;          //設置比例


            IContourMap contourMap = (IContourMap)contourMapFrame.Overlays.Item(1);

            /*
             * contourMap.ShowColorScale = true;										// 顯示對應色柱
             * contourMap.ColorScale.Top = 10;										//色柱y方向位置
             * contourMap.ColorScale.Left = contourMap.Left + contourMap.Width + 0.8;//色柱x方向位置
             * contourMap.ColorScale.Width = 1;									//色柱寬度
             * contourMap.ColorScale.Height = 10;										//色柱高度
             * contourMap.ColorScale.LabelFont.Size = 10;
             * contourMap.ColorScale.LabelFont.Face = "Time New Roman";
             * contourMap.ColorScale.LabelFrequency = 1;
             * contourMap.ColorScale.Name = "PM2.5 (μg/m3)";
             */

            contourMap.FillContours = true;    //添加顏色填充
            //通過文件加載顏色
            ILevels levels = contourMap.Levels;
            levels.LoadFile(path + "PM25.lvl");

            //加載系統顏色
            //contourMap.FillForegroundColorMap.LoadFile(path + "Rainbow.clr");
            //contourMap.ApplyFillToLevels(1, 1, 0);

            //使用灰色
            //contourMap.Levels.AutoGenerate(contourMap.Grid.zMin,contourMap.Grid.zMax,10);

            for (int i = 0; i < contourMap.Levels.Count; i++)
            {
                contourMap.Levels.Item(i + 1).ShowLabel  = false;                               //顯示等值線上的數值
                contourMap.Levels.Item(i + 1).ShowHach   = false;                               //
                contourMap.Levels.Item(i + 1).Line.Style = "Invisible";                         //不顯示線
            }

            contourMap.SmoothContours = SrfConSmoothType.srfConSmoothNone;       //平滑等值線邊界當前設置不平滑
            #endregion


            #region 添加邊界
            //後添加的會覆蓋在先前添加的圖片之上
            IMapFrame boundryMapFrame = Shapes.AddBaseMap(path + "city.shp", "Defaults=1");
            for (int i = 1; i <= boundryMapFrame.Axes.Count; i++)
            {
                boundryMapFrame.Axes.Item(i).Visible       = false;                   //隱藏軸線
                boundryMapFrame.Axes.Item(i).MajorTickType = SrfTickType.srfTickNone; //隱藏邊線
                boundryMapFrame.Axes.Item(i).ShowLabels    = false;                   //隱藏軸線上的坐標
            }
            boundryMapFrame.SetLimits(xMin: 140000,                                   //x最小值
                                      xMax: 370000,                                   //x最大者
                                      yMin: 2400000,                                  //y最小值
                                      yMax: 2800000                                   //y最大值
                                      );
            boundryMapFrame.xMapPerPU = 23000;
            boundryMapFrame.yMapPerPU = 20000;

            IBaseMap boundryBaseMap = (IBaseMap)boundryMapFrame.Overlays.Item(1);
            boundryBaseMap.Line.Width = 0.001;                          //設置邊線寬度
            #endregion

            string strWH = string.Format("width = {0:f0}, height = {1:f0}, KeepAspect = 1, ColorDepth = 32", 680, 1280); //設置輸出圖片的高度和寬度
            Doc.Export2(path + "Image.png", SelectionOnly: false, Options: strWH, FilterId: "png");                      //設置輸出圖片格式名
            Doc.Close(SrfSaveTypes.srfSaveChangesNo);                                                                    //不生成srf文件
            app.Quit();
            System.GC.Collect(System.GC.GetGeneration(app));
        }