Tuesday, September 1, 2015

OnBase Unity C# Visual Studio: Create an ODBC connection

Core to creating an OnBase Visual Studio application is to connecting to and querying the onbase database instance for various activities outside of what the API exposes. Here are the steps to do this:


  1. Install the ODBC driver for your OnBase database
  2. Configure a Data Source Name entry
  3. Import the ODBC class for reference
  4. Write code to establish a connection object
  5. Open a connection
  6. Run through the results
  7. Close a connection
Here's some of the code to help do this:

... main code


                OdbcConnection conn = openODBCConnection();
                OdbcDataReader dr = null;
                OdbcCommand cmd = null;

                cmd = new OdbcCommand("select a.keyvaluechar from keyitem141 a  " +
                "where a.itemnum = '" + itemnumtemp + "'", conn);

                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    TempValue = dr[0].ToString().Trim();
                }

                conn.Close();
                cmd.Dispose();
                dr.Dispose();

... connection method
                 conn.ConnectionString = "DSN=OnBaseDSN;UID=hsi;PWD=password"

OnBase Unity C# Visual Studio: update a keyword value

Ok, from previous posts, we know how to do the following: create an app connection, get a doc ID, create a doc object. Once we have those, we can modify a keyword's value. Note: this is not the same as adding a keyword, which is what you want to do if one doesn't exist. Hope this helps...

                        // check whether document was locked
                        if (documentLock.Status == DocumentLockStatus.LockObtained)
                        {

                            KeywordModifier keyModifier = doc.CreateKeywordModifier();

                            KeywordType searchKeywordType = g_Application.Core.KeywordTypes.Find("Your Date");

                            // loop thru keyword records
                            foreach (KeywordRecord keyRecord in doc.KeywordRecords.FindAll(searchKeywordType))
                            {
                                // loop though keywords
                                foreach (Keyword keywordOld in keyRecord.Keywords.FindAll(searchKeywordType))
                                {

                                    // Find Keyword Type 
                                    KeywordType keywordType0 = core.KeywordTypes.Find("Your Date");

                                    // Create Keyword Object
                                    DateTime newdate1 = DateTime.ParseExact(strDate,"MM/dd/yyyy", null);
                                    string strDatex = newdate1.ToString("MM-dd-yyyy");
                                    DateTime NewDateValue = Convert.ToDateTime(strDatex);

                                    Keyword keywordNew = keywordType0.CreateKeyword(NewDateValue);
                        
                                    //update keyword
                                    keyModifier.UpdateKeyword(keywordOldkeywordNew);

                                  
                                }
                            }

                            //Apply changes
                            keyModifier.ApplyChanges();

                            //release doc lock
                            documentLock.Release();
                           }

OnBase Unity C# Visual Studio: attach a lifecycle

As I've shown in a previous post, you'll need to create an application connection, find the doc handle of the doc you want to attache a lifecycle to, and create the doc object. Once you'll done that, you'll need to create the workflow and lifecycle objects. Then, add the doc to the lifeycle;


                    Workflow workflow = g_Application.Workflow;
                    LifeCycle lifeCycle = g_Application.Workflow.LifeCycles.Find(<config number of the                       lifecycle);
                    workflow.AddDocumentToLifeCycle(doc, lifeCycle);

OnBase Unity C# Visual Studio code to create a document object

In many cases you'll need a document object to perform actions on it. Here are the basics:

