2023.1:Grooper Scripting - CSS Utilities

From Grooper Wiki
Revision as of 09:31, 14 June 2024 by Randallkinard (talk | contribs) (// via Wikitext Extension for VSCode)

This article is about an older version of Grooper.

Information may be out of date and UI elements may have changed.

20252023.1

Gain familiarity with the Grooper object model by scripting real world examples and see how commonly used namespaces and their members are leveraged.

You may download the ZIP below and upload it into your own Grooper environment (version 2023.1). It contains a folder to be imported into the "Projects" folder in the node tree. There are two Projects in this folder: an "incomplete" version for use in following along with the walkthrough of this article, and a "complete" version you can use if you want to quickly test the end result. The complete version has a compiled solution with the appropriate .dll and .xml files attached to the Object Library. If you are going to follow along with the walkthrough, delete the "complete" version. If you want to test the results of the completed Object Library you will need to recycle the "GrooperAppPool" in IIS after import for the object command to be available.

About

IMPORTANT


Before we begin, it is highly recommend to review the contents of the Remote Scripting Setup article. In that article you will learn how to configure your environment so that you can debug on your local machine, and not need to be on the "Grooper Server" in order to do so. You will also see how the Grooper SDK is used to push the files of your local solution to the target object in Grooper so that it may be properly compiled within the application.


The purpose of this article is to walk you through an example of creating a simple object command that will set CSS styling in the Style Sheet property of "DataFieldContainer" objects (in code "DataFieldContainer" is the base class for Data Model, Data Section, Data Table objects). In so doing we will get exposure to the powerful Object Library object and its useful solution template generation functionality. This solution will then be used in Visual Studio 2019 to write the necessary code to accomplish the desired task. This process will reveal namespaces and their members that are commonly used to expand the capabilities of Grooper via scripting.

The script we create will be fairly simple, but it will give you a foundation upon which you could very easily expand to increase its capabilities and usefulness. In so doing you can make a powerful and easy to use tool you may end up using in your regular Grooper designing.

Getting Started

In this section we will get the necessary components created from Grooper to begin setup for our object command.

Import Project Files and Create Object Library

The system this work will be done on is configured appropriately to debug and push files to Grooper via the Grooper SDK. Given that, the following is true:


  1. Open a compatible web browser (in this case Google Chrome is being used)
  2. In the URL box type:
    localhost/Grooper/Design
  3. Select the "Projects" folder in the node tree
  4. Click the "Upload" button
  5. In the "ZIP File Import" dialog box click the "Choose File" button
  6. Browse to where you downloaded the Grooper ZIP file provided for this article, select the file, and click "Open"
  7. Back in the "ZIP File Import" dialog box click the "Upload" button to complete the upload


A "completed" version of the work we'll be doing is provided. It contains a compiled version of the solution attached to the Object Library we will create. If you wanted to use this you could simply refresh the "GrooperAppPool" in IIS and the object command would be available. However, for the purposes of this walkthrough it will be removed.

  1. Expand the folder of the imported object
  2. Right-click the 'completed' Project and select "Delete"
  3. In the "Delete" dialog box click the "Execute" button


  1. Expand the folder provided from the ZIP import
  2. Right-click the "Object Libraries" folder
  3. In the pop-out menu select Add > Object Library
  4. In the "Add" dialog box use the name:
    CssUtilities
  5. Click the "Execute" button


  1. With the Object Library added we can see it in the node tree

Create and Download C# Solution Files

Moving forward in this walkthrough we will be using C# for our .NET coding language as it by far the most popular choice. If enough requests for VB variations of the code come in we could update this walkthrough to have both.

  1. Select the newly created Object Library
  2. Click the "Scripting" tab.
  3. Click the "Create" button.
    • This button will be grayed out if you are not using "localhost" in your URL.
    • Refer to the Remote Scripting Setup article for information on setting up your environment if you are working from a computer that is not the computer where Grooper and the Grooper Web Client is installed.
  4. Choose C# from the drop-down menu.


  1. Executing the previous command will create several files from a template that will be the foundation of the solution we will edit in Visual Studio.
  2. You can select individual files and view their contents in the Document Viewer.
  3. You can download individual files or even make edits here, although this may not be the best interface for doing edits.
  4. The "ScriptingSession.cs" file has a couple of important comments.
    • Please note that compiling this script from Visual Studio will not add/update the ObjectLibrary DLL in Grooper. To add/update this DLL in Grooper and make the functionality in this project visible to Grooper, the Compile button must be used from the Script tab of the Grooper node in the Grooper Web Client.
    • You can debug with the GrooperSDK. Find the GrooperSDK in Visual Studio by going to Extensions..Manage Extensions..Online and searching for 'Grooper'. In addition to debugging, the GrooperSDK exposes commands such as Save, Save and Compile, and Get Latest.


The solution files that were just created are attached to the "CssUtilities" Object Library in the "Grooper Filestore". In order to properly edit this solution in Visual Studio we need to download a local copy of these files.

  1. Click the "Advanced" tab.
  2. Here you can see the files made are attached to this object in the "Grooper Filestore". We need to download local copies of these files to edit them.


  1. Click back on the "Scripting" tab.
  2. In the "Working Directory" dialog box, enter a path. The default path provided will suffice.
    C:\GrooperScripts
  3. Click the "OK" button.
  4. In the "Edit Script" dialog box a message confirms the files were saved and put in a sub-directory named after the selected object.
  5. Click the "OK" button.


While we're still in Grooper let's download an image that will be used as an "IconResource" in our solution.

  1. Expand the "Resources" folder and select "CssBadge.png".
  2. Right-click the image in the Document Viewer and select "Save image as".
  3. Choose a directory to save. The "Downloads" folder will suffice.
  4. Name the file:
    CssBadge.png
  5. Click the "Save" button.

Coding

Now for the fun part! In this section we will be writing the code for our "CssUtilities" namespace by defining the class and methods that will execute our object command.

NOTE: It's a good idea, when you can, to run Visual Studio with elevated permissions.

IconResource

We will start by adding our first piece of Grooper code: an attribute class called "IconResourceAttribute", but we'll call it simply as "IconResource".

Definition

The "IconResourceAttribute" is a class that allows you to decorate classes, methods, or properties with metadata specifying an icon resource. This icon can be used in various parts of an application to visually represent the annotated element.

Key Components

  • Namespace: Grooper
  • Assembly: Grooper.dll

Attribute Targets

  • Targets: Class, Method, Property

Enum: IconStyle

  • Normal: Standard icon without any overlay.
  • OverlayOnFolder: Icon overlaid on a folder image.
  • Add, Delete, Edit, Error, Go, Back, Lightning, Link, Save, GreenDot, RedDot, Search, Check, Folder, Archive, Wrench, Refresh: Various predefined styles for the icon.

Fields

  • IconResource: string - The name of the image resource.
  • Style: IconStyle - The style of the icon.
  • AssemblyName: string - The name of the assembly where the resource is located (optional).

Properties

  • ErrorImage: Bitmap - A static property that returns an error image if the specified icon resource is not found.

Methods

  • Constructors:
    • IconResourceAttribute(string IconResource, IconStyle Style = IconStyle.Normal)
    • IconResourceAttribute(string AssemblyName, string IconResource, IconStyle Style = IconStyle.Normal)
  • GetBitmap(Type tpe): Returns the bitmap image of the icon for the given type.
  • GetBitmap(Assembly Assembly): Returns the bitmap image from the specified assembly.
  • CreateIcon(Type tpe): Creates an icon handle from the bitmap.
  • GetIconKey(Type tpe): Generates a key for the icon based on type.
  • GetIconStream(Type tpe): Returns a stream of the icon image.
  • Static Methods:
    • GetBlankIcon(): Returns a blank icon.
    • GetBlankStream(): Returns a stream for a blank icon.
    • GetIconKey(Assembly Assm, string IconResource, IconStyle Style): Generates a key for the icon based on assembly and style.
    • GetBitmap(Assembly Assm, string IconResource, IconStyle Style): Retrieves the bitmap image from the assembly with specified style.

Caching

  • IconCache: A dictionary that caches icon images to avoid redundant loading.

Private Helpers

  • NamedAssembly: Returns the assembly based on the AssemblyName field.
  • GetAssembly(Type Type): Returns the assembly for the given type or the named assembly.
  • GetIconInternal(Assembly Assm, string IconResource, IconStyle Style): Retrieves the icon internally, considering the style.
  • GetOverlayIcon(Assembly Assm, string IconResource, string OverlayName): Retrieves an overlay icon.
  • GetIcon(Assembly Assm, string IconResource): Retrieves the icon from the assembly.
  • LoadResource(Assembly Assm, string IconResource): Loads the resource from the assembly.
  • GetResourceStream(Assembly Assm, string IconResource): Gets a stream for the resource.
  • OverlayIcon(Bitmap BgImage, Bitmap FgImage, int X, int Y): Overlays one icon on another.

Usage

This attribute can be used to decorate classes, methods, or properties, providing a way to associate them with a specific icon resource. The icons can be used in UI elements, documentation, or any other place where a visual representation of the code element is useful.

Example

<syntaxhighlight lang="csharp" line> [IconResource("MyIconResource", IconResourceAttribute.IconStyle.Normal)] public class MyClass {

   // Class implementation

} </syntaxhighlight>

This example specifies that MyClass should be represented by the MyIconResource icon in its normal style. The second argument, however, is optional, and "Normal" is the default, so it could be written simply as:

<syntaxhighlight lang="csharp" line> [IconResource("MyIconResource")] public class MyClass {

   // Class implementation

} </syntaxhighlight>

Applying IconResource to our Code

With an understanding of what "IconResourceAttribute" is we can now go about applying this attribute class to our code.

  1. Launch Visual Studio as admin and select "Open a Project or Solution".
  2. Navigate to and select the solution file.
  3. Click the "Open" button.


Before we add the attribute to our main class we need to add the icon as a resource file in our project.

  1. Right-click the project in the solution explorer
  2. Select "Properties" from the pop-out menu.
  3. In the project properties select "Resources".
  4. A resources file does not exist, so we need to create one.


  1. With the default resources file added...
  2. ...click the "Add Resource" drop-down and select "Add Existing File".
  3. Navigate to and select the "CssBadge.png" file saved out of Grooper.
  4. Click the "Open" button.


  1. A "Resources" folder and the "CssBadge.png" file have been added to our project.
  2. You can see the file represented here.
  3. Close the properties of the project.
  4. Save the changes when prompted.


  1. Right-click the project in the solution explorer.
  2. In the pop-out menu select "Add > New Item".
  3. In the "Add New Item" window select "C# Class".
  4. Name the class:
    SetStyles.cs
  5. Click the "Add" button.


The "IconResource" attribute class is part of the "Grooper" assembly. In order to use this class we will need to add a using directive for "Grooper".

Before adding "Grooper" as a using directive it needs to be referenced in our project. Thankfully, the solution we created out of Grooper is based on a template that has done this work for us. The .csproj file that was created as part of our solution is an XML formatted file that has defined several references for us. As a result, there are several references already built into our project. With that understanding, let's continue forward.


  1. Add the using directive:
    <syntaxhighlight lang="csharp" line start="6">using Grooper;</syntaxhighlight>
    If you type the code out instead of copy/pasting from here you will notice the linter will recognize the "Grooper" assembly because it is in your references, which will allow you to auto-complete if you so choose by pressing tab. The same will be true now for members of the "Grooper" namespace (such as the following "IconResource" class) as you continue to write code.
  2. On the line above the main class add the "IconResource" attribute:
    <syntaxhighlight lang="csharp" line start="11">[IconResource("CssBadge")]</syntaxhighlight>
    Again, note the "IconStyle" parameter is optional and not including it will use the default "Normal" style. Feel free to experiment with the options available from the enumeration.
  3. Note that the .png extension is not needed

Inspecting and Searching

Now that we have added our first piece of Grooper code it might be useful to take a quick aside and get exposure to a couple of tools that you may find useful moving forward. Understanding where to get more information can often prove more useful than just being handed the definition of something.

  1. Mouse-over the "IconResource" class to get more information.
    • You can see information regarding it's parent namespace as well as comments written by the developers.


The mouse-over information can be useful, but seeing the de-compiled source code can explain even more. Keep in mind that Visual Studio's ability to de-compile is reliant on you agreeing to their legal terms about the copy-right of source code.

  1. Right-click the "IconResource" class and choose "Go to Definition" from the pop-out menu.


  1. A separate tab will open and show you the source.
    • The de-compilation will occur in the language you are working in. The project we are working in is in C#, so the code will be shown in C#, even though most of Grooper's code was written in VB.NET.
  2. You will even be taken to the specific line where this class is defined.


If you want to do some real digging, you can view the contents of an assembly in the "Object Browser".

  1. Right-click the "Grooper" assembly in the "References" section of the Solution Explorer and choose "View in Object Library".


  1. A separate tab will open and show the "Object Browser".
  2. Expand the assembly you wish to explore.
  3. Choose a type you wish to inspect.
  4. You can see information about the selection.
  5. You can also select members of a type and see information about them as well.

DataContract and DataMember

The object command we are creating will consist of a dialog box with a property grid. The properties we define will ultimately apply a configuration to the Set Styles property of "DataFieldContainer" objects. Grooper stores properties of objects as serialized JSON. As a result, we will now learn about and apply an important attribute classes known as "DataContract" and its related "DataMember".

Definition

The .NET namespace "System.Runtime.Serialization" includes the "DataContract" class, which is crucial for enabling serialization and deserialization of data. Here's an explanation of what the "DataContract" does and its significance:

Purpose

  • The "DataContract" attribute is used to define a type that can be serialized or deserialized. Serialization is the process of converting an object into a form that can be easily transported (for example, into XML or JSON). Deserialization is the reverse process, converting serialized data back into an object.

Usage

  • You apply the "DataContract" attribute to a class or structure to specify that it is serializable. You can also use the "DataMember" attribute to mark the fields or properties of the class that you want to be serialized.

Serialization Process

  • When a class is marked with "DataContract", only members marked with "DataMember" are serialized. This allows for precise control over what data is serialized, which can be important for ensuring data security and reducing the amount of data transmitted.

Example

Here's a simple example to illustrate how "DataContract" and "DataMember" work:

<syntaxhighlight lang="csharp" line> using System; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO;

[DataContract] public class Person {

   [DataMember]
   public string FirstName { get; set; }
   [DataMember]
   public string LastName { get; set; }
   // This field will not be serialized because it does not have the DataMember attribute.
   public int Age { get; set; }

}

class Program {

   static void Main()
   {
       Person person = new Person() { FirstName = "John", LastName = "Doe", Age = 30 };
       // Serializing the person object to JSON
       DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
       using (MemoryStream stream = new MemoryStream())
       {
           serializer.WriteObject(stream, person);
           stream.Position = 0;
           StreamReader reader = new StreamReader(stream);
           string json = reader.ReadToEnd();
           Console.WriteLine("Serialized JSON: " + json);
       }
       // Deserializing from JSON back to a Person object
       string jsonData = "{\"FirstName\":\"John\",\"LastName\":\"Doe\"}";
       using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonData)))
       {
           Person deserializedPerson = (Person)serializer.ReadObject(stream);
           Console.WriteLine($"Deserialized Person: {deserializedPerson.FirstName} {deserializedPerson.LastName}");
       }
   }

} </syntaxhighlight>

