NiceLabel.Blog Everything you wanted to know about NiceLabel

21Oct/11Off

Password Protected Forms – A Warning

As I already mentioned in one of the previous posts, you can protect your forms so nobody can modify them or even view details of actions. You have to be careful though that you do not forget the password, because there is no way you can decrypt the form actions without knowing the password. If you forget the password, you will have to configure form again.

I would suggest using one of the password managers for storing the passwords because these days it is not easy to remember them all. I use KeePass because it is free and I can also use the password database on the Android phone, but you can use any one you like.

14Oct/11Off

Label Structure 2.9

New label of Label Structure utility is now available for download. The following has changed from the last release:

  • Support for sorting objects, variables, functions and databases by clicking the column header was added.
  • Information about functions now also includes a list of input variables.
  • ID column was added to the variables information.
  • All VB scripts can now be extracted from a .lbl file by using Tools->Extract VB scripts from label file.
  • Possibility to add all .lbl files from a selected folder and all subfolders when setting variable length, changing graphics paths, setting printer or extracting VB scripts from .lbl file.
  • A bug in "Set paths" command where not all selected labels were processed was fixed.
  • Support for creating DOT graph files for selected label was added. This allows you to visually see the connections between different parts of a label like variables, objects, and functions. You will have to use GraphViz to view the graphs though.

 

Label Graph

17May/11Off

Formatting numbers and date/time using current locale in NiceForm and NiceLabel Portal

Locale is a set of parameters that defines the user's language, country and any special variant preferences that the user wants to see in their user interface. Usually a locale identifier consists of at least a language identifier and a region identifier.

General settings usually include the following display format settings:

  • Number format setting
  • Character classification, case conversion settings
  • Date/Time format setting
  • String collation setting
  • Currency format setting
  • Paper size setting
  • Other minor settings

The locale settings are about formatting output given a locale. For example you can see some of the settings for the Slovenian locales on my machine in the screenshot below.

Region and Language

Even more options are available if you click the “Additional settings…” button.

Customize Number, Currency, Time and Date Format

To view or modify these changes  in Windows 7 you have to follow these steps:

  1. Click Start > Control Panel.
  2. Double-click the Region and Language icon. The Region and Language dialog box appears.

Please note that you have to be logged in with an account with Administrative Privileges in order for this to work.

Working with Locales in Python Scripts

To work with locales in Python scripts in NiceForm you have to use the locale module. Your script would typically start with something like this:

import locale
locale.setlocale(locale.LC_ALL, '')

This sets the locale for all categories (number format settings, currency format settings, date/time settings, etc.) to the user’s default setting.

You can also set the locale to a specific one. For example to change current locale in your Python script to German, you could use the following code:

locale.setlocale(locale.LC_ALL, 'deu_deu')

or to French

locale.setlocale(locale.LC_ALL, 'fra_fra')

Unfortunately locale module is not supported in IronPython (that is used to implement scripting in NiceLabel Portal) so you have to write a little different code. To obtain information about current locale (or current culture as it is called in Silverlight) you have to use the following code:

import System
culture = System.Threading.Thread.CurrentThread.CurrentCulture


And to set the culture you would do this:

from System.Globalization import *
culture = CultureInfo("de-DE");
System.Threading.Thread.CurrentThread.CurrentCulture = culture

Formatting Numbers Using Current Locale

The following code converts values of two NiceForm (or NiceLabel Portal) variables (that are represented as strings) into floating point numbers using the current locales, calculates the difference between them and assigns this new value to the third variable value (again as a string value).

import sys
if sys.platform == 'silverlight':
    import System
    culture = System.Threading.Thread.CurrentThread.CurrentCulture
    number1 = System.Single.Parse(originalSellingPrice.Value, culture.NumberFormat)
    number2 = System.Single.Parse(sellingPrice.Value, culture.NumberFormat)
    diff = number1 - number2
    subtract_price.Value = diff.ToString("F")
else:
    import locale
    locale.setlocale(locale.LC_ALL, '')
    number1 = locale.atof(originalSellingPrice.Value)
    number2 = locale.atof(sellingPrice.Value)
    diff = number1 - number2
    subtract_price.Value = locale.format("%.2f", diff)


