Step by Step Guide for Developing Your First by amberp

VIEWS: 47 PAGES: 14

									Step by Step Guide for Developing Your First .NET SAS
Project

Table of Contents

Step by Step Guide for Developing Your First .NET SAS Project .................................... 1
  Written By....................................................................................................................... 1
  Purpose............................................................................................................................ 1
  Prerequisites .................................................................................................................... 1
  Basic Form Layout .......................................................................................................... 2
  Adding in the references to SAS ..................................................................................... 3
  Wire it all up ................................................................................................................... 4
  Explaining the code......................................................................................................... 7
  Visual Basic Version....................................................................................................... 8


Written By

Alan Churchill
Savian, LLC
http://www.savian.net


Purpose

.NET has become a very popular choice for developing GUIs for the Windows platform.
.NET also has tremendous capabilities in a lot of areas including XML processing, batch,
web services, support for mobile devices, etc. Combining it with the power of SAS
provides a powerful toolkit.

This is an introductory paper to help people absolutely new to .NET build a standalone
Windows application.


Prerequisites

Visual Studios 2005 (VS2005), any version.
Base SAS installed on the machine where you run the code
Chapter 1 – Submitting SAS Code
Basic Form Layout

  1. Open up Visual Studios 2005 (any edition)
  2. File  New  Project
  3. Select Visual C# (or whatever language you prefer)  Windows  Windows
     Application
  4. Give it an appropriate name and directory location. Click OK
  5. From the toolbox icon on the left hand side of the designer, drag out a button and
     a RichTextBox and place them on the form.

  You should see something like this:




                                                Properties


  6. Click on the button1 and in the properties box, change its Text to read “Submit”
     and its Name to submitCode
   7. Click on the RichTextBox and change its Name to sasLog
   8. Click on the Form1 and change its Text to “SAS Code Submit”

Your form should now look like this:




Adding in the references to SAS

References are compiled class libraries that expose the capabilities of a particular
product. There are references for every program installed on the machine. In order to get
at the SAS functionality, you need to include a reference for their product in your code.

   1. In the upper right-hand pane of VS2005 is the Solution Explorer. Right-click on
      References and choose Add Reference. Then be patient this can take awhile
      depending upon the workload and how many items you have on your machine.
   2. Click on the COM tab
   3. Find the one that says SASWorkspaceManager and select it. Click OK. You will
      notice that it adds several references to SAS.
Wire it all up

Now it is necessary to tell the button what to do when it is clicked. Clicking on a button,
or any action on a form, fires an event. The button click event will call SAS, submit some
code, and post the log back to the screen.

   1. In VS2005, click on the button. In the properties window, click on the lightening
      bolt symbol        at the top. This shows you all of the events available to the
      button. Don’t take any action here, this is merely to show the multitude of events
      available
   2. Double-click on the submit button on the form. This will automatically wire up
      the event for that button.

You should see this in the code editor:

       using    System;
       using    System.Collections.Generic;
       using    System.ComponentModel;
       using    System.Data;
       using    System.Drawing;
       using    System.Text;
       using    System.Windows.Forms;

       namespace WindowsApplication1
       {
           public partial class Form1 : Form
           {
               public Form1()
               {
                   InitializeComponent();
               }

                  private void submitCode_Click(object sender, EventArgs e)
                  {

                  }
            }
       }

       The using statements at the top merely keep you from coding a
       lot. Instead of typing in something like:

       System.Text.StringBuilder sb = new System.Text.StringBuilder();

       It is simplified to:

       StringBuilder sb = new StringBuilder();
     3. Add in a using statement for SAS and the WorkspaceManager:

        using SAS ;
        using SASWorkspaceManager;

VB.NET version (by default VB.NET does not have any Import statements
at the top of the code. Just place these statements as the very first
statements in the code):

Imports SAS
Imports SASWorkspaceManager


     4. Replace your code with the following:

