2015年8月19日 星期三

如何在EEP 2012 JQ頁面上使用CKEditor

如何使用CKEditorEEP頁面
1.先在專案中加入CKEditor

2.Head載入ckeditor.js

3.將原先jqDataForm當中的textarea欄位予以隱藏。

4.jqDataform後面手動貼入一個Textarea(要加class=’ckeditor’)

5.body後面加入ckeditor置換textarea的指令。

6.head中增加ckeditorjqDataform欄位做資料交換的function

7.function設定在jqDataform的對應屬性,讓資料可於正確時機自動交換。



前端Source Code :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="F_KM.aspx.cs" Inherits="Template_JQuerySingle1" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="../ckeditorFull/ckeditor.js"></script>
    <script type="text/javascript">
        function downloadScript(val, rowData) {
            return '<a href="../handler/JqFileHandler.ashx?File=../Files/KM/' + val + '">' + val + '</a>';
        }
        function downloadScript1(val, rowData) {
            return '<a href="../handler/JqFileHandler.ashx?File=../Files/KMFB/' + val + '">' + val + '</a>';
        }
        function myFunction() {
            CKEDITOR.instances['editor12'].setData(decodeURIComponent($('#dataFormMasterKM').val()));
        }
        function myFunctionA() {
            $('#dataFormMasterKM').val(encodeURIComponent(CKEDITOR.instances['editor12'].getData()));
        }
        function myFunctionD() {
            CKEDITOR.instances['editor13'].setData(decodeURIComponent($('#dataFormDetailKM').val()));
        }
        function myFunctionDA() {
            $('#dataFormDetailKM').val(encodeURIComponent(CKEDITOR.instances['editor13'].getData()));
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <JQTools:JQScriptManager ID="JQScriptManager1" runat="server" />
            <JQTools:JQDataGrid ID="dataGridView" data-options="pagination:true,view:commandview" RemoteName="SeKM.T_KM" runat="server" AutoApply="True"
                DataMember="T_KM" Pagination="True" QueryTitle="Query" EditDialogID="JQDialog1"
                Title="知識管理" AllowAdd="True" AllowDelete="True" AllowUpdate="True" AlwaysClose="False" BufferView="False" CheckOnSelect="True" ColumnsHibeable="False" DeleteCommandVisible="True" DuplicateCheck="False" EditMode="Dialog" EditOnEnter="True" InsertCommandVisible="True" MultiSelect="False" NotInitGrid="False" PageList="10,20,30,40,50" PageSize="10" QueryAutoColumn="False" QueryLeft="" QueryMode="Window" QueryTop="" RecordLock="False" RecordLockMode="None" TotalCaption="Total:" UpdateCommandVisible="True" ViewCommandVisible="True">
                <Columns>
                    <JQTools:JQGridColumn Alignment="left" Caption="知識編號" Editor="text" FieldName="KMBH" Format="" MaxLength="50" Visible="true" Width="120" FormatScript="" />
                    <JQTools:JQGridColumn Alignment="left" Caption="知識主題" Editor="text" FieldName="Subject" Format="" MaxLength="16" Visible="true" Width="120" />
                    <JQTools:JQGridColumn Alignment="left" Caption="附件檔名" Editor="infofileupload" FieldName="FJMC" Format="" MaxLength="50" Visible="true" Width="120" FormatScript="downloadScript" />
                    <JQTools:JQGridColumn Alignment="left" Caption="關鍵字" Editor="text" FieldName="Keyword" Format="" MaxLength="100" Visible="true" Width="120" />
                    <JQTools:JQGridColumn Alignment="left" Caption="用戶編號" Editor="text" FieldName="USERID" Format="" MaxLength="20" Visible="true" Width="120" />
                </Columns>
                <TooItems>
                    <JQTools:JQToolItem Icon="icon-add" ItemType="easyui-linkbutton"
                        OnClick="insertItem" Text="新增" />
                    <JQTools:JQToolItem Icon="icon-save" ItemType="easyui-linkbutton" OnClick="apply"
                        Text="存檔" />
                    <JQTools:JQToolItem Icon="icon-undo" ItemType="easyui-linkbutton" OnClick="cancel"
                        Text="取消" />
                    <JQTools:JQToolItem Icon="icon-search" ItemType="easyui-linkbutton"
                        OnClick="openQuery" Text="查詢" />
                </TooItems>
                <QueryColumns>
                </QueryColumns>
            </JQTools:JQDataGrid>

            <JQTools:JQDialog ID="JQDialog1" runat="server" BindingObjectID="dataFormMaster" Title="知識管理">
                <JQTools:JQDataForm ID="dataFormMaster" runat="server" DataMember="T_KM" HorizontalColumnsCount="2" RemoteName="SeKM.T_KM" AlwaysReadOnly="False" Closed="False" ContinueAdd="False" disapply="False" DivFramed="False" DuplicateCheck="False" HorizontalGap="0" IsAutoPageClose="False" IsAutoPause="False" IsAutoSubmit="False" IsNotifyOFF="False" IsRejectNotify="False" IsRejectON="False" IsShowFlowIcon="False" ShowApplyButton="False" ValidateStyle="Hint" VerticalGap="0" OnLoadSuccess="myFunction" OnApply="myFunctionA" >

                    <Columns>
                        <JQTools:JQFormColumn Alignment="left" Caption="知識編號" Editor="text" FieldName="KMBH" Format="" maxlength="50" Width="180" ReadOnly="True" NewRow="False" />
                        <JQTools:JQFormColumn Alignment="left" Caption="知識主題" Editor="text" FieldName="Subject" maxlength="0" ReadOnly="False" Width="280" NewRow="True" />
                        <JQTools:JQFormColumn Alignment="left" Caption="附件檔名" Editor="infofileupload" FieldName="FJMC" Format="" maxlength="50" Width="180" NewRow="True" EditorOptions="filter:'rar|zip|7z|doc|docx',isAutoNum:true,upLoadFolder:'Files\\KM',showButton:true,showLocalFile:false,fileSizeLimited:'500'" />
                        <JQTools:JQFormColumn Alignment="left" Caption="關鍵字" Editor="infooptions" FieldName="Keyword" Format="" maxlength="100" Width="180" NewRow="True" EditorOptions="title:'關鍵字選擇',panelWidth:300,remoteName:'SeBasic.T_Keyword',tableName:'T_Keyword',valueField:'F_Keyword',textField:'F_Keyword',columnCount:2,multiSelect:true,openDialog:true,selectAll:false,selectOnly:false,items:[]" Visible="True" />
                        <JQTools:JQFormColumn Alignment="left" Caption="知識內容" Editor="textarea" EditorOptions="height:200" FieldName="KM" Format="" maxlength="0" NewRow="True" Visible="False" Width="360" ReadOnly="False" RowSpan="1" Span="1" />
                    </Columns>
                </JQTools:JQDataForm>
                <textarea id="editor12" class="ckeditor" cols="80" rows="10" name="editor12"></textarea>
                <JQTools:JQDataGrid ID="dataGridDetail" runat="server" AutoApply="False" DataMember="T_KMFB" EditDialogID="JQDialog2" Pagination="False" ParentObjectID="dataFormMaster" RemoteName="SeKM.T_KM" Title="知識補充明細" AllowAdd="True" AllowDelete="True" AllowUpdate="True" AlwaysClose="False" BufferView="False" CheckOnSelect="True" ColumnsHibeable="False" DeleteCommandVisible="True" DuplicateCheck="False" EditMode="Dialog" EditOnEnter="True" InsertCommandVisible="True" MultiSelect="False" NotInitGrid="False" PageList="10,20,30,40,50" PageSize="10" QueryAutoColumn="False" QueryLeft="" QueryMode="Window" QueryTitle="Query" QueryTop="" RecordLock="False" RecordLockMode="None" TotalCaption="Total:" UpdateCommandVisible="True" ViewCommandVisible="True" >
                    <Columns>
                        <JQTools:JQGridColumn Alignment="left" Caption="知識編號" Editor="text" FieldName="KMBH" Width="100" Visible="False" MaxLength="50" />
                        <JQTools:JQGridColumn Alignment="left" Caption="序號" Editor="text" FieldName="seq" Width="100" MaxLength="50" />
                        <JQTools:JQGridColumn Alignment="left" Caption="補充項目" Editor="text" FieldName="FBSubject" Width="100" MaxLength="50" />
                        <JQTools:JQGridColumn Alignment="left" Caption="補充附件" Editor="text" FieldName="FJMC" Width="100" FormatScript="downloadScript1" MaxLength="50" />
                        <JQTools:JQGridColumn Alignment="left" Caption="補充者" Editor="text" FieldName="FBUSERID" Frozen="False" IsNvarChar="False" MaxLength="20" QueryCondition="" ReadOnly="False" Sortable="False" Visible="True" Width="40">
                        </JQTools:JQGridColumn>
                        <JQTools:JQGridColumn Alignment="left" Caption="KM" Editor="text" FieldName="KM" Frozen="False" IsNvarChar="False" MaxLength="0" QueryCondition="" ReadOnly="False" Sortable="False" Visible="False" Width="80">
                        </JQTools:JQGridColumn>
                    </Columns>
                    <RelationColumns>
                        <JQTools:JQRelationColumn FieldName="KMBH" ParentFieldName="KMBH" />
                    </RelationColumns>
                    <TooItems>
                        <JQTools:JQToolItem Icon="icon-add" ItemType="easyui-linkbutton" OnClick="insertItem" Text="新增" />
                        <JQTools:JQToolItem Icon="icon-edit" ItemType="easyui-linkbutton" OnClick="updateItem" Text="修改" />
                        <JQTools:JQToolItem Icon="icon-remove" ItemType="easyui-linkbutton" OnClick="deleteItem" Text="刪除" />
                    </TooItems>
                </JQTools:JQDataGrid>
                <JQTools:JQDialog ID="JQDialog2" runat="server" BindingObjectID="dataFormDetail" Title="知識補充">
                    <JQTools:JQDataForm ID="dataFormDetail" runat="server" ParentObjectID="dataFormMaster" DataMember="T_KMFB" HorizontalColumnsCount="2" RemoteName="SeKM.T_KM" AlwaysReadOnly="False" Closed="False" ContinueAdd="False" disapply="False" DivFramed="False" DuplicateCheck="False" HorizontalGap="0" IsAutoPageClose="False" IsAutoPause="False" IsAutoSubmit="False" IsNotifyOFF="False" IsRejectNotify="False" IsRejectON="False" IsShowFlowIcon="False" ShowApplyButton="False" ValidateStyle="Hint" VerticalGap="0" OnApply="myFunctionDA" OnLoadSuccess="myFunctionD" >
                        <Columns>
                            <JQTools:JQFormColumn Alignment="left" Caption="知識編號" Editor="text" FieldName="KMBH" Width="180" Visible="False" MaxLength="50" />
                            <JQTools:JQFormColumn Alignment="left" Caption="序號" Editor="text" FieldName="seq" Width="180" ReadOnly="True" MaxLength="50" NewRow="False" />
                            <JQTools:JQFormColumn Alignment="left" Caption="補充項目" Editor="text" FieldName="FBSubject" Width="180" NewRow="True" RowSpan="1" Span="1" MaxLength="50" />
                            <JQTools:JQFormColumn Alignment="left" Caption="補充附件" Editor="infofileupload" FieldName="FJMC" Width="180" NewRow="False" EditorOptions="filter:'rar|zip|7z|doc|docx',isAutoNum:true,upLoadFolder:'Files\\KMFB',showButton:true,showLocalFile:false,fileSizeLimited:'500'" MaxLength="50" Visible="True" />
                            <JQTools:JQFormColumn Alignment="left" Caption="補充知識" Editor="text" FieldName="KM" MaxLength="16" NewRow="False" ReadOnly="False" RowSpan="1" Span="1" Visible="False" Width="180" />
                        </Columns>
                        <RelationColumns>
                            <JQTools:JQRelationColumn FieldName="KMBH" ParentFieldName="KMBH" />
                        </RelationColumns>
                    </JQTools:JQDataForm>
                    <textarea id="editor13" class="ckeditor" cols="80" rows="10" name="editor13"></textarea>
                    <JQTools:JQAutoSeq ID="JQAutoSeq1" runat="server" BindingObjectID="dataFormDetail" FieldName="seq" />
                </JQTools:JQDialog>
                <JQTools:JQDefault ID="defaultMaster" runat="server" BindingObjectID="dataFormMaster" EnableTheming="True">
                    <Columns>
                        <JQTools:JQDefaultColumn CarryOn="False" DefaultValue="自動編號" FieldName="KMBH" RemoteMethod="True" />
                    </Columns>
                </JQTools:JQDefault>
                <JQTools:JQValidate ID="validateMaster" runat="server" BindingObjectID="dataFormMaster" BorderStyle="NotSet" ClientIDMode="Inherit" Enabled="True" EnableTheming="True" EnableViewState="True" ViewStateMode="Inherit">
                </JQTools:JQValidate>
                <JQTools:JQDefault ID="defaultDetail" runat="server" BindingObjectID="dataFormDetail" BorderStyle="NotSet" ClientIDMode="Inherit" Enabled="True" EnableTheming="True" EnableViewState="True" ViewStateMode="Inherit">
                </JQTools:JQDefault>
                <JQTools:JQValidate ID="validateDetail" runat="server" BindingObjectID="dataFormDetail" BorderStyle="NotSet" ClientIDMode="Inherit" Enabled="True" EnableTheming="True" EnableViewState="True" ViewStateMode="Inherit">
                    <Columns>
                        <JQTools:JQValidateColumn CheckNull="True" FieldName="KMBH" RemoteMethod="True" ValidateType="None" />
                    </Columns>
                </JQTools:JQValidate>
            </JQTools:JQDialog>
        </div>
    </form>
</body>
    <script type="text/javascript">
        CKEDITOR.replace('editor12');
        CKEDITOR.replace('editor13');
    </script>
</html>

2015年5月4日 星期一

Memo 同事做的EXTRACT_TABLE_DATA (SAP可Join的 Read Table RFC)

先實做此一內建Function

FUNCTION EXTRACT_TABLE_DATA .
*"----------------------------------------------------------------------
*"*"區域介面:
*"  TABLES
*"      FIELDS STRUCTURE  ZSQL_CLAUSE_ELEMENTS
*"      FROMCLAUSE STRUCTURE  ZSQL_CLAUSE_ELEMENTS
*"      WHERECLAUSE STRUCTURE  ZSQL_CLAUSE_ELEMENTS
*"      DATA STRUCTURE  ZTABLEROWS
*"----------------------------------------------------------------------


*"----------------------------------------------------------------------
*" Copy selected fields from QUERY_TABLE to DATA_STRUCTURE
*"----------------------------------------------------------------------
  TYPE-POOLS: abap.
  DATA:
        columnName TYPE SO_TEXT,
        fieldDataDescrRef  TYPE REF TO abap_componentdescr,
        numberFields TYPE i,
        fieldDescr TYPE abap_componentdescr,
        fieldname TYPE string,
        fieldDescrTab TYPE abap_component_tab,
        rowStructDescr TYPE REF TO cl_abap_structdescr,
        rowReference TYPE REF TO data,
        returnRowString TYPE string,
        dataFieldString TYPE string,
        dataline LIKE data,
        fromClauseRow TYPE ZSQL_CLAUSE_ELEMENTS,
        fromClauseString TYPE string,
        whereClauseRow TYPE ZSQL_CLAUSE_ELEMENTS,
        whereClauseString TYPE string,
        fieldsRow TYPE ZSQL_CLAUSE_ELEMENTS.
  FIELD-SYMBOLS:
          <datarow> TYPE ANY,
          <datafield> TYPE ANY.


* CREATE DataStructure with field names
* Datatypes are read from fieldnames of FIELDS input table
  DESCRIBE TABLE FIELDS LINES numberFields.
  LOOP AT FIELDS INTO fieldsRow.
    fieldname = SY-TABIX.
* names need to be unique and must start with a char
    CONCATENATE 'string' fieldname INTO fieldname.
    CONDENSE fieldname.
    fieldDescr-name = fieldname.
* for dictionary lookup we need to change columnnames from Open SQL
* to dictionary notation
    columnName = fieldsRow-TEXT.
    REPLACE FIRST OCCURRENCE OF SUBSTRING '~' IN columnName WITH '-' RESPECTING CASE.

    fieldDescr-type ?= cl_abap_typedescr=>describe_by_name( columnName ).
    APPEND fieldDescr TO fieldDescrTab.
  ENDLOOP.

  rowStructDescr = cl_abap_structdescr=>create( fieldDescrTab ).

* now we create the actual data structure in memory
  create data rowReference type HANDLE rowStructDescr.
* finally we assign it to the Field-symbol used by the select statement
  ASSIGN rowReference->* TO <datarow>.
* End Create DataStructure

* to simplify calls we concatenate from and whereclause into strings
* this way caller doesn't need to check word wrappings
  fromClauseString = ''.
  LOOP AT FROMCLAUSE INTO fromClauseRow.
    CONCATENATE fromClauseString fromClauseRow-TEXT INTO fromClauseString.
  ENDLOOP.

  whereClauseString = ''.
  LOOP AT WHERECLAUSE INTO whereClauseRow.
    CONCATENATE whereClauseString whereClauseRow-TEXT INTO whereClauseString.
  ENDLOOP.

* Now start actual select operation
  SELECT (FIELDSFROM (fromClauseString) INTO <datarow> WHERE (whereClauseString).
* we read all fields of the current row, cast it to string and
* concatenate it into a dataline with division chars.
    CLEAR: returnRowString.
    DO numberFields TIMES.
      ASSIGN component sy-index of structure <datarow> to <datafield>.
      dataFieldString = <datafield>.
      CONCATENATE returnRowString '|' datafieldstring INTO returnRowString.
    ENDDO.
    dataline = returnRowString.
* finally dataline is added to the return table.
    INSERT dataline INTO TABLE data.
  ENDSELECT.

ENDFUNCTION.


使用範例





2015年4月29日 星期三

Domino 7 使用 ADO 做 Mysql 的 新增,修改,刪除及查詢

查詢

Sub Initialize
On Error Goto ErrHandle
Set session=New NotesSession
Set db=session.CurrentDatabase
Set ws=New NotesUIWorkspace
Set agent = session.CurrentAgent
Set currentLog = New NotesLog( db.Title+" - Agent - "+agent.Name+" on "+db.Server )
Set profile=db.GetProfileDocument("SystemProfile")
Call currentLog.OpenNotesLog( db.Server, profile.LogPath(0) )
Dim conn As Variant
Set conn = CreateObject ("ADODB.Connection")
ConnAdmin = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER="+profile.SqlServer(0)+"; DATABASE="+profile.SqlDatabase(0)+";UID="+profile.SqlAccount(0)+";PASSWORD="+profile.SqlPasswd(0)+"; OPTION=3"
conn.open ConnAdmin
Set uidoc=ws.CurrentDocument
Set doc=uidoc.Document
Set RSTT = CreateObject("ADODB.Recordset")
'SQL = "SELECT * FROM mm_budget WHERE MM_MARA_MATNR='"+doc.ItemNo(0)+"'"
SQL = "SELECT * FROM mm_budget WHERE MM_MARA_MATNR='"+uidoc.FieldGetText("ItemNo")+"' AND BGTDATE>'" +uidoc.FieldGetText("Result")+"'"
rstt.CursorLocation=3
rstt.open SQL, conn, 1,3
rstt.Sort = "BGTDATE DESC"
Call uidoc.FieldClear("A")
Call uidoc.FieldClear("B")
Call uidoc.FieldClear("C")
Call uidoc.FieldClear("D")
Call uidoc.FieldClear("E")
Call uidoc.FieldClear("F")
Do While Not rstt.eof
' For i = 0 To 5
' this.field=rstt.Fields(i).field
' this.value=rstt.Fields(i).value
' Set item = doc.AppendItemValue (field, value)
' Next
Call uidoc.FieldAppendText("A",Cstr(rstt.Fields(0).value)+Chr(10)+Chr(13))
Call uidoc.FieldAppendText("B",Cstr(rstt.Fields(4).value)+Chr(10)+Chr(13))
Call uidoc.FieldAppendText("C",Cstr(rstt.Fields(2).value)+Chr(10)+Chr(13))
Call uidoc.FieldAppendText("D",Cstr(rstt.Fields(5).value)+Chr(10)+Chr(13))
Call uidoc.FieldAppendText("E",Cstr(rstt.Fields(3).value)+Chr(10)+Chr(13))
Call uidoc.FieldAppendText("F",Cstr(rstt.Fields(1).value)+Chr(10)+Chr(13))
RSTT.MoveNext
Loop
rstt.close
conn.close
ErrHandle:
Print  "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl)
Call currentLog.LogError(0,"不明錯誤,請查詢Log 記錄 : " & "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl))
End Sub

新增

Sub Initialize
On Error Goto ErrHandle
Set session=New NotesSession
Set db=session.CurrentDatabase
Set ws=New NotesUIWorkspace
Set agent = session.CurrentAgent
Set currentLog = New NotesLog( db.Title+" - Agent - "+agent.Name+" on "+db.Server )
Set profile=db.GetProfileDocument("SystemProfile")
Call currentLog.OpenNotesLog( db.Server, profile.LogPath(0) )
Dim avarNew As Variant
avarNew = Split(profile.RecNo(0), "|")
Dim conn As Variant
Set conn = CreateObject ("ADODB.Connection")
ConnAdmin = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER="+profile.SqlServer(0)+"; DATABASE="+profile.SqlDatabase(0)+";UID="+profile.SqlAccount(0)+";PASSWORD="+profile.SqlPasswd(0)+"; OPTION=3"
conn.open ConnAdmin
Set uidoc=ws.CurrentDocument
Set doc=uidoc.Document
SQL = "INSERT INTO `mis`.`mm_budget` (`BGTTYPE`, `BGTDATE`, `QTY`, `MM_MARA_MATNR`, `MM_KOS_KOSTL`) VALUES ('"+avarNew(4)+"', '"+avarNew(1)+"', '"+avarNew(3)+"', '"+avarNew(0)+"', '"+avarNew(2)+"')"
Call currentlog.LogAction(SQL)
conn.execute(SQL)
conn.close
ErrHandle:
Print  "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl)
Call currentLog.LogError(0,"不明錯誤,請查詢Log 記錄 : " & "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl))
End Sub

刪除

Sub Initialize
On Error Goto ErrHandle
Set session=New NotesSession
Set db=session.CurrentDatabase
Set ws=New NotesUIWorkspace
Set agent = session.CurrentAgent
Set currentLog = New NotesLog( db.Title+" - Agent - "+agent.Name+" on "+db.Server )
Set profile=db.GetProfileDocument("SystemProfile")
Call currentLog.OpenNotesLog( db.Server, profile.LogPath(0) )
Dim conn As Variant
Set conn = CreateObject ("ADODB.Connection")
ConnAdmin = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER="+profile.SqlServer(0)+"; DATABASE="+profile.SqlDatabase(0)+";UID="+profile.SqlAccount(0)+";PASSWORD="+profile.SqlPasswd(0)+"; OPTION=3"
conn.open ConnAdmin
Set uidoc=ws.CurrentDocument
Set doc=uidoc.Document
SQL = "DELETE FROM `mis`.`mm_budget` WHERE `BGTID`='"+profile.RecNo(0)+"';"
Call currentlog.LogAction(SQL)
conn.execute(SQL)
conn.close
ErrHandle:
Print  "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl)
Call currentLog.LogError(0,"不明錯誤,請查詢Log 記錄 : " & "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl))
End Sub

修改

Sub Initialize
On Error Goto ErrHandle
Set session=New NotesSession
Set db=session.CurrentDatabase
Set ws=New NotesUIWorkspace
Set agent = session.CurrentAgent
Set currentLog = New NotesLog( db.Title+" - Agent - "+agent.Name+" on "+db.Server )
Set profile=db.GetProfileDocument("SystemProfile")
Call currentLog.OpenNotesLog( db.Server, profile.LogPath(0) )
Dim avarNew As Variant
avarNew = Split(profile.RecNo(0), "|")
Dim conn As Variant
Set conn = CreateObject ("ADODB.Connection")
ConnAdmin = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER="+profile.SqlServer(0)+"; DATABASE="+profile.SqlDatabase(0)+";UID="+profile.SqlAccount(0)+";PASSWORD="+profile.SqlPasswd(0)+"; OPTION=3"
conn.open ConnAdmin
Set uidoc=ws.CurrentDocument
Set doc=uidoc.Document
SQL = "UPDATE `mis`.`mm_budget` SET `MM_MARA_MATNR`='"+DoTrim(avarNew(1))+"',`MM_KOS_KOSTL`='"+DoTrim(avarNew(3))+"',`BGTTYPE`='"+DoTrim(avarNew(5))+"',`BGTDATE`='"+DoTrim(avarNew(2))+"', `QTY`='"+DoTrim(avarNew(4))+"' WHERE `BGTID`='"+DoTrim(avarNew(0))+"';"
Call currentlog.LogAction(SQL)
conn.execute(SQL)
conn.close
ErrHandle:
Print  "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl)
Call currentLog.LogError(0,"不明錯誤,請查詢Log 記錄 : " & "Error" & Str(Err) & ": " & Error$ & " on line " & Cstr(Erl))
End Sub

2015年4月22日 星期三

Domino利用JCO來透過RFC_RAED_TABLE取得SAP資料的範例

很多取SAP資料的小應用其實都不需要自己寫RFC,下面這個例子是讓用戶輸入料號及批號來取得品名及可用量和有效期。

import lotus.domino.*;
import java.util.*;
import com.sap.mw.jco.*;
public class SAPApprove extends AgentBase {
private Session session;
private AgentContext agentContext;
private Database db;
private String sapIP,sapClient,sapAccount,sapPasswd,sapLang,sapSysNo;
private JCO.Function function;
private JCO.Function function1;
private JCO.Function function2;
private JCO.Client client ;
private Log log;
private boolean isError=false;
private String errMsg="";
private String resultCode;
private String resultMsg ;
private String cnname ;
private String quantity ;
private String valid_date ;
private Document doc;

public void init(Session session,AgentContext agentContext) throws NotesException{
try {
this.session=session;
this.agentContext=agentContext;
this.db=agentContext.getCurrentDatabase();
Document profile=db.getProfileDocument("SystemProfile",null);
sapIP=profile.getItemValueString("SAPIP");
sapClient=profile.getItemValueString("SAPClient");
sapAccount=profile.getItemValueString("SAPAccount");
sapPasswd=profile.getItemValueString("SAPPasswd");
sapLang=profile.getItemValueString("SAPCode");
sapSysNo=profile.getItemValueString("SAPSysNO");
String logPath=profile.getItemValueString("LogPath");
log = session.createLog( db.getTitle()+" 's Agent "+agentContext.getCurrentAgent().getName()+" on " + db.getServer());
log.openNotesLog(db.getServer(),logPath);
Agent agent = agentContext.getCurrentAgent();
doc = db.getDocumentByID(agent.getParameterDocID());
System.out.println("Load Profile OK.");
}catch(Exception e) {
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","載入SAP 設定時,發生錯誤 !!");
}catch ( Exception ex){}
}
}


public void processApprove() {
boolean isok;
Item notifyitem;
try{
System.out.println("Begin JCO Connection....");
log.logAction("Begin JCO Connection....");
client = JCO.createClient(sapClient, sapAccount, sapPasswd, sapLang, sapIP, sapSysNo);
client.connect();
JCO.Repository repository = new JCO.Repository( "Notes", client );
JCO.Attributes attr = client.getAttributes();
IFunctionTemplate ftemplate = repository.getFunctionTemplate( "RFC_READ_TABLE" );
function = new JCO.Function( ftemplate );
function1 = new JCO.Function( ftemplate );
function2 = new JCO.Function( ftemplate );
System.out.println("Begin Load Note Procsess Documents....");
log.logAction("Begin Load Note Procsess Documents....");
if (doc != null) {
String sn=doc.getItemValueString("ItemNo").replaceAll("\\s+", "").trim();
String sn2=doc.getItemValueString("Batch").replaceAll("\\s+", "").trim();
System.out.println("Begin Process ItemNo: " + sn + "-Batch-" + sn2);
log.logAction("Begin Process ItemNo: " + sn + "-Btach-" + sn2);

//取中文名稱
function.getImportParameterList().setValue(",","DELIMITER");
function.getImportParameterList().setValue("MAKT","QUERY_TABLE");
JCO.ParameterList inputTables  = function.getTableParameterList();
            JCO.Table table = inputTables.getTable("OPTIONS");
table.appendRows(1);
table.setValue("MATNR EQ '"+ sn +"' ", "TEXT");
function.setTableParameterList(inputTables);
client.execute( function );
JCO.Table returnTable1 = function.getTableParameterList().getTable("DATA");
int records = returnTable1.getNumRows();
if (records == 0) {
cnname = "N/A";
}
else {
returnTable1.setRow(1);
String[] aArray = returnTable1.getString("WA").split(",");
cnname=aArray[3];
}

//取庫存量
function1.getImportParameterList().setValue(",","DELIMITER");
function1.getImportParameterList().setValue("MCHB","QUERY_TABLE");
JCO.ParameterList inputTables1  = function1.getTableParameterList();
            JCO.Table table1 = inputTables1.getTable("OPTIONS");
table1.appendRows(1);
table1.setValue("MATNR EQ '"+ sn +"' AND CHARG EQ '"+ sn2 +"'", "TEXT");
function1.setTableParameterList(inputTables1);
client.execute( function1);
JCO.Table returnTable2 = function1.getTableParameterList().getTable("DATA");
int records2 = returnTable2.getNumRows();
if (records2 == 0) {
quantity = "N/A";
}
else {
returnTable2.setRow(1);
System.out.println("Get Data: " + returnTable2.getString("WA"));
String[] bArray = returnTable2.getString("WA").split(",");
quantity=bArray[13];
}

//取有效期
function2.getImportParameterList().setValue(",","DELIMITER");
function2.getImportParameterList().setValue("MCH1","QUERY_TABLE");
JCO.ParameterList inputTables2  = function2.getTableParameterList();
            JCO.Table table2 = inputTables2.getTable("OPTIONS");
table2.appendRows(1);
table2.setValue("MATNR EQ '"+ sn +"' AND CHARG EQ '"+ sn2 +"'", "TEXT");
function2.setTableParameterList(inputTables2);
client.execute( function2);
JCO.Table returnTable3 = function2.getTableParameterList().getTable("DATA");
int records3 = returnTable3.getNumRows();
if (records3 == 0) {
valid_date = "N/A";
}
else {
returnTable3.setRow(1);
System.out.println("Get Data: " + returnTable3.getString("WA"));
String[] cArray = returnTable3.getString("WA").split(",");
valid_date = cArray[9];
}
session.setEnvironmentVar("AgentResult",cnname+","+quantity+","+valid_date);
}
}catch(java.lang.NoClassDefFoundError e){
e.printStackTrace();
try{
session.setEnvironmentVar("AgentResult","SAP 元件未安裝!!");
}catch ( Exception ex){}
}
catch(Exception e) {
e.printStackTrace();
try{
log.logError(0,e.getLocalizedMessage());
session.setEnvironmentVar("AgentResult","代理程式發生不明錯誤!!");
}catch(Exception err){}
}finally{
try{
  JCO.releaseClient(client);
log.close();
}catch(Exception err){}
}
}

public void NotesMain() {

try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
SAPApprove sapobj=new SAPApprove();
sapobj.init(session,agentContext);

Agent agent = agentContext.getCurrentAgent();

sapobj.processApprove();

} catch(Exception e) {
e.printStackTrace();
}
}
}