Script should work in both NiceLabel Portal (code block after the if statement) and NiceForm (code block after the else statement).

Formatting Date/Time Using Current Locale

Again code for NiceLabel Portal and NiceForm is a little different. It does however in both cases display date and time in different formats using user’s current locale settings.

import sys
if sys.platform == 'silverlight':
    import System
    dt = System.DateTime.Now
    d1.Value = "Long time: " + dt.ToLongTimeString()
    d2.Value = "Long date: " + dt.ToLongDateString()
    d3.Value = "Short time: " + dt.ToShortTimeString()
    d4.Value = "Short date: " + dt.ToShortDateString()
    d5.Value = "Day of the week: " + dt.ToString("ddd") + " (abbreviated), " + dt.ToString("dddd") + " (full)"
    d6.Value = "Month name: " + dt.ToString("MMM") + " (abbreviated), " + dt.ToString("MMMM") + " (full)"
else:
    from datetime import date
    import time
    import locale
    locale.setlocale(locale.LC_ALL, '')   

    date1 = date.today();
    d1.Value = time.strftime("Long time: %H:%M:%S");
    d2.Value = date1.strftime("Long date: %d.%B %Y");
    d3.Value = time.strftime("Short time: %X");
    d4.Value = date1.strftime("Short date: %x");
    d5.Value = date1.strftime("Day of the week: %a (abbreviated), %A (full)");
    d6.Value = date1.strftime("Month name: %b (abbreviated), %B (full)");

To use a specific locale (French in this case) you would do this:

import sys
if sys.platform == 'silverlight':
    import System
    from System.Globalization import *
    culture = CultureInfo("fr-FR");
    System.Threading.Thread.CurrentThread.CurrentCulture = culture
    dt = System.DateTime.Now
    d1.Value = "Long time: " + dt.ToLongTimeString()
    d2.Value = "Long date: " + dt.ToLongDateString()
    d3.Value = "Short time: " + dt.ToShortTimeString()
    d4.Value = "Short date: " + dt.ToShortDateString()
    d5.Value = "Day of the week: " + dt.ToString("ddd", culture) + " (abbreviated), " + dt.ToString("dddd", culture) + " (full)"
    d6.Value = "Month name: " + dt.ToString("MMM", culture) + " (abbreviated), " + dt.ToString("MMMM", culture) + " (full)"
else:
    from datetime import date
    import time
    import locale
    locale.setlocale(locale.LC_ALL, 'fra_fra')   

    date1 = date.today();
    d1.Value = time.strftime("Long time: %H:%M:%S");
    d2.Value = date1.strftime("Long date: %d.%B %Y");
    d3.Value = time.strftime("Short time: %H:%M");
    d4.Value = date1.strftime("Short date: %d.%b.%Y");
    d5.Value = date1.strftime("Day of the week: %a (abbreviated), %A (full)");
    d6.Value = date1.strftime("Month name: %b (abbreviated), %B (full)");


Related posts:

http://www.primozic.net/nl/manipulating-date-and-time-using-python-in-niceform-and-nicelabel-portal/

http://www.primozic.net/nl/working-with-modules-in-python-scripts-in-niceform-and-nicelabel-portal/

http://www.primozic.net/nl/working-with-strings-in-python-scripts-in-niceform/

http://www.primozic.net/nl/python-scripting-in-niceform-and-nicelabel-portal/

11May/11Off

How can I work with files in NiceLabel Portal?

NiceLabel Portal uses Microsoft Silverlight as its underlying technology. Because Silverlight is a browser-based plug-in, it has by default the lowest security privileges to ensure a safe browsing experience. This restriction introduces a number of challenges, especially when it comes to working with files. For example you do not have direct access to files on your drive from NiceLabel Portal. There is a solution though that might solve most of the problems.

Isolated storage is a great way to store data on the end user’s local computer. It’s flexible in that it works in all modes of Silverlight operation (in-browser, out-of-browser, elevated out-of-browser) and works as a virtual file system. Isolated storage is tied to individual user and lies outside of the browser cache. This means that even if a user clears browser history, files within isolated storage will remain intact.

