Add CodeBar to an Item using DI API (Add-On)

Hi you all.
I am developing a ADD -On for version 9 and I am having a problem to add the barcode of a item.
In this new version the barcode must already be created on the table obcd BEFORE assign it to an item, as opposed to 8 in which this was a text field and you could put anything you wanted .
My problem is that I have a method in my add-on that is responsible for generating an automatic bar code when the user creates a new item, but I can not directly assign this barcode to the item as before ( Item.BarCode = XXXXX ) as I explained previously . Also, if I do it this way a new window pops up to define barcodes and is not what I want.
I've checked the SDK and mention two objects: SAPbobsCOM.BarCodesService and SAPbobsCOM.BarCode .
The problem is that when I try to instantiate them, an error come up .
                                Dim As New SAPbobsCOM.BarCodesService BarCodeService
                                BarCode Dim As New SAPbobsCOM.BarCode
                                BarCode.ItemNo = Code
                                BarCode.BarCode = Generar_Codigo_Barras (Code)
                                BarCodeService.Add ( BarCode )
Someone have idea why this is happenning?
I have also seen that there is a class called SAPbobsCOM.ItemsBarCodes but I can not not instantiate eather
Thanks in advance
Greetings.

Try this:
* Crea o actualiza un código de barras para un artículo en el formato correspondiente
void LOG_Util::creaActualizaEANSBO(const string &asItemCode, const string &asEAN, const string &asForm, const string &asDForm)
    SAPbobsCOM::ICompanyServicePtr lpCmpSer;
    SAPbobsCOM::IBarCodesServicePtr lpBCSer;
    SAPbobsCOM::IBarCodeParamsPtr lpBCPar;
    SAPbobsCOM::IBarCodePtr lpBC;
    SAPbobsCOM::IRecordsetPtr lRS;
    ostringstream sql;
    long lUomEntry, lBcdEntry;
    lRS = g->GetCmp()->GetBusinessObject(SAPbobsCOM::BoRecordset);
    lUomEntry = dameUomEntry(asForm);
    // Verificamos la existencia del EAN en la ficha del artículo de SBO
    sql << "SELECT BcdEntry";
    sql << " FROM OBCD";
    sql << " WHERE ItemCode = '" << asItemCode << "'";
    sql <<    " And Bcdcode = '" << asEAN << "'";
    lRS->DoQuery(sql.str().c_str());
    lpCmpSer = g->GetCmp()->GetCompanyService();
    lpBCSer = lpCmpSer->GetBusinessService(SAPbobsCOM::BarCodesService);
    if (lRS->GetEoF() == VARIANT_TRUE)
        // Tenemos que crear el EAN
        lpBC = lpBCSer->GetDataInterface(SAPbobsCOM::bsBarCode);
        lpBC->PutItemNo(asItemCode.c_str());
        lpBC->PutUoMEntry(lUomEntry);
        lpBC->PutBarCode(asEAN.c_str());
        lpBC->PutFreeText(asDForm.c_str());
        lpBCSer->Add(lpBC);
        lpBC.Release();
    else
        // Tenemos que actualizar el EAN
        lBcdEntry = lRS->GetFields()->Item("BcdEntry")->GetValue();
        lpBCPar = lpBCSer->GetDataInterface(SAPbobsCOM::bsBarCodeParams);
        lpBCPar->PutAbsEntry(lBcdEntry);
        lpBC = lpBCSer->Get(lpBCPar);
        lpBC->PutUoMEntry(lUomEntry);
        lpBC->PutFreeText(asDForm.c_str());
        lpBCSer->Update(lpBC);
        lpBC.Release();
        lpBCPar.Release();
    lpBCSer.Release();
    lRS.Release();