Create an application session
        AuthenticationProperties authProps = null;
              authProps = Hyland.Unity.Application.CreateDomainAuthenticationProperties(TestAppServer, TestDatabase);
                authProps.LicenseType = LicenseType.Default;
                  g_Application = Hyland.Unity.Application.Connect(authProps);

          Run your query to find the document's handle. Creating a SQL connection and running it is in a separate post.

                  long docID = Convert.ToInt64(dr[0].ToString().Trim());

                  Document doc = g_Application.Core.GetDocumentByID(docID);

          Once you have a document object you can update keys, attach lifecycles, etc.

          Thursday, March 26, 2015

          OnBase Unity Script to Import Content

          This script is not complete, but should show the essential components that assure the ability to import content into OnBase. Typically when you are importing via a script, you are reading an index file line by line and using these values along with a pointer to a file in a folder to import. Enjoy!

          To import you'll need a value for the file type, the OnBase document type, some descriptive keyword types, and a file list.

          get an application session:
          getOnBaseAppSession(); //see method below

          Setup the file type for import:

          if (filetype == "TIF")
          {
          filetype = "Image File Format";
          }

          Loop through the index file, reading each line and splitting the values:

          StreamReader file = new StreamReader(path);
          while ((line = file.ReadLine()) != null)
          {
          ...

          string[] indexValues = line.Split(delimiterChar);
          ...

          importDoc(doctypetemp, filetypetemp, fileList, Sourcekeywords);

          }

          The importDoc method will do all of the OnBase importing:

          private void importDoc(string doctypetemp, string filetypetemp, List<string> fileList, string Sourcekeywords)
          {
          try...
          //set the storage
          Storage storage = g_Application.Core.Storage;

          //set the doc type
          DocumentType documentType = g_Application.Core.DocumentTypes.Find(doctypetemp);

          //Set file type 
          FileType fileType = g_Application.Core.FileTypes.Find(filetypetemp);

          // create storage props from the storage object
          StoreNewDocumentProperties storeDocumentProperties = storage.CreateStoreNewDocumentProperties(documentType, fileType);

          // Add keyword record to storage properties
          storeDocumentProperties.AddKeyword("Account#", Accounttemp);

          // storeDocumentProperties.ExpandKeysets = true;

          // Assign document date 
          storeDocumentProperties.DocumentDate = DateTime.Now;

          // Allow document to be auto named 
          //storeDocumentProperties.AutoName = true;

          // Add comment 
          storeDocumentProperties.Comment = "Custom Import";

          // Do not add document to workflow 
          storeDocumentProperties.Options = StoreDocumentOptions.SkipWorkflow;

          //import!
          Document newDocument = g_Application.Core.Storage.StoreNewDocument(fileList, storeDocumentProperties);

          }

          private void getOnBaseAppSession()
          {
          try
          {
          //connect to OnBase 
          AuthenticationProperties authProps;
          authProps = Hyland.Unity.Application.CreateDomainAuthenticationProperties(<TestAppServer>, <TestDatabase>);
          authProps.LicenseType = LicenseType.Default;
          g_Application = Hyland.Unity.Application.Connect(authProps);
          }

          Saturday, March 14, 2015

          OnBase Unity Script to Create a User

          The following C# Unity script snippet could be used to create OnBase User accounts before the users actually log in. This is useful if you want to provision the User account, group memberships, and load balancing without burdening the User to log in first.

          ctx = new PrincipalContext(ContextType.Domain, "<your company's domain>");
          UserAdministration userAdmin = g_Application.Core.UserAdministration;

          //loop through all users in a list <listADUsers>
          //check if user is in the OnBase core group
          User OBuserTemp = g_Application.Core.GetUser(AddOBUser);
          UserGroupList obusergrps = OBuserTemp.GetUserGroups();
          Boolean onbasegrptest = false;

          foreach (string ADUser in listADUsers)
          {
          AddOBUser = ADUser.ToString().ToUpper();

          UserPrincipal user = new UserPrincipal(ctx);
          PrincipalSearcher srch = null;
          srch = new PrincipalSearcher(user);
          user.SamAccountName = AddOBUser;
          srch = new PrincipalSearcher();
          srch.QueryFilter = user;
          PrincipalSearchResult<Principal> result = srch.FindAll();
          Principal Psrch = result.ToList()[0];
          DirectoryEntry Dresult = (DirectoryEntry)Psrch.GetUnderlyingObject();

          String EmailAddress = Dresult.Properties["mail"].Value.ToString();
          String DisplayName = Dresult.Properties["displayName"].Value.ToString();

          //create user and add to selected group
          NewUserProperties userProperties = userAdmin.CreateNewUserProperties(AddOBUser, "<default password>");
          userProperties.EmailAddress = EmailAddress;
          userProperties.RealName = DisplayName;
          User OBuser = userAdmin.CreateUser(userProperties);
          userAdmin.AddUserToGroups(OBuser, grpList);
          user.Dispose();
          srch.Dispose();
          Psrch.Dispose();
          result.Dispose();
          Dresult.Dispose();
          }

          Saturday, March 7, 2015

          OnBase Unity Script to Add Active Directory Group Members to OnBase Group

          The following search Active Directory for a specific group and members and adds these members to the corresponding OnBase Group.

          namespace AddADGroupMembersToOnBase
          {
              using System;
              using System.Text;
              using Hyland.Unity;
              using Hyland.Unity.Workflow;
              using System.Data.Odbc;
              using System.Collections;
              using System.DirectoryServices;
              using System.DirectoryServices.AccountManagement;
              using System.Collections.Generic;

              /// <summary>
              /// This adds AD members from AD group to OnBase group.
              /// </summary>
              public class AddADGroupMembersToOnBase : Hyland.Unity.IWorkflowScript
              {
                  private Hyland.Unity.Document _doc;
                  private Hyland.Unity.Application _app;
                  private Hyland.Unity.WorkflowEventArgs _args;
                  private PrincipalContext ctx;

                  #region IWorkflowScript
                  /// <summary>
                  /// Implementation of <see cref="IWorkflowScript.OnWorkflowScriptExecute" />.
                  /// <seealso cref="IWorkflowScript" />
                  /// </summary>
                  /// <param name="app"></param>
                  /// <param name="args"></param>
                  public void OnWorkflowScriptExecute(Hyland.Unity.Application app, Hyland.Unity.WorkflowEventArgs args)
                  {
          _app = app;
          _doc = args.Document;
          _args = args;
               
                     try{
                         

          ctx = new PrincipalContext(ContextType.Domain, "<your company domain>");
          GroupPrincipal grp = null;
          string gName = "<the AD group name to search>";
                          grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, gName);
          ArrayList ADUserList = new ArrayList();

                          int numofusers = 0;

          //find all AD users
                              foreach (Principal p in grp.GetMembers(true))
                              {
                                  DirectoryEntry Dresult = (DirectoryEntry)p.GetUnderlyingObject();
                                  String Attr1 = Dresult.Properties["userAccountControl"].Value.ToString();
                                  if (Attr1 == "512")
                                      ADUserList.Add(p.SamAccountName.ToUpper());
                                  Dresult.Dispose();

                                  numofusers++;
                              }

                              //list AP Approvers from OnBase group
                              UserGroup usrGroup;
                              UserList users;
                              ArrayList OBUserList = new ArrayList();
                              usrGroup = _app.Core.UserGroups.Find(gName);
                              users = _app.Core.UserAdministration.GetUsers(usrGroup);

                              foreach (User user in users)
                              {
                                  OBUserList.Add(user.Name.ToString().ToUpper());
                              }

                              grp.Dispose();
                              ctx.Dispose();

                              foreach (string ADUser in ADUserList)
                              {
                                 if (!OBUserList.Contains(ADUser))
                                 {
                                    addAPMember(ADUser, gName);
                                 }
                              }
          }
          catch (Exception ex)
          {
          _app.Diagnostics.Write(ex);
          _args.ScriptResult=false;
          }
                  }


          private void addAPMember(string APMember, string gName)
                  {
                      try
                      {
                          if (_app.Core.GetUser(APMember) != null)
                          {
                              UserAdministration userAdmin = _app.Core.UserAdministration;
                              List<UserGroup> grpList = new List<UserGroup>();
                              UserGroup grpToAdd;

                              //add the onbase core group
                              grpToAdd = _app.Core.UserGroups.Find(gName);
                              grpList.Add(grpToAdd);
                              
                              //add OB user to selected group
                              userAdmin.AddUserToGroups(_app.Core.GetUser(APMember.ToUpper()), grpList);
          }

                      }catch (Exception ex)
          {
          _app.Diagnostics.Write(ex);
          _args.ScriptResult=false;
          }
                  }
                  #endregion
              }
          }

          OnBase VB Script to send an email

          The following is a sample OnBase VB Script to use to send an email.

          Sub Main35()

          Const CONNECTSTRING = "DSN=OnBase;UID=<ownerID>;PWD=<ownerPSWD>"

          ' Root level OnBase Automation object
            Dim oApp
            Set oApp = CreateObject("OnBase.Application")


             oApp.ExecutionStatus = 1

          'set up parameters for CDO
          strSMTPFrom = "support@yourcompany.com"
          strSMTPTo = "level1support@yourcompany.com"
          strSMTPRelay = "smtp.yourcompany.com"
          strTextBody = "There are too many errors on the server"
          strSubject = "ALERT: check OnBase processor server"
          strAttachment = ""

          'Create and set up CDO object
          Set oMessage = CreateObject("CDO.Message")
          oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 
          oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPRelay
          oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 
          oMessage.Configuration.Fields.Update

          'send message
          oMessage.Subject = strSubject
          oMessage.From = strSMTPFrom
          oMessage.To = strSMTPTo
          oMessage.TextBody = strTextBody
          'oMessage.AddAttachment strAttachment
          oMessage.Send

          Set oMessage = Nothing


          End Sub 'Main35()

          Sunday, March 1, 2015

          OnBase Scan Queue Tools

          If your company's ECM operation is scanning, indexing, and committing hundreds of scan batch a day, you may want to have extra insight into the daily processing metrics. You may also need to drill down into the scanning and logging to investigate issues.

          The Scan Queue Tool allows you to search Scan Queues by the state of each scan by Scan Batches by Date Range. If the scan queue is configured to send out HL7 messages, you can use it to find a text string with the message. For HL7 translations, you can find information base on the mapping values.


          Please see the tool's screen shot below.




          If you are interested in using this tool for a free trial, or have suggestions on other functionality, please contact me at webber_john@charter.net. 

          Tuesday, February 24, 2015

          OnBase Unity Workflow script to create a note

          Below is a method that creates an OnBase note which is attached to the doc being processed.
          It accepts a string which will the text that is meant to show in the note.

          private void createNote(string noteText)
          {
              //Create a Note with the error message
              NoteType noteType = _app.Core.NoteTypes.Find("<note type>");
              NoteModifier noteMod = _args.Document.CreateNoteModifier();

              //Properties of the Note
              NoteProperties noteProps = noteMod.CreateNoteProperties();
              noteProps.Text = "Validation Issue" + Environment.NewLine + "Error               Message: "+ noteText;
              
              //Create the New Note
              Note newNote = noteType.CreateNote(noteProps);
              noteMod.AddNote(newNote);
              noteMod.ApplyChanges();

              //_app.Diagnostics.Write("Note Added");
          }

          OnBase Unity Workflow script to export a doc to the directory


          Below is an OnBase unity workflow script to export a doc to the directory. Be sure to add the References that you are using.


          namespace _SaveToFile
          {
              using System.IO;
              using System.Text;
          using System;
              using Hyland.Unity;
              using Hyland.Unity.Workflow;
              
              
              /// <summary>
              /// script for doing something in a workflow
              /// </summary>
              public class _SaveToFile : Hyland.Unity.IWorkflowScript
              {
                  
                  #region IWorkflowScript
                  //<summary>
                 //  Implementation of the export to file share of the 3M integration
                 // </summary>
                  /// <param name="app"></param>
                  /// <param name="args"></param>

                  public void OnWorkflowScriptExecute(Hyland.Unity.Application app, Hyland.Unity.WorkflowEventArgs args)

                  {
          try
                      {
          Document wfdoc = args.Document;
                      //Application _app = app;
          string url = "<application service URL";
          string username = "<manager account";
          string password = "<manager password";
          string datasource = "DSN of OnBase database";

          //Create a new Unity Integration Application Object
          OnBaseAuthenticationProperties props = Application.CreateOnBaseAuthenticationProperties(url, username, password, datasource);
          props.LicenseType = LicenseType.Default;
          Application _app = Application.Connect(props);


          string dirPath = @"\\FileServer\Share\" + args.Document.ID + ".";

                          // create Redition

                          Rendition wfrend = wfdoc.DefaultRenditionOfLatestRevision;

                          //PageData

                          using (PageData wfPageData = _app.Core.Retrieval.Image.GetDocument(wfrend))
                          {
                              //Utility to write data page stream
                              Utility.WriteStreamToFile(wfPageData.Stream, dirPath + wfPageData.Extension);
                          }

          args.ScriptResult = true;

          _app.Disconnect();

                      }
                      catch (UnityAPIException Uex)
                      {
                          app.Diagnostics.Write("Unity API: "+Uex.Message);
          args.ScriptResult = false;
                      }
                      catch (Exception ex)
                      {
                          app.Diagnostics.Write("Exception: "+ex.Message);
                      args.ScriptResult = false;
          }

                  }

                  #endregion
              }
          }

          OnBase Unity Workflow Script ODBC connection method

          Here is a standard OnBase workflow ODBC connection method.

          • You have to have the DSN setup on the machine that is running the workflow process/timer.
          • You need to add a Reference in the Unity IDE
          namespace <project name>
          {


              using Hyland.Unity;
              using Hyland.Unity.Workflow;
              using System.Data.Odbc;
          ...

              public class <project name> : Hyland.Unity.IWorkflowScript
              {
          ...
                  public void OnWorkflowScriptExecute(Hyland.Unity.Application app, Hyland.Unity.WorkflowEventArgs args)
                  {
                   
          OdbcConnection conn = openODBCConnection();
          ...
                   }
          ...
          private OdbcConnection openODBCConnection()
                  {
                      var conn = new OdbcConnection();
                      conn.ConnectionString = "DSN=OnBaseDSN;UID=<instance user>;PWD=<password>";
                      conn.Open();
                      return (conn);
                  }

          Saturday, January 31, 2015

          OnBase Purge Tool


          Refreshing an OnBase repository from production to test can be challenging especially with a large amount of content that needs to be trimmed. The application below allows a System Admin to locate documents by date and doc type, and to delete or purge them. 



          This application is built in .Net and is easy to configure. As you can see, there is a date range and doc type selections. The search can show a result count and a list of results. Once you are satisfied with the results, you can choose to delete the document, or purge it. Deleting is much faster and requires that you purge the files through Document Maintenance.

          If you are interesting in learning more about this application please email me at webber_john@charter.net.