Tuesday, December 4, 2018


Jerry Nordbye
November/26/2018
IT FND 100 B au Oct: Foundations of Programming: Python
Assignment 7

A script to show error handling and Pickling

Introduction

               Write a simple script showing error handling with Pythons try-except and using Pickling to save and read objects from disk.

Variables

               Since this is a small script we only have a few variables [Figure 1]  objFileName and objFileName2  are used to store the file names we’ll be using. The two variables for our test lists are lstInventoryDishes and lstInventoryUtensils.


[Figure 1] variable list

Try Except

               The try-except block (Real Python. “Python Exceptions: An Introduction.”) is Pythons way of catching runtime errors. In its most basic form you put the code that has potential to throw a run time error in the try part of the block [Figure2] if a run time error comes up Python will execute what’s in the except block [Figure 2] instead of displaying the error on the screen and exiting.

[Figure 2] Basic try-except block

               You can trap all errors and treat them as one [Figure 2] or you can trap individual errors [Figure 3] and treat them accordingly while still having a catch all for other errors. Figure 3 also demonstrates you can have a try-except block with another try-except block. In figure 3 we catch the end of file error (EOFError) so we know we have read all the contents of the file and can continue instead of Python throwing and error and exiting the script.

[Figure 3] Embedded try-except blocks

               The try-except block can also end with “else” and or “Finally” [Figure 4].  The “else” block is run if there are no exceptions while the “Finally” block will run whether there is an error or not.

[Figure 4] Try example from https://docs.python.org/3/tutorial/errors.html [External site]

               There are many individual types of errors you can catch.  Here are a few, ZeroDivisionError, FileNotFoundError, FileExistsError.  A nice list can be found here at airbrake.io https://airbrake.io/blog/python-exception-handling/class-hierarchy [External site]

Pickling

               Pickling (Pickle - Python Object Serialization.) is a way to store objects in Python to either a file or over the network. Couple things to watch out for. Pickling is a Python only thing if you need interoperability with other languages look towards JSON. Also you can run into issue Pickling data in one version of Python and trying to read it in another. You can Pickle many types of objects in Python. Below is a list from Python.org  https://docs.python.org/3/library/pickle.html [External site]
  • NoneTrue, and False
  • integers, floating point numbers, complex numbers
  • strings, bytes, bytearrays
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module (using def, not lambda)
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).
You can use Pickling to serialize and entire object [Figure 5] or the individual elements within an object [Figure 6]. The dump method (pickle.dump()) is used to pickle and save an object. Pickle dumps arguments are the file object’s name and access mode.  The ‘b’ in the access mode argument “wb” stands for Binary, the file type. The saveInventoryWhole method saves the entire list as one object where the saveInventoryIndivd method uses the for loop to go thru the list and then saves each item individually.


[Figure 5] Pickle the entire list as one



[Figure 6] Pickle individual elements of an object

               To read the data back into the program you use the load method (pickle.load()). The load method takes one argument the file object name and unpickles and returns the object. Below are two examples of unpickling. The first example loadInventoryWhole method [Figure 7] loads the entire object which in this case is a list back in a once. Out next example loadInventoryIndivd method [Figure 8] needs to loop thru the entire file as we saved each element of the list individually.  We use the EOFError error to let us know we have reached the end of file. Seems wrong to do it this way but I have seen lots of examples doing just this and non-doing it any other way. Also, no complaints were made in regards of this method so it seems it’s the correct or accepted  way of handling this.



[Figure 7]  loadInventoryWhole


[Figure 8] loadInventoryIndivd

Output

               Since this is a very basic script the output is very minimal. The program saves two lists lstInventoryDishes and lstInventoryUtensils save them to file Inventory.dat and Inventory2.dat respectively, clears out the list,  reloads the list from disk and then prints the list out to show it did work. I have included a couple screenshots first from PyCharm [Figure 9] and next from the dos prompt [Figure 10]


[Figure 9] output in PyCharm