To work with Isolated Storage in NiceLabel Portal you will have to use Python scripts. Here are scripts for some of the most common scenarios you might encounter when working with Isolated Storage.

Basics of Isolated Storage

The System.IO.IsolatedStorage namespace provides the functionality to work with a user’s isolated storage area. This area can be accessed through the IsolatedStorageFile class, which exposes two methods that retrieve an IsolatedStorageFile. These methods are GetUserStoreForApplication and GetUserStoreForSite. The GetUserStoreForApplication can be used to retrieve a user’s isolated storage for a specific Silverlight application, defined by the full URL to the .xap. The GetUserStoreForSite method gets a user’s isolated storage for the entire domain.

from System.IO.IsolatedStorage import *
store = IsolatedStorageFile.GetUserStoreForApplication()

Once you’ve retrieved an IsolatedStorageFile, you can use it to manage a virtual file system, which gives you the ability to work with files and directories.

Checking if Isolated Storage is enabled

Before using Isolated Storage you should check if it is enabled because user can disable it in the “Microsoft Silverlight Configuration” dialog box under the “Application Storage” page). To configure the Silverlight plug-in (not just the Application Storage) a user can right-click the opened solution in the NiceLabel Portal or simply find Microsoft Silverlight in the Windows Start menu.

image

To programmatically check if Isolated Storage is enabled you can use the following code:

from System.IO.IsolatedStorage import *

isEnabled = IsolatedStorageFile.IsEnabled
if (isEnabled):
    # do something
else:
    # display error message

Checking the Available Space

By default in-browser application gets 1 MB of free space. The IsolatedStorageFile class exposes two read-only properties that inform you of an isolated storage area’s memory situation. The first property, Quota, holds the total number of bytes allocated to the storage area. The other property,  AvailableFreeSpace, represents the number of bytes remaining in the Isolated Storage.

from System.IO.IsolatedStorage import *

store = IsolatedStorageFile.GetUserStoreForApplication()
usedSize.Value = "Used size: " + str(store.UsedSize) + " bytes"
quota.Value = "Quota: " + str(store.Quota) + " bytes"
availableFreeSpace.Value = "Available free space: " + str(store.AvailableFreeSpace) + " bytes"

Requesting more space

To increase the Isolated Storage quota, you must call the IncreaseQuotaTo method from a user-initiated event, such as in an event handler for a button-click event. Unfortunately because of the way action execution is implemented in NiceLabel Portal you will not be able to increase the quota by a Python script even if you have the script defined on the “On click” event of the button object. You will have to write your own application that calls the above mentioned method or contact NiceLabel support for help.

Listing the contents of the virtual file system