Explanation of the Example

  • DataContract Attribute: The "Person" class is marked with the "DataContract" attribute, indicating it can be serialized.
  • DataMember Attribute: The "FirstName" and "LastName" properties are marked with the "DataMember" attribute, so they will be included in the serialization process. The "Age" property is not marked with "DataMember", so it will not be serialized.
  • Serialization: The "DataContractJsonSerializer" is used to serialize the "Person" object to JSON format.
  • Deserialization: The same serializer is used to deserialize the JSON data back into a "Person" object.

Key Points

  • Selective Serialization: You can choose which members of a class to serialize, which is useful for controlling the data exposed and transferred.
  • Interoperability: Using "DataContract" ensures compatibility with other platforms and technologies, as it can serialize to standard formats like XML and JSON.
  • Version Tolerance: "DataContract" supports versioning, allowing new members to be added to the contract without breaking existing clients.

In summary, the "DataContract" attribute in .NET provides a way to define which classes and members are serializable, enabling controlled and flexible data serialization and deserialization.

Applying DataContract and DataMember to our Code

As the previous definition states, the "DataContract" and associated "DataMember" attribute classes are in the "System.Runtime.Serialization" namespace, so we will need to include a using directive for them. "System.Runtime.Serialization" is already an assembly in our project's references, so adding it will be simple. Once added, "DataContract" can be easily be added as an attribute to our main class. The same is true for "DataMember" once we create our first property.

  1. Note that "System.Runtime.Serialization" is already in our project's references.
  2. Add the using directive:
    <syntaxhighlight lang="csharp" line start="7">using System.Runtime.Serialization;</syntaxhighlight>
  3. Modify the attribute line by adding "DataContract":
    <syntaxhighlight lang="csharp" line start="11">[DataContract, IconResource("CssBadge")]</syntaxhighlight>