private void submitCode_Click(object sender, EventArgs e)
{
  StringBuilder sb = new StringBuilder("/* Code sample by Savian */");
  sb.Append("data test;");
  sb.Append("set sashelp.class;");
  sb.Append("run;");

    string log = SubmitSasCode(sb.ToString());
    sasLog.Text = log
}

 private string SubmitSasCode(string sasCode)
 {
   string errorMessage;
   WorkspaceManager wsm = new WorkspaceManager();
   Workspace ws = (Workspace)wsm.Workspaces.CreateWorkspaceByServer("",
SASWorkspaceManager.Visibility.VisibilityProcess, null, "", "", out
errorMessage);
   ILanguageService ls = ws.LanguageService;
   ls.LineSeparator = "\r\n";
   ls.Submit(sasCode);
   string log = ls.FlushLog(1000).Replace("\f", "");
   return log;
 }
We’ll explain the code in a second. For now, let’s build and see what
happens.

  5. Press F5 to build and run the application.
  6. When the application pops up, press the Submit button.

You should see this:
Explaining the code

The code basically calls SAS, gets the resulting log back, and posts it to the
RichTextBox. Let’s go through the details:

When the Submit button is pressed, the following code creates the SAS program to
execute. StringBuilder is a powerful tool that lets a developer append strings together.
There are other ways to handle this but StringBuilder is simple and effective:

  StringBuilder sb = new StringBuilder("/* Code sample by Savian */");
  sb.Append("data test;");
  sb.Append("set sashelp.class;");
  sb.Append("run;");

The code is then sent to another method:

  string log = SubmitSasCode(sb.ToString());

The SubmitSasCode method then creates a workspace using the SAS local provider:

   string errorMessage;
   WorkspaceManager wsm = new WorkspaceManager();
   Workspace ws = (Workspace)wsm.Workspaces.CreateWorkspaceByServer("",
SASWorkspaceManager.Visibility.VisibilityProcess, null, "", "", out
errorMessage);

A LanguageService is created:

   ILanguageService ls = ws.LanguageService;

This line merely makes the code more readable and is optional:

   ls.LineSeparator = "\r\n";

The code is submitted:

   ls.Submit(sasCode);

The resulting log is returned and is made more readable:

   string log = ls.FlushLog(1000).Replace("\f", "");

The log is returned to the calling method (submitCode_Click)

   return log;

The returned log is then bound to the RichTextBox:

  sasLog.Text = log
Visual Basic Version

Here is the VB.Net code for the sample application in case someone needs it:

Private Sub submitCode_Click(ByVal sender As Object, ByVal e As
EventArgs)
 Dim sb As StringBuilder = New StringBuilder("/* Code sample by Savian
*/")
 sb.Append("data test;")
 sb.Append("set sashelp.class;")
 sb.Append("run;")
 Dim log As String = SubmitSasCode(sb.ToString)
 sasLog.Text = log
End Sub

Private Function SubmitSasCode(ByVal sasCode As String) As String
 Dim errorMessage As New String
 Dim wsm As WorkspaceManager = New WorkspaceManager
 Dim ws As Workspace = CType(wsm.Workspaces.CreateWorkspaceByServer("",
SASWorkspaceManager.Visibility.VisibilityProcess, Nothing, "", "",
errorMessage), Workspace)
 Dim ls As ILanguageService = ws.LanguageService
 ls.LineSeparator = "" & Microsoft.VisualBasic.Chr(13) & "" &
Microsoft.VisualBasic.Chr(10) & ""
 ls.Submit(sasCode)
 Dim log As String = ls.FlushLog(1000).Replace("" &
Microsoft.VisualBasic.Chr(12) & "", "")
 Return log
End Function
Chapter 2 – Displaying the SAS Data
We will build upon the application we started in Chapter 1.

   1. First, create a directory on your machine called “c:\temp”.
   2. Copy the shoes dataset into the c:\temp from the following directory:

       ..\Program Files\SAS\SAS 9.1\core\sashelp\shoes.sas7bdat

   3. Move some items around so there is more space. Give yourself plenty of room
      because this application will be more functional than the last.




   4. Next, drag out a TabControl (found under Containers in the Toolbox) and expand
      it a little. Shrink your RichTextBox so it is smaller than the TabControl. This is
      merely to help with visualizing.
5. Move the submit button toward the top of the WinForm
6. Drag out a Panel control (found under containers) and set its Dock property to the
   bottom rectangle.




7. Drag the Submit button into the Panel control. Resize the panel control so it is a
   bit smaller.




8. Drag your existing RichTextBox into the TabControl’s tabPage1 and drop it.
9. Select the TabControl. BE CAREFUL here and don’t select just a tab. Click near
   the top of the tab’s and make sure the whole control is selected. Optionally, to
   make sure there are no mistakes, select the TabControl1 on the dropdown at the
   top of the Properties window.
10. Once the TabControl is selected, go into it’s properties and set Dock to be the
    center rectangle.
11. Click on the RichTextBox in the tabPage1 and .set it’s Dock property to the
    center rectangle.
12. Relabel the tabPage1 and tabPage2 to “Log” and “Data” respectfully using the
    Properties. It is easiest to select these using the dropdown above the Property
    control.
13. Switch to the new Data tab (again, use the dropdown).
14. Next, drag out a DataGridView from the ToolBox. The DataGridView, by
    default, is under the Data section in the Toolbox. Set its dock property to fill
    similar to the other 2 items.
      15. Switch to the Data tab using the dropdown above properties and switch over to
          the event view by selecting the lightening bolt icon at the top of properties.




      16. Double-click the blank spot to the right of the Enter property. This should
          automatically wire up an event that will fire whenever someone clicks on that tab.
      17. Put the following code in between the brackets of the tab enter event:

try
{
    System.Data.DataSet sasDs = new System.Data.DataSet();
    OleDbConnection sas = new
OleDbConnection(@"Provider=sas.LocalProvider; Data Source=c:\temp");
    sas.Open();
    OleDbCommand sasCommand = sas.CreateCommand();
    sasCommand.CommandType = CommandType.TableDirect;
    sasCommand.CommandText = "shoes";
    OleDbDataAdapter da = new OleDbDataAdapter(sasCommand);
    da.Fill(sasDs, "SasData");
    sas.Close();
    dataGridView1.DataSource = sasDs.Tables["SasData"];
}
catch (Exception ex)
{
    MessageBox.Show("Unable to load SAS dataset. Error seen was: " +
ex.ToString());
}

  18. Go to the top of the program and add in the following to your using statements:

using System.Data.OleDb;

VB.NET version (just place this Import statement as the first statement
in the program):

Imports System.Data.OleDb

  19. Press F5 and build. You should see the following when you enter the Data tab:
Visual Basic Version

Here is the VB.Net code for the tab event:

Private Sub tabPage2_Enter(ByVal sender As Object, ByVal e As
EventArgs)
 Try
   Dim sasDs As System.Data.DataSet = New System.Data.DataSet
   Dim sas As OleDbConnection = New
OleDbConnection("Provider=sas.LocalProvider; Data Source=c:\temp")
   sas.Open
   Dim sasCommand As OleDbCommand = sas.CreateCommand
   sasCommand.CommandType = CommandType.TableDirect
   sasCommand.CommandText = "shoes"
   Dim da As OleDbDataAdapter = New OleDbDataAdapter(sasCommand)
   da.Fill(sasDs, "SasData")
   sas.Close
   dataGridView1.DataSource = sasDs.Tables("SasData")
 Catch ex As Exception
   MessageBox.Show("Unable to load SAS dataset. Error seen was: " +
ex.ToString)
 End Try
End Sub

								
To top