[Figure 10] output from Dos command box

Summary

               We created a simple script demonstrating the try-except block and how to both Pickle and unpickle objects and save them to disk.  Full source code follows the appendix

Appendix

Real Python: “Python Exceptions: An Introduction.” Real Python, Real Python, 23 July 2018, realpython.com/python-exceptions/#the-try-and-except-block-handling-exceptions.
The Python Exception Class Hierarchy:  Airbrake Blog, 3 Nov. 2017, airbrake.io/blog/python-exception-handling/class-hierarchy.
Pickle - Python Object Serialization.: 16.2. Threading - Higher-Level Threading Interface - Python 2.7.15 Documentation, docs.python.org/2/library/pickle.html.

  Source Code

# -------------------------------------------------#
# Title: Exceptions and pickling module
# Dev:   JNordbye
# Date:  December/3/2018
# ChangeLog: (Who, When, What)
#   J Nordbye  12/3/18, Added code to complete assignment 5
#
# -------------------------------------------------#
import pickle #import the pickle Module

#=-------------------   Data -----------------------#
objFileName = "Inventory.dat"
objFileName2 = "Inventory2.dat"
lstInventoryDishes = [("Mug", 24.99, 5), ("Cup", 14.99, 10), ("Saucer", 9.99, 10)]    # list of items in inventory
lstInventoryUtensils =[("Knife", 9.99, 25), ("Fork", 4.99, 20), ("Spoon", 4.99, 10)]  # list of items in inventory


#------------------- Input/Output -------------------#
def listInventory( inInventory): # print out whats in the specifiedInventory
   
for item in inInventory:
       
print(f" {item[2]:2} {item[0]}(s) valued a {item[2]} each")
   
print()  # add a line break in

def saveInventoryWhole(): # save the Dishes inventory as one object
   
try:
       
with open(objFileName, "wb") as fileOut:
           pickle.dump(lstInventoryDishes, fileOut)
   
except Exception as e:
       
print("Error with file")
       
print(e)

def loadInventoryWhole(): # read the Dishes inventory in as one object
   
global lstInventoryDishes
   
try:
       
with open(objFileName, "rb") as fileIn:
            lstInventoryDishes = pickle.load(fileIn)
   
except Exception as e:
       
print("Error with file")
       
print(e)


def saveInventoryIndivd():  # save each part of the Utensil inventory individually
   
try:
        objFile =
open(objFileName2, "wb")
       
for item in lstInventoryUtensils:
            pickle.dump(item, objFile)
        objFile.close()
   
except Exception as e:
       
print("Error with File")
        
print(e)


def loadInventoryIndivd(): # load each item from disk and add to the Utensil Inventory
   
try:
       
with open(objFileName2, "rb") as inFile:
           
while True:
               
try:
                    item = pickle.load(inFile)
                    lstInventoryUtensils.append(item)
               
except EOFError: # error check for reaching end of file.
                   
break
                except
Exception as e:
                   
print("Error with file")
                   
print(e)
                   
break
    except
Exception as e:
       
print("Error with file")
       
print(e)

#------------------- Processing ---------------------#
saveInventoryWhole()  # save the Dishes inventory
lstInventoryDishes.clear()  # clear out the list
loadInventoryWhole() # load the dishes inventory in from file
print("Dishes Inventory")
listInventory(lstInventoryDishes)
# print out the Dishes list

saveInventoryIndivd() # save utensiles inventory to file
lstInventoryUtensils.clear() # clear the list
loadInventoryIndivd() # load the utensiles inventory in
print("Utensil Inventory")
listInventory(lstInventoryUtensils)


Sunday, November 21, 2010

Powershell commands pt 4

[PS] C:\>get-adsite

Name HubSiteEnabled
---- --------------
Default-First-Site-Name False


[PS] C:\>New-EdgeSubscription -FileName c:\edgesubexport.xml -site "default-first-site-name"

Name Site Domain
---- ---- ------
EdgeServer tailspintoys.inte... tailspintoys.exte...
WARNING: EdgeSync requires that the Hub Transport servers in Active Directory
site default-first-site-name must be able to resolve the IP address for
EdgeServer.tailspintoys.external, and be able to connect to that host on ports
50636.


[PS] C:\>Get-SendConnector

Identity AddressSpaces Enabled
-------- ------------- -------
EdgeSync - Default-First-Site-Name to Internet {smtp:*;100} True
EdgeSync - Inbound to Default-First-Site-Name {smtp:--;100} True


[PS] C:\>Start-EdgeSynchronization


Result : Success
Type : Configuration
Name : CN=EdgeServer,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,C
N=tailspintoys,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=tailspintoys,DC=internal
FailureDetails :
StartUTC : 5/28/2010 4:23:48 AM
EndUTC : 5/28/2010 4:23:49 AM
Added : 7
Deleted : 1
Updated : 0
Scanned : 345
TargetScanned : 339

Result : Success
Type : Recipients
Name : CN=EdgeServer,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,C
N=tailspintoys,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=tailspintoys,DC=internal
FailureDetails :
StartUTC : 5/28/2010 4:23:48 AM
EndUTC : 5/28/2010 4:23:49 AM
Added : 33
Deleted : 0
Updated : 0
Scanned : 33
TargetScanned : 0



[PS] C:\>Test-EdgeSynchronization


Name : EdgeServer
LeaseHolder : GLASGOW
LeaseType : Option
ConnectionResult : Succeeded
FailureDetail :
LeaseExpiry : 5/27/2010 10:23:49 PM
LastSynchronized : 5/27/2010 9:23:49 PM
CredentialStatus : Synchronized
TransportServerStatus : Synchronized
TransportConfigStatus : Synchronized
AcceptedDomainStatus : Synchronized
SendConnectorStatus : Synchronized
MessageClassificationStatus : Synchronized
RecipientStatus : Synchronized
CredentialRecords : Number of credentials 3

[PS] C:\>Test-EdgeSynchronization -verify "text@tailspintoys.internal"


Name : EdgeServer
LeaseHolder : GLASGOW
LeaseType : Option
ConnectionResult : Succeeded
FailureDetail :
LeaseExpiry : 5/27/2010 10:23:49 PM
LastSynchronized : 5/27/2010 9:23:49 PM
CredentialStatus : Skipped
TransportServerStatus : Skipped
TransportConfigStatus : Skipped
AcceptedDomainStatus : Skipped
SendConnectorStatus : Skipped
MessageClassificationStatus : Skipped
RecipientStatus : Synchronized
CredentialRecords : Number of credentials 3

Powershell commands pt 3

Chapter 5 Moving users and implemementing bulk management

Set access rights on mailboxes

[PS] C:\>Get-Mailbox | Add-MailboxPermission -user kima -accessrights fullaccess

Creating a template

[PS] C:\>new-mailbox _Template -UserPrincipalName _Template@tailspintoys.external -database "first storage group\db1"
-OrganizationalUnit Users -ResetPasswordOnNextLogon $true

cmdlet New-Mailbox at command pipeline position 1
Supply values for the following parameters:
Password: *********

Name Alias ServerName ProhibitSendQuota
---- ----- ---------- ---------------
_Template _Template glasgow unlimited


Creating new users and mailboxes from a CSV using a Template

[PS] C:\>$template = Get-Mailbox _Template
[PS] C:\>$TempPassword = ConvertTo-SecureString Password1 -AsPlainText -Force

[PS] C:\>Import-Csv c:\newusers.csv | ForEach-Object -Process { New-Mailbox -name $_.Name
-UserPrincipalName $_.upn -OrganizationalUnit $_.ou -Database "first storage group\db1"
-Password $tempPassword -TemplateInstance $template}

Name Alias ServerName ProhibitSendQuota
---- ----- ---------- ---------------
Angela Barbariol Angela.Barbariol glasgow unlimited
Mark Harrington Mark.Harrington glasgow unlimited
Keith Harris Keith.Harris glasgow unlimited
Tony Allen Tony.Allen glasgow unlimited
Isabel Martins Isabel.Martins glasgow unlimited


Part of the CSV file

name,UPN,ou
Angela Barbariol,Angela.Barbariol@tailspintoys.internal,tailspintoys.internal/users
Mark Harrington, Mark.Harrington@tailspintoys.internal,tailspintoys.internal/users

Create new Mailbox Database and Move users to it

[PS] C:\>New-MailboxDatabase "First Glasgow Mailbox Database" -storagegroup "First storage Group"

Name Server StorageGroup Recovery
---- ------ ------------ --------
First Glasgow Mai... GLASGOW First Storage Group False


[PS] C:\>Mount-Database "First Glasgow Mailbox database"

Summary: 5 item(s). 5 succeeded, 0 failed.
Elapsed time: 00:00:47


Summary: 5 item(s). 5 succeeded, 0 failed.
Elapsed time: 00:00:47


Move one user
'tailspintoys.internal/Users/Keith Harris' | move-mailbox -BadItemLimit '5'
-TargetDatabase 'GLASGOW\First Storage Group\First Glasgow Mailbox Database'

Move all users from one mail database to another

[PS] C:\>Get-Mailbox -Database "first storage group\first glasgow mailbox database" | Move-Mailbox
-TargetDatabase "First storage group\db1"

Setting Mailbox quotas

[PS] C:\>Import-Csv c:\setquotas.csv | ForEach-Object -process { Set-Mailbox $_.identity -ProhibitSendReceiveQuota
$_.recieve -ProhibitSendQuota $_.send -IssueWarningQuota $_.warning }

Setting users departments

[PS] C:\>Import-Csv c:\userdepartment.csv | ForEach-Object -process { Set-user $_.name -Department $_.department }

Powershell command pt 2

Create and mount public folders database

new-publicfolderdatabase -StorageGroup 'GLASGOW\First Storage Group' -Name 'First Glasgow Database' -EdbFilePath 'C:\Program Files\Microsoft\Exchange Server\Mailbox\First Storage Group\First Glasgow Database.edb'


mount-database -Identity 'CN=First Glasgow Database,CN=First Storage Group,CN=InformationStore,CN=GLASGOW,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups,CN=tailspintoys,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=tailspintoys,DC=internal'


Creating new public folders and enable them
[PS] C:\>New-PublicFolder -name management

Name Parent Path
---- -----------
management \


[PS] C:\>New-PublicFolder -name "manage reports" -path \management

Name Parent Path
---- -----------
manage reports \management

[PS] C:\>Enable-MailPublicFolder \management
[PS] C:\>Enable-MailPublicFolder "\management\manage reports"

[PS] C:\>Set-MailPublicFolder \management -EmailAddressPolicyEnabled $false
[PS] C:\>Set-MailPublicFolder "\management\manage reports" -EmailAddressPolicyEnabled $false


[PS] C:\>Set-MailPublicFolder "\management\manage reports" -PrimarySmtpAddress managereport@tailspintoys.internal


[PS] C:\>Set-MailPublicFolder \management -PrimarySmtpAddress management@tailspintoys.internal

[PS] C:\>get-publicfolder

Name Parent Path
---- -----------
IPM_SUBTREE


[PS] C:\>get-publicfolder -recurse

Name Parent Path
---- -----------
IPM_SUBTREE
accounts \
management \
manage reports \management


[PS] C:\>get-publicfolder -recurse format-list name


Name : IPM_SUBTREE

Name : accounts

Name : management

Name : manage reports

[PS] C:\>Disable-MailPublicFolder "\management\manage reports"

Confirm
Are you sure you want to perform this action?
Disabling mail public folder "\management\manage reports".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
[PS] C:\>Remove-PublicFolder "\management\manage reports"

Confirm
Are you sure you want to perform this action?
Removing public folder "\management\manage reports".
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
[PS] C:\>

Powershell commands pt 1

Since quite a few of the examples in the Microsoft 70-236 book have typo's, I'm posting the ones I have used. Some include the output


new-AcceptedDomain -Name 'Tailspin Toys .com' -DomainName 'tailspintoys.com'
-DomainType 'Authoritative'


enable-OutlookAnywhere -Server 'GLASGOW'
-externalHostname 'outlkany.tailspintoys.com'
-DefaultAuthenticationMethod 'Basic' -SSLOffloading $false


Create new storage group

new-StorageGroup -Server 'GLASGOW' -Name 'second storage group'
-LogFolderPath 'C:\Program Files\Microsoft\Exchange Server\Mailbox\second storage group' -SystemFolderPath 'C:\Program Files\Microsoft\Exchange Server\Mailbox\second storage group'


Create a mailbox database and mount it:

new-mailboxdatabase -StorageGroup 'GLASGOW\second storage group' -Name 'Second Mailbox database' -EdbFilePath 'C:\Program Files\Microsoft\Exchange Server\Mailbox\second storage group\Second Mailbox database.edb'


mount-database -Identity 'CN=Second Mailbox database,CN=second storage group ,CN=InformationStore, CN=GLASGOW,CN=Servers,CN=Exchange Administrative Group (FYDIBOHF23SPDLT),CN=Administrative Groups ,CN=tailspintoys,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=tailspintoys,DC=internal'

New mailbox enable user

[PS] C:\>$password = read-host "Enter Password" -AsSecureString
Enter Password: *********

[PS] C:\>new-mailbox -UserPrincipalName annie.hall@tailspintoys.internal
-Database "first storage group\db1" -name annieh -organizationalunit users
-displayname "Annie Hall" -password $password
-ResetPasswordOnNextLogon $false

Name Alias ServerName ProhibitSendQuota
---- ----- ---------- ---------------
annieh annie.hall glasgow unlimited


Below since no user password is supplied you will be asked for one

New-Mailbox -Name 'Don Hall' -Alias 'donh'
-OrganizationalUnit 'tailspintoys.internal/Users'
-UserPrincipalName 'donh@tailspintoys.internal' -SamAccountName 'donh'
-FirstName 'Don' -Initials '' -LastName 'Hall'
-Password 'System.Security.SecureString' -ResetPasswordOnNextLogon $true
-Database 'GLASGOW\First Storage Group\DB1'

[PS] C:\>Disable-Mailbox -identity bobbyh

Confirm
Are you sure you want to perform this action?
Disabling Mailbox "bobbyh" will remove the Exchange properties from the Windows
user object and mark the mailbox in the database for removal.
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y
[PS] C:\>
[PS] C:\>Enable-Mailbox -identity bobbyh

cmdlet Enable-Mailbox at command pipeline position 1
Supply values for the following parameters:
Database: db2

Name Alias ServerName ProhibitSendQuo
ta
---- ----- ---------- ---------------
bobbyh bobby.hall glasgow unlimited

[PS] C:\>Remove-Mailbox -identity bobbyh

Confirm
Are you sure you want to perform this action?
Removing the Mailbox "bobbyh" will remove the Windows user object and mark the
mailbox in the database for removal.
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help
(default is "Y"):y


Set-CASMailbox -identity adam@contoso.com -OWATasksEnabled:$true -POPEnabled:$true


New Mail-enabled user



New-MailUser -Name 'Sean p. Alexander' -Alias 'sead.p.alexander'
-OrganizationalUnit 'tailspintoys.internal/Users'
-UserPrincipalName 'sead.p.alexander@tailspintoys.internal'
-SamAccountName 'sead.p.alexander' -FirstName 'Sean' -Initials 'p'
-LastName 'Alexander' -Password 'System.Security.SecureString'
-ResetPasswordOnNextLogon $false -ExternalEmailAddress 'SMTP:sean.p.alexander@adato.com'

also remove-mailuser, disable-mailuser, enable-mailuser to enable you must supple e-mail address
[PS] C:\>Enable-MailUser -identity "Bobby Hall" -ExternalEmailAddress bobbyh@contoso.com

Set-MailUser "bobbyh" -ExternalEmailAddress bobbyh@seaworld.com to configure e-mail properties

New Mail Contact

New-MailContact -ExternalEmailAddress 'SMTP:s.pearson@adatum.com' -Name 'Simon Pearson' -Alias 'SimonPearson' -OrganizationalUnit 'tailspintoys.internal/Users'
-FirstName 'Simon' -Initials ''-LastName 'Pearson'

also enable-mailcontact, disable-mailcontact, and remove-mailcontact
Enable-MailContact -identity "Bobby Hall" -ExternalEmailAddress bobbyh@contoso.com


Create Dynamic Distribution Group

new-DynamicDistributionGroup -Name 'Contoso employees'
-IncludedRecipients 'MailUsers' -ConditionalCompany 'contoso, ltd.'
-OrganizationalUnit 'tailspintoys.internal/Users' -Alias 'Contosoemployees'
-RecipientContainer 'tailspintoys.internal/Users'

Create distribution group

[PS] C:\>New-DistributionGroup -name sales -Type 'distribution' -OrganizationalUnit 'tailspintoys.internal/users' -SamAccountName Sales -alias sales

Name DisplayName GroupType PrimarySmtpAddress
---- ----------- --------- ------------------
sales sales Universal sales@tailspinto...


[PS] C:\>Add-DistributionGroupMember sales -member "annie hall"

[PS] C:\>Get-DistributionGroupMember sales

Name RecipientType
---- -------------
annieh UserMailbox

[PS] C:\>Remove-DistributionGroupMember sales -member annieh

Confirm
Are you sure you want to perform this action?


new-DistributionGroup -Name 'Service Techs' -Type 'Distribution'
-OrganizationalUnit 'tailspintoys.internal/Users' -SamAccountName 'Service Techs'
-Alias 'ServiceTechs'

also have remove-distributiongroup and disable-distributiongroup, enable-distributiongroup

set-distributiongroup to configure e-mail setting for group



Create Room Mailbox

New-Mailbox -Name 'Auditorium' -Alias 'Auditorium'
-OrganizationalUnit 'tailspintoys.internal/Users'
-UserPrincipalName 'Auditorium@tailspintoys.internal' -SamAccountName 'Auditorium'
-FirstName '' -Initials '' -LastName '' -Database 'GLASGOW\First Storage Group\DB1'
-Room -ManagedFolderMailboxPolicy 'deleted folders service'

set-MailBoxCalenderSettings Auditorium -automateProcessing:AutoAccept

set-MailBoxCalenderSettings Auditorium -automateProcessing:none

set-MailboxCalendarSettings -identity Auditorium -ResourceDelegates "annie hall"

Create equipment mailbox

New-Mailbox -Name 'Projector' -Alias 'Projector'
-OrganizationalUnit 'tailspintoys.internal/Users'
-UserPrincipalName 'Projector@tailspintoys.internal' -SamAccountName 'Projector'
-FirstName '' -Initials '' -LastName '' -Database 'GLASGOW\First Storage Group\DB1'
-Equipment

Create a custom property

[PS] C:\>Set-ResourceConfig -DomainController glasgow.tailspintoys.internal -Res
ourcePropertySchema room/NetworkProjector

Monday, August 2, 2010

Tour de Delay

The Tour De France had put a temporary halt to my Exchange studies, no surprise there. :) Also I have been bitten by the programming bug again. Went back and forth between C/C++ and c# but in the end went with C#. I have taken quite a few semesters of C/C++ classes at local community collages and UW extension but went with C# for now as I'm also interested in learning asp.net.