Before we step inside our main class and add properties, and attributes to those properties, let's set a "public" access modifier to our class declaration to make it accessible from any other code in the same assembly or another assembly that references it.

  1. Add access modifier to class declaration:
  2. <syntaxhighlight lang="csharp" line start="12">public class SetStyles</syntaxhighlight>
  3. Making this class public has generated a warning for us to address.


To address the warning offered by Visual Studio we need to add XML tags for C# documentation comments. You can choose to ignore this warning, as it won't cause compile issues, but commenting code is a good practice. Additionally, XML doc. comments supply not only supply mouse-over tooltips when in Visual Studio, but Grooper leverages these comments and displays them within the "help" of Grooper (we'll observe this later).

  1. Return the linve above the class attributes and insert:
  2. <syntaxhighlight lang="csharp" line start="11">///</syntaxhighlight>
    Visual Studio will recognize this syntax and insert the following:
    <syntaxhighlight lang="csharp" line start="11">/// <summary>

/// /// </summary></syntaxhighlight>


Feel free to add your own summary comment, come back to this part later when you have a better idea of what you'd want to write, or as stated previously you can not add the comment block at all (again, not having it won't affect compilation.)

Or, if you want, you can add the comments I have created: <syntaxhighlight lang="csharp" line start="11"> /// <summary> /// Easily set CSS styles in a dialog box with properties /// </summary> /// <remarks> /// This will add an object command to "DataFieldContainer" objects that will open a dialog box to allow a user to easily set CSS styles. /// Upon execute the property values will be inserted as CSS into the "Style Sheet" property of the respective Data Element. /// </remarks> </syntaxhighlight>

Moving forward, the assumption will be that you have added my comments, therefore line numbering will reflect as much.


We now need to create a member of our class that will have the "DataMember" attribute class applied to it. In our case we will work with a property that will ultimately end up in the "property grid" of the dialog box that our object command will generate.

We will start with a property we will call "LabelWidth". It will define the width of the labels of the child "DataField" objects (in code "DataField" is the base class for both Data Field and Data Column objects) within our target "DataFieldContainer".

  1. Inside the "SetStyles" class define a property as follows:
  2. <syntaxhighlight lang="csharp" line start="24">public string LabelWidth { get; set; }</syntaxhighlight>
  3. To clear the XML comment warning add the following summary remarks:
    <syntaxhighlight lang="csharp" line start="21">/// <summary>

/// A property to set the CSS "width" setting of child Data Elements /// </summary></syntaxhighlight>


  1. Insert a line above the property and add the attribute:
  2. <syntaxhighlight lang="csharp" line start="24">[DataMember]</syntaxhighlight>

Category and DisplayName

Now that we've added our first property and applied the attribute classes necessary to serialize the output, let's learn about a couple of other commonly used attribute classes, "Category" and "DisplayName", and apply them as well.

Definition

The "Category" and "DisplayName" attribute classes are part of the System.ComponentModel namespace in .NET and are primarily used for enhancing the design-time experience, particularly in property grids. Property grids are featured very prominently in Grooper.

"Category" Attribute

The "Category" attribute is used to group properties of a class into categories within a property grid. This makes it easier to organize and locate properties when inspecting or editing them in a visual designer.

<syntaxhighlight lang="csharp" line> using System; using System.ComponentModel;

public class MySettings {

   [Category("Appearance")]
   public string BackgroundColor { get; set; }
   [Category("Appearance")]
   public string Font { get; set; }
   [Category("Behavior")]
   public bool IsResizable { get; set; }
   [Category("Behavior")]
   public bool IsDraggable { get; set; }

} </syntaxhighlight>

In this example:

  • Properties "BackgroundColor" and "Font" are grouped under the "Appearance" category.
  • Properties "IsResizable" and "IsDraggable" are grouped under the "Behavior" category.
  • When displayed in a property grid, these properties will be organized under their respective categories.

"DisplayName" Attribute

The "DisplayName" attribute is used to specify a custom display name for a property. This is useful when you want to present a more user-friendly or descriptive name for a property than what is provided by its identifier.

<syntaxhighlight lang="csharp" line> using System; using System.ComponentModel;

public class MySettings {

   [DisplayName("Background Color")]
   public string BackgroundColor { get; set; }
   [DisplayName("Font Family")]
   public string Font { get; set; }
   [DisplayName("Resizable")]
   public bool IsResizable { get; set; }
   [DisplayName("Draggable")]
   public bool IsDraggable { get; set; }

} </syntaxhighlight>

In this example:

  • The "BackgroundColor" property will be displayed as "Background Color".
  • The "Font" property will be displayed as "Font Family".
  • The "IsResizable" property will be displayed as "Resizable".
  • The "IsDraggable" property will be displayed as "Draggable".

Usage in Property Grid

When these attributes are applied to properties in a class, and this class is then used in a property grid within a development environment or custom application, the property grid will:

  • Group properties according to the "Category" attribute.
  • Display properties using the names specified by the "DisplayName" attribute.

This improves the usability and readability of the properties for developers and end-users, making it easier to configure and manage properties within the UI.

Summary

  • Category Attribute: Groups properties into categories for better organization in property grids.
  • DisplayName Attribute: Specifies a custom, user-friendly name for a property to enhance readability and understanding.

Both of these attributes enhance the design-time and runtime experience by making property management more intuitive and user-friendly.

Applying Category and DisplayName to our Code

As the previous definition states, the "Category" and "DisplayName" attribute classes are in the "System.ComponentModel" namespace, so we will need to include a using directive for that. It is defined within the "System" assembly that is in our project's references, so adding the required using directive will be simple. Once added, "Category" and "DisplayName" can easily be leveraged as attributes on our property.

  1. "System.ComponentModel" is a namespace defined in the "System" assembly that is already in our references.
  2. "System" is defined as a using directive, however...
  3. ...an explicit using directive for "System.ComponentModel" must be used.
  4. Modify the attribute line of the "LabelWidth" property by adding the new attribute classes and a string argument for their names:
    <syntaxhighlight lang="csharp" line start="25">[DataMember, Category("Label"), DisplayName("Width")]</syntaxhighlight>