Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

David Mullet http://rubyonwindows.blogspot.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS 

Creating Charts in Excel

From the Ruby on Windows blog...

#   creating a chart in excel
require 'win32ole'

#   set some parameter variables
xlColumns = 2
xlColumnClustered = 51
xlWhite = 2
xlRed = 3
xlBlue = 5
xlGray = 15

#   connect to a running instance of excel
xl = WIN32OLE.connect('Excel.Application')
wb = xl.Workbooks('mlb_stats.xls')

#   delete "MLB Scoring" chart if it already exists
xl.DisplayAlerts = false
    begin
        wb.Charts("MLB Scoring").Delete
    rescue
    end
xl.DisplayAlerts = true

#   create a new chart
mychart = wb.Charts.Add
mychart.Name = "MLB Scoring"
mychart.SetSourceData wb.Worksheets("Runs Scored and Allowed").Range("A1:C15"), xlColumns
mychart.ChartType = xlColumnClustered

#   set series names in the legend
mychart.SeriesCollection(1).Name = "Runs Scored"
mychart.SeriesCollection(2).Name = "Runs Allowed  "

#   set colors
mychart.SeriesCollection(1).Interior.ColorIndex = xlBlue
mychart.SeriesCollection(2).Interior.ColorIndex = xlRed
mychart.ChartArea.Interior.ColorIndex = xlWhite
mychart.ChartArea.Border.ColorIndex = xlBlue
mychart.PlotArea.Interior.ColorIndex = xlGray
mychart.PlotArea.Border.ColorIndex = xlWhite

#   set chart title properties
mychart.HasTitle = true
mychart.ChartTitle.Characters.Text = "American League - Runs Scored vs. Runs Allowed"
mychart.ChartTitle.Font.Name = 'Verdana'
mychart.ChartTitle.Font.Size = 16
mychart.ChartTitle.Font.Bold = true


Further details and discussion here.

Basic wxRuby Form Example

From the Ruby on Windows blog...


require 'wx'
include Wx

class MyFrame < Frame
    def initialize()
        super(nil, -1, 'My Frame Title')
        # First create the controls
        @my_panel = Panel.new(self)
        @my_label = StaticText.new(@my_panel, -1, 'My Label Text', 
            DEFAULT_POSITION, DEFAULT_SIZE, ALIGN_CENTER)
        @my_textbox = TextCtrl.new(@my_panel, -1, 'Default Textbox Value')
        @my_combo = ComboBox.new(@my_panel, -1, 'Default Combo Text', 
            DEFAULT_POSITION, DEFAULT_SIZE, ['Item 1', 'Item 2', 'Item 3'])
        @my_button = Button.new(@my_panel, -1, 'My Button Text')
        # Bind controls to functions
        evt_button(@my_button.get_id()) { |event| my_button_click(event)}
        # Now do the layout
        @my_panel_sizer = BoxSizer.new(VERTICAL)
        @my_panel.set_sizer(@my_panel_sizer)
        @my_panel_sizer.add(@my_label, 0, GROW|ALL, 2)
        @my_panel_sizer.add(@my_textbox, 0, GROW|ALL, 2)
        @my_panel_sizer.add(@my_combo, 0, GROW|ALL, 2)
        @my_panel_sizer.add(@my_button, 0, GROW|ALL, 2)        
        show()
    end
    
    def my_button_click(event)
        # Your code here
    end
end

class MyApp < App
    def on_init
        MyFrame.new
    end
end

MyApp.new.main_loop()


Further details and discussion here.

Automating Outlook with Ruby: Inbox & Messages

From the Ruby on Windows blog.

require 'win32ole'
outlook = WIN32OLE.new('Outlook.Application')
mapi = outlook.GetNameSpace('MAPI')

# Get a reference to the Inbox or other folder:
inbox = mapi.GetDefaultFolder(6)
personal_folders = mapi.Folders.Item('Personal Folders')
baseball_folder = personal_folders.Folders.Item('Baseball')

# Get a count of a folder's unread items:
puts "#{inbox.UnreadItemCount} unread messages"

# Iterate over messages in a folder:
inbox.Items.each do |message|
    # Your code here...
end

# Retrieve a single message:
first_message = inbox.Items(1)

# Delete a message:
message.Delete

# Move a message to another folder:
baseball_folder = personal_folders.Folders.Item('Baseball')
message.Move(baseball_folder)

inbox.Items.Count.downto(1) do |i|
    message = inbox.Items(i)
    if message.Subject =~ /cardinals/i
        message.Move(baseball_folder)
    end