Similar Messages

  • How to update 500 list items using Rest API

    Hi All,
    i have requirement that is "required to update 500 list items using rest Api".
    how can i do it,please share your thoughts with me.
    Thanks,
    Madhu.

    Didn't get you correctly, if you asking reference for REST API to update list items please refer below links
    http://msdn.microsoft.com/en-us/library/office/jj164022(v=office.15).aspx
    Destin -MCPD: SharePoint Developer 2010, MCTS:SharePoint 2007 Application Development

  • Error Add Item using DI API 2007  B

    Sirs,
         I gettin a error on add a item using a follow code:
                       If m_Item.GetByKey('100') = True Then
                            m_Item.ItemType = ItemTypeEnum.itItems
                            m_Item.ItemsGroupCode = 1
                            m_Item.ItemClass = ItemClassEnum.itcMaterial 
    'This line ocorred a error 'oToBP.ItemClass = {"Property 'ItemClass' of 'Item' is invalid"}
                            lErrorCode = m_Item.Update()
                        Else
                            lErrorCode = 1
                        End If
    Please,
    I'm waiting a urgent response .
    Great.
    Fábio Nascimento

    Fabio,
    In 2007 A the ItemsgroupCode start at 100 and not 1.
    Perhaps this is your problem.
    Christophe

  • How to add a polygon to mapviewer using Javascript API

    Hi,
    I am using JavaScript API for the MapViewer.
    Using redlining tool, my application allows user to draw polygon onto the map.
    I would like to have union, difference and intersect tools. I know the back end logic can be done using using JTS or SDO_Union, SDO_difference, and SDO_intersection. but how do i display the result polygon on the map? Note that I am not going to store the polygon in the database.
    Thanks for any ideas.

    Hi,
    If I understand well you are using Oracle Maps. User do some redlining, then you somehow makes FOI polygons. Then you get the coordinates of the polygons and send them to the back-end where you can use spatial functions and get the coordinates of the new polygon.
    You can store those coordinates in i.e. hidden input field on page (if you use JSF it is very simple) and then use JavaScript to parse them and Oracle Maps API to create new FOI polygon and add it to mapviewer object. One disadvantage of this concept is that reloading of page (submit) is necessary.
    Branislav

  • Add user to sharepoint group using REST API

    I am trying to add a user to sharepoint group with following code
    serviceUrl= Appweb + "/_api/SP.AppContextSite(@target)/web/sitegroups("+GroupId+")/users?@target='host web'";
        $.ajax({
            url: serviceUrl,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            body: "{'__metadata': { 'type': 'SP.User' },'LoginName':'i:0#.f|membership|'+email }",
      headers: {"accept":"application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest":$("#__REQUESTDIGEST").val()
        async: false,
      success: function (data) {
               alert('success');
      error: function (data) {
                 alert('fail');
    The request goes to error function. Response of the request is Microsoft.SharePoint.Client.InvalidClientQueryException and message is A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was
    expected
    I tried the sample from following link but fail it
    https://msdn.microsoft.com/en-us/library/office/dn531432.aspx

    Hi,
    Per my understanding, you might want to add an user to a SharePoint group in host web from a SharePoint Hosted App using REST API.
    Here is a working demo for your reference:
    var hostweburl;
    var appweburl;
    $(document).ready(function () {
    //Get the URI decoded URLs.
    hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
    appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    // Resources are in URLs in the form:
    // web_url/_layouts/15/resource
    var scriptbase = hostweburl + "/_layouts/15/";
    // SP.RequestExecutor.js to make cross-domain requests
    $.getScript(scriptbase + "SP.RequestExecutor.js", loadPage);
    // Utilities
    // Retrieve a query string value.
    // For production purposes you may want to use a library to handle the query string.
    function getQueryStringParameter(paramToRetrieve)
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1)
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve) return singleParam[1];
    function addUsersInGroup() {
    var executor;
    // Initialize the RequestExecutor with the app web URL.
    executor = new SP.RequestExecutor(appweburl);
    executor.executeAsync({
    url: appweburl + "/_api/SP.AppContextSite(@target)/web/sitegroups(8)/users?@target='" + hostweburl + "'",
    method: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    body: "{'__metadata': { 'type': 'SP.User' },'LoginName':'i:0#.f|membership|[email protected]'}",
    headers: {
    "Accept": "application/json; odata=verbose",
    "content-type": "application/json;odata=verbose",
    "X-RequestDigest":$("#__REQUESTDIGEST").val()
    success: addUsersInGroupSuccessHandler,
    error: addUsersInGroupErrorHandler
    function addUsersInGroupSuccessHandler(data)
    console.log(data);
    var jsonObject = JSON.parse(data.body);
    console.log(jsonObject);
    function addUsersInGroupErrorHandler(data)
    console.log(data);
    var jsonObject = JSON.parse(data.body);
    console.log(jsonObject);
    Thanks 
    Patrick Liang
    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact
    [email protected].

  • Error adding file type item using portal api

    We are using portal 3.0.8.
    I can add text and url type items fine but when i try to add a file type item, i get following error.
    ERROR at line 1:
    ORA-29532: Java call terminated by uncaught Java exception: java.lang.SecurityException: relative
    pathnames are not allowed(c:/abc.txt)
    ORA-06512: at "PORTAL30.WWSBR_API", line 24
    ORA-06512: at "PORTAL30.WWSBR_API", line 272
    ORA-06512: at line 4
    Please help.
    Thanks
    null

    Manoj,
    Please try to define a reproducible test case. Is this happening in all content area? Is it happening with all files, or only particular ones? What platform are you running on? What version of the database are you using?
    Have you checked your repository for invalid objects? If any exist, please try to recompile them.
    Thanks,
    Jerry

  • Create List Item using REST API

    Hi All
      I try create list item using REST in SharePoint 2013.  when code is try add new item in list , getting error :
    A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was expected.
    Please help me
    function addData() {
    var title = $('#txtTitile').val();
    //alert(title);
    var items = {
    __metadata: { "Type": "SP.Data.OrderDetailsListItem"},
    Title:title
    var exec = new SP.RequestExecutor(appweburl);
    exec.executeAsync(
    url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists/getbytitle('OrderDetails')/Items?@target='" + hostweburl + "'",
    method: "POST",
    data: JSON.stringify(items),
    headers: {
    Accept: "application/json;odata=verbose",
    "Content-Type": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
    success: function (data) { alert(JSON.parse(data)); },
    error: function (error)
    { alert(JSON.stringify(error)); }
    with Regards Sivam

    Hi,                                                             
    Here is a demo which works in my environment for your reference:
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function()
    $("#Button1").click(function(){
    createListItemWithDetails("list2", "http://sp2013sps", "item1");
    // Getting the item type for the list
    function GetItemTypeForListName(name) {
    //alert("GetItemTypeForListName: "+name);
    return"SP.Data." + name.charAt(0).toUpperCase() + name.slice(1) + "ListItem";
    // CREATE Operation
    // listName: The name of the list you want to get items from
    // siteurl: The url of the site that the list is in. // title: The value of the title field for the new item
    // success: The function to execute if the call is sucesfull
    // failure: The function to execute if the call fails
    function createListItemWithDetails(listName, siteUrl, title) {
    var itemType = GetItemTypeForListName(listName);
    //alert("itemType :"+itemType);
    var item = {
    "__metadata": { "type": itemType },
    "Title": title
    $.ajax({
    url: siteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
    type: "POST",
    contentType: "application/json;odata=verbose",
    data: JSON.stringify(item),
    headers: {
    "Accept": "application/json;odata=verbose",
    "X-RequestDigest": $("#__REQUESTDIGEST").val()
    success: function (data) {
    location.href=location.href;
    //success(data);
    error: function (data) {
    alert("error");
    //failure(data);
    </script>
    <input id="Button1" type="button" value="Run Code"/>
    Best regards
    Patrick Liang
    TechNet Community Support

  • How to add discussions to Collaboration Room using Rooms API

    Hi All,
    How to add discussions to any room using the Rooms API?
    I looked at the NW04s javadocs, but could not find which would help?
    Any pointers will be appreciated.
    Regards,Sandip

    Hi All,
    Any help!
    Any help from SAP? Are the discussion APIs available?
    Any input is appreciated. Thanks
    Regards
    Sandip
    Message was edited by:
            Sandip Agarwal

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

  • Update List Items using REST API - Keep Getting 400 Bad Request

    I am using code from the following answer:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/40833576-5853-4ca4-95cf-b5b1d69f465f/sharepoint-rest-and-c-sample-to-update-list-item?forum=sharepointdevelopment
    I am having a tough time figuring out the issue though.  I have been able to retrieve list items, but now I want to update those items.  This is the following code just to get the digest information with passing in credentials:
    public static string GetFormDigest(System.Net.NetworkCredential cred)
    string formDigest = null;
    string resourceUrl = "https://SITEURL/_api/contextinfo";
    HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
    wreq.Credentials = cred;
    wreq.Method = "POST";
    wreq.Accept = "application/json;odata=verbose";
    wreq.ContentLength = 0;
    wreq.ContentType = "application/json";
    string result;
    WebResponse wresp = wreq.GetResponse();
    using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
    result = sr.ReadToEnd();
    var jss = new JavaScriptSerializer();
    var val = jss.Deserialize<Dictionary<string, object>>(result);
    var d = val["d"] as Dictionary<string, object>;
    var wi = d["GetContextWebInformation"] as Dictionary<string, object>;
    formDigest = wi["FormDigestValue"].ToString();
    Console.WriteLine(formDigest);
    return formDigest;
    Then the following code is used:
    string result = string.Empty;
    Uri uri = new Uri(sharepointUrl.ToString() + "/_api/Web/lists/getByTitle('DemoList')/items(1)");
    HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
    wreq.Credentials = cred;
    wreq.Method = "POST";
    wreq.Accept = "application/json; odata=verbose";
    wreq.ContentType = "application/json; odata=verbose";
    wreq.Headers.Add( "X-HTTP-Method","MERGE");
    wreq.Headers.Add( "IF-MATCH", "*");
    wreq.Headers.Add("X-RequestDigest", GetFormDigest(cred));
    string stringData = "{'__metadata': { 'type': 'SP.Data.DemoListListItem' }, 'Title': 'updated!'}";
    wreq.ContentLength = stringData.Length;
    StreamWriter writer = new StreamWriter(wreq.GetRequestStream());
    writer.Write(stringData);
    writer.Flush();
    try {
    WebResponse wresp2 = wreq.GetResponse();
    using (StreamReader sr = new StreamReader(wresp2.GetResponseStream()))
    result = sr.ReadToEnd();
    catch (Exception e) { Console.WriteLine("An error occurred: '{0}'", e); }
    It errors out when it tries to send the command to Sharepoint.  I am NOT using a sharepoint hosted app.  I just wanted to directly contact sharepoint and update items.  Any help or suggestions would be greatly appreciated!
    Thanks,
    Priyank
     

    I just found some other code that seemed to work on editing a title and edited it kind of guessing it would work and it did!
    This is the code that ended working using the same digest code from above:
    Console.WriteLine("\n Newer Fancier Code \n");
    Uri uri = new Uri("https://SHAREPOINTURL/_api/web/lists/GetByTitle('Demo')/items(1)");
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.ContentType = "application/json;odata=verbose";
    request.Headers["X-RequestDigest"] = GetFormDigest(cred);
    request.Headers["X-HTTP-Method"] = "MERGE";
    request.Headers["IF-MATCH"] = "*";
    request.Credentials = cred;
    request.Accept = "application/json;odata=verbose";
    request.Method = "POST";
    string stringData = "{ '__metadata': { 'type': 'SP.ListItem' }, 'Location': 'updatedinfo' }";
    request.ContentLength = stringData.Length;
    StreamWriter writer = new StreamWriter(request.GetRequestStream());
    writer.Write(stringData);
    writer.Flush();
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    Just fyi if anyone was wondering.  Next, I'm going to be trying to update multiple fields, possibly multiple items if possible if anyone knows how to do that.

  • Add Goods Receipt using DI API

    Hi all,
    I want to add a new Goods Receipt using DI API, for each of the lines:
            oBatchReceipt.Lines.SetCurrentLine(1)
            oBatchReceipt.Lines.ItemCode = "ItemA"
            oBatchReceipt.Lines.WarehouseCode = "WH01"
            oBatchReceipt.Lines.Quantity = 1000
    instead of entering the unitcost of the item, i want to enter the line total.
    (unitcost or oBatchReceipt.Lines.Price is commented out)
            'oBatchReceipt.Lines.Price = costUnit
            oBatchReceipt.Lines.LineTotal = 1563
    so, when the Goods Receipt is added, there is no error popped up, but the total of created Goods Receipt is 0 (zero).
    I want to use the LineTotal instead of Price. Using the SBO system UI, user can enter quantity and linetotal and sytem will automatically calculate the price. But using DI API, i dont think it works because someone from forum says that LineTotal is NOT read/write property as written in SDK documentation.
    Anyone knows about this issue?
    Thanks.
    Cheers'
    erwine

    Hi Erwine Sukardy ,
                                   For eg.  you have used  an item  named as  " ItemA". Please go to the "Item Mater Data " . Set the unitprice as you required .Then no need to enter unitprice at line level using DIAPI .
                                If unitprice exists in item master data then . It will automatically calculates the LineTotal.
                          Hope it helps....,
    Best Regards
    V.Rangarajan

  • Error using DI API on Item Revaluation

    Dear All
    While on Revaluation of Item using DI API System gives error meaasage as "Internal Error 5002" ans displaya 'Material Revaluation failed'.
    Can any one help me to find the reason for this error and how to overcome the situation?
    With regards
    Aloke

    Dear Siva
    Following is the code I am using for revaluation of items which is giveing "Internal Error 5002':
    Dim lMaterialRevaluation As SAPbobsCOM.MaterialRevaluation
            lMaterialRevaluation = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oMaterialRevaluation)
            For li As Integer = 0 To ls_Lines.Length - 1
                If ls_Lines(li).Split(vbTab).Length <> 5 Then
                    My.Computer.FileSystem.WriteAllText(ls_OutFileName, lnl_SrlNo & "--> Can't Read in the data in Line " & li + 1, True)
                    My.Computer.FileSystem.WriteAllText(ls_OutFileName, vbNewLine, True)
                    lnl_SrlNo += 1
                    Continue For
                End If
                ls_ItemCode = ls_Lines(li).Split(vbTab)(0).Trim
                ls_WareHouseCode = ls_Lines(li).Split(vbTab)(1).Trim
                ld_Price = ls_Lines(li).Split(vbTab)(2).Trim
                li_IncAccount = ls_Lines(li).Split(vbTab)(3).Trim
                li_DecAccount = ls_Lines(li).Split(vbTab)(4).Trim
                lMaterialRevaluation.Lines.SetCurrentLine(li)
                lMaterialRevaluation.Lines.ItemCode = ls_ItemCode
                lMaterialRevaluation.Lines.WarehouseCode = ls_WareHouseCode
                lMaterialRevaluation.Lines.Price = ld_Price
                lMaterialRevaluation.Lines.RevaluationIncrementAccount = li_IncAccount
                lMaterialRevaluation.Lines.RevaluationDecrementAccount = li_DecAccount
                lMaterialRevaluation.Lines.Add()
            Next
            Dim li_Ret As Integer
            li_Ret = lMaterialRevaluation.Add
            If li_Ret = 0 Then
                MsgBox("Material Revaluation Completed")
                System.Runtime.InteropServices.Marshal.ReleaseComObject(lMaterialRevaluation)
            Else
                oCompany.GetLastError(lErrCode, sErrMsg)
                MsgBox(sErrMsg & ", Material Revaluation failed")
            End If
    Can you or any one else suggest where the error lies.
    Thanks & with regards
    Aloke
    Edited by: ALOKE BANDYOPADHYAY on Jul 5, 2011 3:01 PM

  • Add Multiple Detail Items Using the Same Query String Parameter

    I am using InfoPath 2010 and SharePoint 2010. 
    I have 2 forms libraries - Expense and Expense Details. 
    The 2 libraries are linked via a custom site column Expense ID. 
    The Expense form contains the main header type info you would typically find on an expense report; e.g., name, purpose, department, etc. 
    The Expense Details form contains multiple detail expenses related to the main expense report such as airfare, rental car, etc. 
    I have created a page that displays an expense report with all of the related expense detail items. 
    The page contains a link to add a new expense detail and passes the Expense ID of the Expense form to the Expense Detail form. 
    This all works fine.  The problem comes in after the first expense detail form is submitted. 
    I can successfully submit the first detail item.  However, the expense detail form loses the Expense ID that was passed to it after the first expense detail form has been submitted. 
    The parameter still shows in the URL but the detail form no longer shows the value of the parameter. 
    What do I need to do in order to be able to add multiple expense detail items using the same Expense ID that was passed to the form? 
    I have tried using a Submit Behavior of Open a new form, Close the form, and Leave the form open. 
    None of these options give me what I need.  Thanks for your help.
    pam

    Laura Rogers Blog
    In case anyone stumbles upon this looking for an answer. Laura Rogers has the answer found in the comments section of her blog above.  It’s not the best but it
    does work. You have to add an extra Info Path Web Form for it to work. I know, you can roll your eyes.<o:p></o:p>
    Steps.<o:p></o:p>
    1. Add Query String<o:p></o:p>
    2. Add the extra Info Path form to the page. This form will be a hidden on the page and will receive the value from the query string.<o:p></o:p>
    3. Add your original Info Path form and have it receive a parameter from the hidden Info Path form.<o:p></o:p>
    Now, when you hit save and it opens a new form the 3 Info Path form will function properly. <o:p></o:p>

  • Use UWL API in a Servet and access the servlet via URL

    Hi All,
    Actually I want to write a servlet from which I will access the uwl items using UWL APIs. And then I will submit HTTP Request to this servlet via url and want to get the UWL items in response. Is it Possible. I know that it is possible to access uwl items from JSPDynpage but is it possible to use it via servlet. If possible please give me some idea. what are the prerequisite.
    Thanks and Regards
    Avijit

    Hello,
    I see your thread is still unanswered, were you able to resolve the problem yourself (if so can you share with others who may have the same problem)? If so can you add anymore details which may help someone else to find an answer?  Or is it ok to mark this post as assumed answered?
    Beth Maben
    EP - Senior Support Consultant II
    SAP Active Global Support
    Global Support Centre Ireland
    **SDN Forum Moderator:
    SAP Enterprise Portal: Application Integration
    **SDN Universal Worklist Wiki:
    http://wiki.sdn.sap.com/wiki/x/ehU

  • Featching Data From The Data Base Using DI API in Matrix

    Hi
       All of u i am shahid i faced a problem when i retrive
       the selected data from the data base using matrix plz.
       Healp me!.
       Thanks
       Mohd Shahid.
       SAP Techinical Consultent
      Option Strict Off
    Option Explicit On
    Friend Class UseMatrix
        '// This parameter will use us to manipulate the
        '// SAP Business One Application
        Private WithEvents SBO_Application As SAPbouiCOM.Application
        Private oForm As SAPbouiCOM.Form
        Private oMatrix As SAPbouiCOM.Matrix
        Private oColumns As SAPbouiCOM.Columns
        Private oColumn As SAPbouiCOM.Column
        '// declareing a DB data source for all the Data binded columns
        Private oDBDataSource As SAPbouiCOM.DBDataSource
        '// declaring a User data source for the "Remarks" Column
        Private oUserDataSource As SAPbouiCOM.UserDataSource
        ' This Function is called automatically when an instance
        ' of the class is created.
        ' Indise this function
        Public Sub New()
            MyBase.New()
            '// set SBO_Application with an initialized application object
            SetApplication()
            '// Create the UI
            CreateFormWithMatrix()
            '// Add Data Sources to the Form
            AddDataSourceToForm()
            '// Bind the Form's items with the desired data source
            BindDataToForm()
            '// Load date to matrix
            GetDataFromDataSource()
            '// Make the form visible
            oForm.Visible = True
        End Sub
        Private Sub SetApplication()
            '// Use an SboGuiApi object to establish connection
            '// with the SAP Business One application and return an
            '// initialized appliction object
            Dim SboGuiApi As SAPbouiCOM.SboGuiApi
            Dim sConnectionString As String
            SboGuiApi = New SAPbouiCOM.SboGuiApi
            '// by following the steps specified above, the following
            '// statment should be suficient for either development or run mode
            sConnectionString = Environment.GetCommandLineArgs.GetValue(1)
            '// connect to a running SBO Application
            Try ' If there's no active application the connection will fail
                SboGuiApi.Connect(sConnectionString)
            Catch ' Connection failed
                System.Windows.Forms.MessageBox.Show("No SAP Business One Application was found")
                End
            End Try
            '// get an initialized application object
            SBO_Application = SboGuiApi.GetApplication()
            'SBO_Application.MessageBox("Hello World")
        End Sub
        Private Sub SBO_Application_AppEvent(ByVal EventType As SAPbouiCOM.BoAppEventTypes) Handles SBO_Application.AppEvent
            Select Case EventType
                Case SAPbouiCOM.BoAppEventTypes.aet_ShutDown
                    SBO_Application.MessageBox("A Shut Down Event has been caught" & _
                        Environment.NewLine() & "Terminating 'Add Menu Item' Add On...")
                    '// terminating the Add On
                    System.Windows.Forms.Application.Exit()
            End Select
        End Sub
        Private Sub CreateFormWithMatrix()
            '// Don't Forget:
            '// it is much more efficient to load a form from xml.
            '// use code only to create your form.
            '// once you have created it save it as XML.
            '// see "WorkingWithXML" sample project
            '// we will use the following object to add items to our form
            Dim oItem As SAPbouiCOM.Item
            '// we will use the following objects to set
            '// the specific values of every item
            '// we add.
            '// this is the best way to do so
            Dim oButton As SAPbouiCOM.Button
            Dim oStaticText As SAPbouiCOM.StaticText
            Dim oEditText As SAPbouiCOM.EditText
            '// The following object is needed to create our form
            Dim creationPackage
            creationPackage = SBO_Application.CreateObject(SAPbouiCOM.BoCreatableObjectType.cot_FormCreationParams)
            creationPackage.UniqueID = "UidFrmMatrix14"
            creationPackage.FormType = "TypeFrmMatrix14"
            '// Add our form to the SBO application
            oForm = SBO_Application.Forms.AddEx(creationPackage)
            '// Set the form properties
            oForm.Title = "Quality Check"
            oForm.Left = 336
            oForm.ClientWidth = 620
            oForm.Top = 44
            oForm.ClientHeight = 200
            '// Adding Items to the form
            '// and setting their properties
            '// Adding an Ok button
            '// We get automatic event handling for
            '// the Ok and Cancel Buttons by setting
            '// their UIDs to 1 and 2 respectively
            oItem = oForm.Items.Add("1", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 5
            oItem.Width = 65
            oItem.Top = 170
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Ok"
            '// Adding a Cancel button
            oItem = oForm.Items.Add("2", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            oItem.Left = 75
            oItem.Width = 65
            oItem.Top = 170
            oItem.Height = 19
            oButton = oItem.Specific
            oButton.Caption = "Cancel"
            '// Adding a Text Edit item
            'oItem = oForm.Items.Add("txtPhone", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            ' oItem.Left = 265
            'oItem.Width = 163
            'oItem.Top = 172
            'oItem.Height = 14
            '// Adding an Add Phone prefix column button
            ' oItem = oForm.Items.Add("BtnPhone", SAPbouiCOM.BoFormItemTypes.it_BUTTON)
            ' oItem.Left = 160
            ' oItem.Width = 100
            ' oItem.Top = 170
            ' oItem.Height = 19
            ' oButton = oItem.Specific
            ' oButton.Caption = "Add Phone prefix"
            '// Add the matrix to the form
            AddMatrixToForm()
        End Sub
        Private Sub AddMatrixToForm()
            '// we will use the following object to add items to our form
            Dim oItem As SAPbouiCOM.Item
            '// we will use the following object to set a linked button
            Dim oLink As SAPbouiCOM.LinkedButton
            '// Adding a Matrix item
            oItem = oForm.Items.Add("Matrix1", SAPbouiCOM.BoFormItemTypes.it_MATRIX)
            oItem.Left = 5
            oItem.Width = 500
            oItem.Top = 5
            oItem.Height = 150
            oMatrix = oItem.Specific
            oColumns = oMatrix.Columns
            '// Adding Culomn items to the matrix
            oColumn = oColumns.Add("#", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "#"
            oColumn.Width = 30
            oColumn.Editable = False
            '// Add a column for Item Code
            oColumn = oColumns.Add("DSItemCode", SAPbouiCOM.BoFormItemTypes.it_LINKED_BUTTON)
            oColumn.TitleObject.Caption = "Item Code"
            oColumn.Width = 40
            oColumn.Editable = True
            '// Link the column to the ITEM master data system form
            oLink = oColumn.ExtendedObject
            oLink.LinkedObject = SAPbouiCOM.BoLinkedObject.lf_Items
            oColumn = oColumns.Add("DSItemName", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Item Name"
            oColumn.Width = 80
            oColumn.Editable = True
            '// Add a column for BP Card Phone
            oColumn = oColumns.Add("DSWhs", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Ware House"
            oColumn.Width = 40
            oColumn.Editable = True
            '// Add a column for BP Card Phone
            oColumn = oColumns.Add("DSQuantity", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Quantity"
            oColumn.Width = 40
            oColumn.Editable = True
            '// Add a column for Combo Box
            oColumn = oColumns.Add("DSQuality", SAPbouiCOM.BoFormItemTypes.it_CHECK_BOX)
            oColumn.TitleObject.Caption = "Quality"
            ' oColumn.ValidValues.Add("OK", "")
            'oColumn.ValidValues.Add("NOT OK", "")
            oColumn.Width = 40
            oColumn.Editable = True
            oColumn = oColumns.Add("DSReport", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            oColumn.TitleObject.Caption = "Remarks"
            ' oColumn.ValidValues.Add("OK", "")
            'oColumn.ValidValues.Add("NOT OK", "")
            oColumn.Width = 40
            oColumn.Editable = True
            '// Add a column for BP Card Phone
            ' oColumn = oColumns.Add("DSPhoneInt", SAPbouiCOM.BoFormItemTypes.it_EDIT)
            ' oColumn.TitleObject.Caption = "Int. Phone"
            'oColumn.Width = 40
            'oColumn.Editable = True
        End Sub
        Public Sub AddDataSourceToForm()
            '// every item must be binded to a Data Source
            '// prior of binding the data we must add Data sources to the form
            '// Add user data sources to the "International Phone" column in the matrix
            ' oUserDataSource = oForm.DataSources.UserDataSources.Add("IntPhone", SAPbouiCOM.BoDataType.dt_SHORT_TEXT, 20)
            '// Add DB data sources for the DB bound columns in the matrix
            oDBDataSource = oForm.DataSources.DBDataSources.Add("OITW")
        End Sub
        Public Sub BindDataToForm()
            '// getting the matrix column by the UID
            oColumn = oColumns.Item("DSItemCode")
            'oColumn.DataBind.SetBound(True, "", "DSCardCode")
            oColumn.DataBind.SetBound(True, "OITW", "ItemCode")
            'oColumn = oColumns.Item("DSItemName")
            'oColumn.DataBind.SetBound(True, "OITW", "ItemName")
            oColumn = oColumns.Item("DSWhs")
            oColumn.DataBind.SetBound(True, "OITW", "WhsCode")
            oColumn = oColumns.Item("DSQuantity")
            oColumn.DataBind.SetBound(True, "OITW", "U_QCStock")
            '// to Data Bind an item with a user Data source
            '// the table name value should be an empty string
            ' oColumn = oColumns.Item("DSPhoneInt")
            'oColumn.DataBind.SetBound(True, "", "IntPhone")
        End Sub
        Public Sub GetDataFromDataSource()
            '// Ready Matrix to populate data
            oMatrix.Clear()
            oMatrix.AutoResizeColumns()
            '// Querying the DB Data source
            oDBDataSource.Query()
            '// setting the user data source data
            'oUserDataSource.Value = "Phone with prefix"
            oMatrix.LoadFromDataSource()
        End Sub
        Private Sub SBO_Application_ItemEvent(ByVal FormUID As String, ByRef pVal As SAPbouiCOM.ItemEvent, ByRef BubbleEvent As Boolean) Handles SBO_Application.ItemEvent
            If (pVal.FormUid = "UidFrmMatrix") Then
                If ((pVal.itemUID = "BtnPhone") And _
                    (pVal.EventType = SAPbouiCOM.BoEventTypes.et_ITEM_PRESSED) And _
                    (pVal.Before_Action = False)) Then
                    AddPrefix()
                End If
                If ((pVal.EventType = SAPbouiCOM.BoEventTypes.et_FORM_UNLOAD) And _
                    (pVal.Before_Action = False)) Then
                    SBO_Application.MessageBox("Form Unloaded, Addon will terminate")
                    System.Windows.Forms.Application.Exit()
                End If
            End If
        End Sub
        Public Sub AddPrefix()
            Dim i As Integer
            Dim PhoneExtCol As SAPbouiCOM.Column
            Dim newPhone As String
            Dim oItem As SAPbouiCOM.Item
            Dim oEditTxt As SAPbouiCOM.EditText
            '// Get the prefix edit text item
            oItem = oForm.Items.Item("txtPhone")
            oEditTxt = oItem.Specific
            '// Flush user input into datasources
            oMatrix.FlushToDataSource()
            '// Get the DBdatasource we base the matrix on
            oDBDataSource = oForm.DataSources.DBDataSources.Item("OCRD")
            '// Iterate all the records and add a prefix to the phone
            For i = 0 To oDBDataSource.Size - 1
                newPhone = oDBDataSource.GetValue("phone1", i)
                newPhone = newPhone.Trim(" ")
                oDBDataSource.SetValue("phone1", i, oEditTxt.String + newPhone)
            Next
            '// Load data back to
            oMatrix.LoadFromDataSource()
        End Sub
    End Class

    Hi Shahid,
    I am not sure what your question is. The code you pasted looks like the MatrixAndDataSources example that comes with the SDK. What are you trying to do?
    Thanks,
    Adele

Maybe you are looking for