The IsolatedStorageFile class provides two methods that enable you to retrieve the items within a storage area. The first method, GetDirectoryNames,  enables you to get the names of the directories that match a certain pattern; the GetFileNames method allows you to search for files that match a particular filter. To perform the search just provide the path to the file or directory. If the directory or file name is found an array with one element will be returned. Otherwise, an empty set will be returned. Wildcard characters can also be used to match file names (the * character matches any number of characters, and the ? character matcher any single character.

from System.IO.IsolatedStorage import *

store = IsolatedStorageFile.GetUserStoreForApplication()
results1 = store.GetFileNames("*.txt");
results2 = store.GetFileNames("Folder/*");
results3 = store.GetFileNames("configfile*"); 

results4 = store.GetDirectoryNames("*");

# convert array of directory names into a string separated by commas
if len(results4) > 0:
    all = ",".join(results)

Creating directories within Isolated Storage

The IsolatedStorageFile class has a method called CreateDirectory that enables you to create a directory within the isolated storage space.

from System.IO.IsolatedStorage import *

store = IsolatedStorageFile.GetUserStoreForApplication()
store.CreateDirectory("Folder1")
store.CreateDirectory("Folder1/Sub/Leaf")

 

The first call to CreateDirectory is pretty simple; it creates a subdirectory under an existing

directory. The second call shows an additional feature. If you provide an absolute path to a subdirectory further down the line, all missing directories along the way will automatically be added. Once a directory exists, you can create files in it.

Checking if an item exists

from System.IO.IsolatedStorage import *

store = IsolatedStorageFile.GetUserStoreForApplication()

msg2.Value = str(store.FileExists(fileName.Value))
if store.FileExists(fileName.Value):
    msg.Value = "File already exists."
else:
    msg.Value = "File does not exist!"

 

Removing items from Isolated Storage

from System.IO.IsolatedStorage import *

store = IsolatedStorageFile.GetUserStoreForApplication()

if store.FileExists(fileName.Value):
    store.DeleteFile(fileName.Value)

if store.DirectoryExists(directoryName.Value):
    store.DeleteDirectory(directoryName.Value)

Possible problems

There are a few problems that you should be aware of when working with Isolated Storage.

  1. Administrators can set disk quota per user and assembly which means there is no guarantee on space available. So it is very important to add exception handling to your code.
  2. Computer can be locked down by administrative security policies preventing applications from writing to the Isolated Storage.
  3. Even though Isolated Storage is placed in a hidden folder it is possible, with a bit of effort, to find the folder. Therefore the data stored is not completely secure as users can change or remove files.

Isolated Storage Best Practices

When you use isolated storage, following these guidelines will help you avoid problems and make the most of the protection isolated storage provides.

  • Wrap all calls to isolated storage within try/catch blocks to be resilient to potential IsolatedStorageExceptions, which can be thrown if isolated storage is disabled or if the store has been deleted.
  • Keep isolated storage paths as small as possible to prevent the internal full path from reaching the 260-character limit.
  • Encrypt sensitive data stored in isolated storage.
  • Use IsolatedStorageSettings to store objects and simple settings in isolated storage.
from System.IO.IsolatedStorage import *

# Write to application settings
settings = IsolatedStorageSettings.ApplicationSettings
settings.Add("FirstName", FirstName.Value)
settings.Add("LastName", LastName.Value)

# Read from application settings
FirstName.Value = settings["FirstName"]
LastName.Value = settings["LastName"]

# Remove just first name from application settings
settings.Remove("FirstName")

# Clear all settings
settings.Clear()

Please note that all code samples in this post will only work in NiceLabel Portal. Even though you will write them in NiceForm you will only be able to test them in NiceLabel Portal.

You can find all the samples in one sample NiceForm file (it is in a .zip file so you will have to uncompress it first).

3May/11Off

How can I fix the “The ‘Microsoft.Jet.OLEDB.4.0′ provider is not registered on the local machine.” error in NiceLabel Portal?

Usually you get this error when you try to use Microsoft Excel file in NiceLabel Portal solution – in a form or in a label file when NiceLabel Portal is installed on a 64-bit operating system. Although I would not suggest using Excel files as a database for anything else but a demo, you can get around this particular problem.

What you have to do is to set “Enable 32-Bit Applications” property of the “EPWebPrintingAppPool” application pool in IIS (Internet Information Services) to “True”.

In IIS 7 you have to open the list of Application Pools, right click the selected application pool and select “Advanced Settings” in the pop up menu.

IIS - List of application pools

When “Advanced Settings” dialog box is shown change the “Enable 32-Bit Applications” property to “True”.

IIS - Advanced settings for application pool

Now all you have to do is reload your solution file in the browser.

31Mar/11Off

How can I select label print quantity from database in NiceLabel?

Selecting print quantity from database in NiceLabel Pro is quite easy.

  1. Run NiceLabel and create new label.
  2. Add new database by selecting “Data Access…” option in the “Data” menu to open the “Data Access Functions” dialog box.

NiceLabel - Database Access Functions

  1. Once in the “Data Access Functions” dialog box, click the “New” button to open the”Database Access” dialog box.

NiceLabel - Database Access

  1. Define or browse for the database.
  2. Once you have selected the database you would like to use, go to the “Fields” tab and select fields you need.

NiceLabel - Database Access Field Definition

  1. Go to “Data Retrieving” page.
  2. In the section “Number of Labels per Record”, select “Number of labels is defined at print time” and then “stored in a database field”.

image

  1. Select the database field that contains the quantity.
  2. Click OK to close the “Database Access” window.
  3. Click Close to close the “Database Access” window.
  4. Add objects to the label and save the label.

image

  1. When you start printing and the “Print” dialog is shown, you will see that the “Variable quantity (defined from database field)” option is selected.

image

30Mar/11Off

Chaining comparison operators in Python

One of the little known facts about Python that can come handy is a possibility to chain comparison operators like this:

x = 5;
print 3 < x < 10;
print x < 10 < x*10;

or

x == y == z

or even

x is y is z
13Mar/11Off

Actions in NiceForm and NiceLabel Portal

One of the main strengths of NiceForm and NiceLabel Portal are actions that let you build workflows that accomplish manual chores quickly, efficiently and effortlessly. You don’t have to know any scripting languages or write any code (unless you want to). Instead, you create and execute workflows simply by dragging and dropping actions. Currently there are 29 actions available in NiceForm. They are grouped in 6 groups: Labeling, Variables, Batch Printing, Database, Connectivity and Other.

Labeling actions: “Open label”, “Print label”, “Set printer”, “Send custom commands”, “Run command file”, “Close label”, “Define printer settings”.

Variables actions: “Set variable”, “Save variable data”, “Load variable data”.

Batch printing actions: “For every label”, “For every record in a table”, “For loop”.

Database actions: “Refresh database”, “Execute SQL statement”, “Import data into database”.

Connectivity actions: “Read data from serial port”, “Write data to serial port”, “Send data to TCP/IP port”, “Acquire image”.

Other actions: “Open another form”, “Open document/program”, “Refresh previews”, “Quit”, “Execute script”, “Move focus to object”, “View log file”, “Browse for file or folder”, “Verify license”.

Where can actions be used in the form?

Actions are executed on certain events that happen on the form. Form itself has three events - On Form Load, On Form Close and On Timer – that can be used to execute actions when form is loaded, closed or when a specified time interval elapses. Also almost all objects (with the exception of the Frame object) have one or more events that trigger action execution (check the “Events” page of the object properties dialogs). Usually these are: On Click (when object like Button is clicked), On Focus (when object becomes active), On Exit (when input focus shifts away from the object) or On Change. Even variable can execute actions when its value changes.

NiceForm - Edit field events

Defining actions

You define actions and their properties in the “Actions Editor” dialog box. This dialog is the same in both NiceForm and NiceWatch so everything that works in NiceForm should also work in NiceWatch (there are some differences in the action types supported).

“Actions Editor” has three sections. On the left you can see a list of all available actions grouped together by functionality (or action type) in several groups. To define action workflows you just have to drag and drop the action to the area on the right or select one and click “Insert” button at the top of the window.

There is a small toolbar at the top of the right section.  “Properties” button opens the properties of the currently selected action in the right pane(you get the same effect by double clicking the action). By clicking the “Delete” you will delete the selected action. Click on the arrow buttons to change the order and hierarchy of the actions in the right pane. Some of the actions like “Open label”, “For every label”, “For every record in a table” and “For loop” work on their “sub” actions – actions that are essentially their child actions. See the picture below for some samples.

Actions editor

The two remaining buttons in the top toolbar are the “Copy” and “Paste” buttons. You can copy/paste actions between different parts of NiceForm, between different instances of NiceForm and even between NiceForm and NiceWatch (if action is available in both applications).

At the bottom of the dialog you can find buttons to close the window, open help file and switch between Basic and Advanced views of the window. You can see the “Actions Editor” in the (default) Basic mode below. The difference between them is that the Basic view shows only the basic, most used actions, while the Advance view shows all available actions.

Actions editor - Basic

Protecting your know-how

If you do not want the end-user to modify forms you have created or to see how you implemented a very complicated script, you can lock (protect) the form with a password. In this case all the actions will be encrypted. Of course you have to make sure you do not forget the password because in that case you will have to design the forms from the start.

To lock the form, do the following:

  1. Open your form.
  2. Select the “Form Properties” option in the “File” menu or double click the form to open “Form Properties” dialog box.
  3. Go to the Advanced tab.
  4. Tick the “Form locked” option.
  5. Tick the “Password protection” and click on the “Set password” button.
  6. Provide the password and click on the “OK” button to close the “Set Password” dialog.
  7. Click on the “OK” button to close the “Form Properties” dialog box.
  8. Select the command Save in the File menu.
  9. Close the form.

Actions that are not supported in NiceLabel Portal

Some of the actions are currently not yet supported in NiceLabel Portal. These are: “Close label”, “For every label”, “Move focus”, “Refresh previews”, “Read data from serial port”, “Write data to serial port”, “Acquire image”, “Browse for file or folder”, “Define printer settings” and “Verify license”. “Import data into database” action is available only in NiceLabel Portal. We plan to support all actions that make sense in the browser environment in the future releases.

3Mar/11Off

Manipulating date and time using Python in NiceForm and NiceLabel Portal

Time values are represented with the time class. Times have attributes for hour, minute, second, and microsecond. They can also include time zone information. A time instance only holds values of time, and not a date associated with the time.

from datetime import datetime;

time1 = datetime.time(datetime.now()); # Get current time
h = time1.hour;
m = time1.minute;
s = time1.second;
ms = time1.microsecond;
tz = time1.tzinfo;
min = time1.min;
max = time1.max;

d1.Value = "Hour: " + str(h);
d2.Value = "Minute: " + str(m);
d3.Value = "Second: " + str(s);
d4.Value = "Microsecond: " + str(ms);
d5.Value = "Time zone: " + str(tz);
d6.Value = "Earliest: " + str(min);
d7.Value = "Latest: " + str(max);

Calendar date values are represented with the date class. Instances have attributes for year, month, and day. It is easy to create a date representing current date using the today() class method. As with time, the range of date values supported can be determined using the min and max attributes.

from datetime import date;

date1 = date.today(); # Get current date
year = date1.year;
month = date1.month;
day = date1.day;
ordinal = date1.toordinal();
min = date1.min;
max = date1.max;

d1.Value = "Day: " + str(day);
d2.Value = "Month: " + str(month);
d3.Value = "Year: " + str(year);
d4.Value = "Ordinal: " + str(ordinal);
d5.Value = "Earliest: " + str(min);
d6.Value = "Latest: " + str(max);

How can I add or subtract from a date?

To add or subtract from a date use the datetime.timedelta object.

from datetime import datetime, timedelta, time;

time1 = datetime.now();
diff = timedelta(weeks=52);  # 1 year
time2 = time1 + diff;
diff = timedelta(days=730);  # 2 years
time3 = time1 + diff;
diff = timedelta(hours=240);  # 10 days
time4 = time1 + diff;
diff = timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=600);  # Adds up to 365 days
time5 = time1 - diff;