end


Further details and discussion can be found here.

Automating Outlook with Ruby: Address Books

From the Ruby on Windows blog...
require 'win32ole'

outlook = WIN32OLE.new('Outlook.Application')
mapi = outlook.GetNameSpace('MAPI')

#   Get list of available Address Lists
mapi.Session.AddressLists.each do |list|
    puts list.Name
end

#   Access an Address List:
address_list = mapi.Session.AddressLists('Contacts')
address_list = mapi.Session.AddressLists('Personal Address Book')
address_list = mapi.Session.AddressLists('Global Address List')

#   Outlook security dialog will prompt to allow access to AddressEntries:
address_entries = address_list.AddressEntries

#   Iterate over the AddressEntries collection:
address_entries.each do |address_entry|
    if address_entry.Name =~ /Sinatra/
        puts address_entry.Name, address_entry.Address
    end
end

#   Search for an Address:
address_entry = address_entries.Item("sinatra, frank")
puts address_entry.Name
puts address_entry.Address

Further details can be found here.

Automating Outlook with Ruby: Contacts

From the Ruby on Windows blog...
require 'win32ole'

outlook = WIN32OLE.new('Outlook.Application')
mapi = outlook.GetNameSpace('MAPI')

#   Create a new Contact
contact = outlook.CreateItem(2)
    contact.FullName = 'Stan Musial'
    contact.BusinessTelephoneNumber = '(314)555-1234'
    contact.Email1Address = 'stan_the_man@stlcardinals.com'
contact.Save

#   Iterate over Contact Items and extract data
contacts = mapi.GetDefaultFolder(10).Items
contacts.each do |contact|
    puts contact.FullName
    puts contact.Email1Address
    puts contact.BusinessTelephoneNumber
end

Further details can be found here.

Automating Windows Media Player with Ruby

From the Ruby on Windows blog.

require 'win32ole'
player = WIN32OLE.new('WMPlayer.OCX')
media_collection = player.mediaCollection
playlists = player.PlaylistCollection

#   Play a song
player.OpenPlayer('c:\music\van halen\right now.wma')

#   Select songs from the Media Collection
all_media = media_collection.getAll()
audio_media = media_collection.getByAttribute("MediaType", "Audio")
sinatra_songs = media_collection.getByAuthor("Frank Sinatra")
album = media_collection.getByAlbum('Come Fly with Me')
jazz_tunes = media_collection.getByGenre('Jazz')
songs = media_collection.getByName('Fly Me to the Moon')

#   Play the first song
first_song = songs.Item(0)
player.OpenPlayer(first_song.sourceURL)

#   Add a song to the Media Collection
song = media_collection.Add('C:\music\Just in Time.wma')

#   Remove a song from the Media Collection
songs = media_collection.getByName('Fly Me to the Moon')
media_collection.Remove(songs.Item(0), true)

#   Select a playlist
all_playlists = playlists.getAll()
split_enz_playlist = playlists.getByName('Split Enz')

#   Iterate over songs in a playlist
(0..my_playlist.Count - 1).each do |i|
    song = my_playlist.Item(i)
    puts song.Name
end

#   Create a new playlist
playlists = player.PlaylistCollection
playlists.newPlaylist('New Playlist')
media_collection.Add('D:\Music\My Playlists\New Playlist.wpl')

#   Remove a playlist
playlists = player.PlaylistCollection
split_enz_playlist = playlists.getByName('Split Enz').Item(0)
playlists.Remove(split_enz_playlist)

#   Add a song to a playlist
song = media_collection.getByName('Fly Me to the Moon').Item(0)
playlist = playlists.getByName('Frank & Dino').Item(0)
playlist.appendItem(song)

#   Remove a song from a playlist
playlist.removeItem(song)

#   Play a playlist
playlist = playlists.getByName('Frank & Dino').Item(0)
player.OpenPlayer(playlist.sourceURL)


Further details can be found here.

Automating and Managing iTunes with Ruby

From the Ruby on Windows blog.
#   connect to the iTunes application object
require 'win32ole'
itunes = WIN32OLE.new('iTunes.Application')

#   place iTunes into MiniPlayer mode
itunes.BrowserWindow.MiniPlayer = true

#   toggle the play/pause setting
itunes.PlayPause

#    increase or decrease volume
itunes.SoundVolume = itunes.SoundVolume + 50
itunes.SoundVolume = itunes.SoundVolume - 25

#   go to previous or next track
itunes.PreviousTrack
itunes.NextTrack