d1.Value = "Current date and time: " + str(time1);
d2.Value = "Added 52 weeks (1 year): " + str(time2);
d3.Value = "Added 730 days (2 years): " + str(time3);
d4.Value = "Added 10 days: " + str(time4);
d5.Value = "Subtracted 365 days: " + str(time5);

How can I calculate difference of two dates?

When two dates are subtracted they produce timedeltas.

from datetime import date;

date1 = date.today();
date2 = date(1973, 7, 6);
diff = date1 - date2;

d1.Value = "Current date: " + str(date1);
d2.Value = "My birthday: " + str(date2);
d3.Value = "I am : " + str(diff.days) + " days old.";

Can I compare date or time values?

Both time and date values can be compared using standard operators to determine which one is earlier or later.

from datetime import date, time;

date1 = date.today();
date2 = date(1973, 7, 6);
time1 = time(12, 0, 0);
time2 = time(13, 5, 0);

d1.Value = "Date 1: " + str(date1);
d2.Value = "Date 2: " + str(date2);
d3.Value = "Date 1 < Date 2: " + str(date1 < date2);
d4.Value = "Time 1: " + str(time1);
d5.Value = "Time 2: " + str(time2);

d6.Value = "Time 1 > Time 2: " + str(time1 < time2);

How can I replace just part of date?

from datetime import datetime;

date1 = datetime.now();            # Use current date and time
date2 = date1.replace(year=2012);  # Change year to 2012
date3 = date1.replace(month=12);   # Change month to December
date4 = date1.replace(day=31);     # Change day to 31
date5 = date1.replace(day=31, month=12, year=2012); # Change day, month and year all at once.

d1.Value = str(date1);
d2.Value = str(date2);
d3.Value = str(date3);
d4.Value = str(date4);
d5.Value = str(date5);

Formatting time and date

Default string representation of a datetime object uses the ISO 8601 format (YYYY-MM-DDHH:MM:SS.mmmmmm). Other formats can be generated using strftime() method. The following directives can be embedded in the format string:

Directive Meaning
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.

Here are some examples of using different directives:

from datetime import date;

format1 = "%A,  %B %d, %Y";
format2 = "Today is day %j of the year.";
format3 = "Short month name: %b; Short weekday name: %a";

date1 = date.today();
d1.Value = date1.strftime(format1);
d2.Value = date1.strftime(format2);
d3.Value = date1.strftime(format3);

How can I get a week number from a date?

from datetime import date;

format = "Today is day %w of the %W week of the year.";

date1 = date.today();
d1.Value = date1.strftime(format);

All code samples above should work in NiceForm and NiceLabel Portal. You can find all samples in sample form file (PyDateTime.xff).

16Feb/11Off

How can I automate NiceLabel from a scripting language like VBScript or Python?

You can find two examples of automating NiceLabel from a scripting language. The first one is in VBScript and the other one in Python. Both samples do the same thing: run NiceLabel, open label file, iterate through a list of variables, set their values and print the label. At the end label is closed and NiceLabel shuts down.

Set nice = CreateObject("NiceLabel5.Application")
If (nice is Nothing) Then
  MsgBox("Cannot open NiceLabel!")
Else
  fileName =  "c:\Labels\Sample.lbl"
  Set lbl = nice.LabelOpenEx(fileName)

  If (lbl is Nothing) Then
      MsgBox("Cannot open '" & fileName & "'!")
  Else
     Set variables = lbl.Variables

     For i = 1 to variables.Count
       Set variable = variables.Item(i)
       ' Use only prompt variables that require prompt.
       If (variable.VarType = 1) and (variable.DefType <> 2) Then
         MsgBox(variable.Name)
         variable.SetValue("Value" & CStr(i))
       End if

       ' Release interface to variable.
       Set variable = Nothing
     Next

     'Set printer
     lbl.PrinterName = "Altec TTP-343 Plus"

     ' Print 1 label
     quantity = "1"
     lbl.Print(quantity)

     ' Release interface to variables list.
     Set variables = Nothing

     ' Release interface to label to close it
     Set lbl = Nothing
  End If

  ' Close NiceLabel
  nice.Quit
  Set nice = Nothing
End if

And the same thing in Python.

import win32com.client
import os.path

# Run NiceLabel
nice = win32com.client.Dispatch("NiceLabel5.Application")
if (nice == None):
    error = "Cannot open NiceLabel";
else:
    fileName = os.path.normpath("c:/Users/alesp/Documents/My Labels/Labels/Sample.lbl");
    lbl = nice.LabelOpenEx(fileName);
    if (lbl == None):
        error = "Cannot open '{0}'".format(fileName);
    else:
        variables = lbl.Variables;
        for i in range (1, variables.Count + 1):
            variable = variables.Item(i);
            if (variable.VarType == 1) and (variable.DefType <> 2):
                variable.SetValue("Value" + str(i));
            # Release interface to variable.
            variable = None;

        # Set printer
        #lbl.PrinterName = "Altec TTP-343 Plus";

        # Print 1 label
        quantity = "1";
        lbl.Print(quantity);

        # Release interface to variables list.
        variables = None;

        # Release interface to variables list and close label.
        lbl = None;

    nice.Quit();
    nice = None;

Please note that these samples will only work on a desktop and not in NiceLabel Portal in a browser. You will also need to have NiceLabel 5 installed.

For more information about automating NiceLabel see the NiceLabel Programming Guide (PDF).