#   grab the entire library playlist
library = itunes.LibraryPlaylist
tracks = library.Tracks

#   select and play a song by name
song = tracks.ItemByName('At Long Last Love')
song.Play

#   search for tracks
artist_tracks = library.Search('Sinatra', 2)
album_tracks = library.Search('Come Fly With Me', 3)
title_tracks = library.Search('Fly Me To The Moon', 5)

#   add all track objects to a ruby array
songs = []
for track in tracks
    songs << track
end

#   sort the songs array
songs = songs.sort_by{|song| [song.Artist, song.Year, song.Album, song.TrackNumber]}

#   iterate over the songs collection
songs.each do |song|
    puts [song.Artist, song.Year, song.Album, song.TrackNumber, song.Name, song.Time].join("\t")
end

#   create a new playlist and add songs
playlist = itunes.CreatePlaylist("My New Playlist")
song = tracks.ItemByName('At Long Last Love')
playlist.AddTrack(song)

#   add all playlist objects to a ruby array
playlists = []
itunes.Sources.each do |source|
    source.PlayLists.each do |playlist|
        playlists << playlist
    end
end

#   iterate over the collection of playlist objects
for playlist in playlists do
    puts playlist.Name
end

#   select a playlist by name, and play the first track
playlist = itunes.Sources.ItemByName('Library').Playlists.ItemByName('All Sinatra')
playlist.PlayFirstTrack

#   exit the iTunes application
itunes.Quit

Further details can be found here.

Automating Outlook with Ruby: Tasks

From the Ruby on Windows blog...
require 'win32ole'

outlook = WIN32OLE.new('Outlook.Application')

#   creating a new task
task = outlook.CreateItem(3)
task.Subject = 'Order Yankees Playoff Tickets'
task.Body = 'Order first-round playoff tickets...'
task.ReminderSet = true
task.ReminderTime = '07/19/2007 9:00 AM'
task.DueDate = '07/20/2007'
task.ReminderPlaySound = true
task.ReminderSoundFile = 'C:\Windows\Media\Ding.wav'
task.Save

#   getting tasks data
mapi = outlook.GetNameSpace('MAPI')
tasks = mapi.GetDefaultFolder(13)
for task in tasks.Items.Restrict("[Status] = 'Waiting on someone else'")
    puts task.Subject
    puts task.DueDate
    puts task.PercentComplete
    puts task.Status
    puts task.Importance
    puts task.LastModificationTime
end

#   search for and delete tasks
for task in tasks.Items.Restrict("[Subject] = 'Order Yankees Playoff Tickets'")
    task.Delete
end

Further details can be found here.

Automating Outlook with Ruby: Calendar Appointments

From the Ruby on Windows blog.

Use Ruby to extract appointments data from the Microsoft Outlook Calendar, delete an appointment, and create a new appointment.
require 'win32ole'

outlook = WIN32OLE.new('Outlook.Application')
mapi = outlook.GetNameSpace('MAPI')
calendar = mapi.GetDefaultFolder(9)

#   reading calendar data
data = []
calendar.Items.each do |appointment|
    rec = []
    rec << appointment.Subject
    rec << appointment.Location
    rec << appointment.Start
    rec << appointment.Duration
    rec << appointment.End
    rec << appointment.Body
    data << rec
end

#   deleting an appointment
calendar.Items.each do |appointment|
    if appointment.Subject == 'Punch Bud Selig in the Nose'
        appointment.Delete
    end
end

#   creating a new appointment
appointment = outlook.CreateItem(1)
appointment.Start = '7/29/2007 11:00 AM'
appointment.Duration = 300
appointment.Subject = 'Baseball Hall of Fame Induction'
appointment.Body = 'Tony Gwynn and Cal Ripken Jr.'
appointment.Location = 'Cooperstown, NY'
appointment.ReminderMinutesBeforeStart = 15
appointment.ReminderSet = true
appointment.Save

Further details and discussion can be found here.

Using Ruby & WMI to Get Win32 Process Information

From the Ruby on Windows blog...

Use Windows Management Instrumentation (WMI) to get information about the Win32 processes being run.
require 'win32ole'

wmi = WIN32OLE.connect("winmgmts://")

processes = wmi.ExecQuery("select * from win32_process")

for process in processes do
    puts "Name: #{process.Name}"
    puts "CommandLine: #{process.CommandLine}"
    puts "CreationDate: #{process.CreationDate}"
    puts "WorkingSetSize: #{process.WorkingSetSize}"
    puts
end

Further details and discussion here.


« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS