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

« Newer Snippets
Older Snippets »
Showing 11-20 of 62 total

Windows XP System Variables

// Windows XP Default System Variables

   1  
   2  %SystemDrive%  		C:
   3  
   4  %SystemRoot% 		C:\WINNT, C:\WINDOWS
   5  
   6  %SystemDirectory% 	C:\WINNT\System32, C:\WINDOWS\System32
   7  
   8  %WinDir% 		C:\WINNT, C:\WINDOWS, C:\WINNT\Program Files
   9  
  10  %ComSpec% 		C:\WINNT\system32\cmd.exe
  11  
  12  %Temp% 			C:\DOCUME~1\Usr\LOCALS~1\Temp from C:\Documents and Settings\Usr\Local Settings\Temp
  13  
  14  %HOMEDRIVE% 		C: The drive letter associated with the user's home directory
  15  
  16  %HOMEPATH% 		The path to the user's home directory (excluding drive): \Documents and Settings\Guest
  17  
  18  %OS% 			Windows_NT -> The operating system the user is running
  19  
  20  %USERDOMAIN% 		The name of the domain that contains the user's account
  21  
  22  %USERNAME% 		The user's name

flickr to desktop background

// description of your code here

   1  
   2  #!/usr/bin/env ruby
   3  
   4  ########################################
   5  # config
   6  ########################################
   7  
   8  groups = ['trees']
   9  flick_api_key = 'cc0880a9d309466758fecb6557d7040b'
  10  
  11  # proxy just comment out to disable, types: http, sspi
  12  #http_proxy = {:host=> 'name', :port => 80, :type => :sspi}
  13  
  14  
  15  # temp files for imagemagick
  16  p1 = 'c:/tmp/img.jpg'
  17  p2 = 'c:\\tmp\\img.bmp'
  18  
  19  # Imagemagick path
  20  # http://www.imagemagick.org/script/binary-releases.php#windows
  21  # Recommended package: ImageMagick-6.3.5-6-Q8-windows-static.exe
  22  # convert.exe is needed only, so Imagemagick can be uninstalled.
  23  imagick_path = 'convert.exe'
  24  
  25  # images with larger/smaller width will be skipped
  26  skip_small = 1000
  27  skip_big = 2100
  28  
  29  ########################################
  30  # code
  31  ########################################
  32  
  33  require 'Win32API'
  34  require 'net/http'
  35  require 'win32/sspi'
  36  require 'json'
  37  require 'yaml'
  38  require "win32/open3"
  39  require "win32/process"
  40  
  41  def parse_url(url)
  42    m = /(?:.*?\/\/)(.*?)(\/.*)/.match(url)
  43    [ m[1] , m[2] ]
  44  end
  45  
  46  class NetWrap
  47    def initialize(p_type = nil, p_host = nil, p_port = nil)
  48      if !p_type
  49        @conn = Net::HTTP
  50      else
  51        @conn = Net::HTTP.Proxy(p_host, p_port)
  52      end
  53      @p_type = p_type
  54    end
  55    
  56    def download(url)
  57      site, path = parse_url(url)
  58      data = ''
  59      @conn.start(site) do |http|
  60        if @p_type && @p_type == :sspi
  61          resp, data = Win32::SSPI::NegotiateAuth.proxy_auth_get(http, path)
  62        else
  63          resp, data = http.get(path)
  64        end
  65      end
  66      return data
  67    end
  68  end
  69  
  70  class FlickR
  71    def initialize(apikey, netw)
  72      @apikey = apikey
  73      @netw = netw
  74    end
  75    
  76    def request(api_meth,params = {})
  77      url = "http://api.flickr.com/services/rest/?method=#{api_meth}&api_key=#{@apikey}&format=json"
  78      params.each {|key,val| url << "&#{key}=#{val}"}
  79      res = @netw.download(url)
  80      JSON.parse(res['jsonFlickrApi('.size..-(');'.size)])
  81    end
  82    
  83    def group_photos(id)
  84      request('flickr.groups.pools.getPhotos', :group_id => id)['photos']['photo']
  85    end
  86    
  87    def group_lookup(name)
  88      request('flickr.urls.lookupGroup', :url => "http://flickr.com/groups/#{name}/pool/")['group']['id']
  89    end
  90  
  91    def photo_urls(id)
  92      request('flickr.photos.getSizes', :photo_id => id)['sizes']['size']
  93    end
  94    
  95    def photo_best(id, width)
  96      sizes = photo_urls(id).sort {|a,b| a['width'].to_i <=> b['width'].to_i}
  97      return sizes.find {|x| x['width'].to_i > width} || sizes.last()
  98    end
  99  end
 100  
 101  class ImgList
 102    def initialize(cfgname)
 103      @cfg = cfgname
 104      @saw = {}
 105      begin
 106        if f = open(@cfg,'r')
 107          @saw = YAML.load(f)
 108          f.close()
 109          cnt = 0
 110          @saw.each {|key,val| cnt += 1 if val[1]}
 111        end
 112      rescue
 113      end
 114    end
 115    
 116    def save()
 117      if f = open(@cfg,'w+')
 118        f.write(@saw.to_yaml)
 119        f.close()
 120      end
 121    end
 122    
 123    def next()
 124      img = @saw.detect {|x| !x[1]}
 125      return img[0] if img
 126      img
 127    end
 128    
 129    def add(url)
 130      if !@saw.has_key?(url)
 131        @saw[url] = false
 132      end
 133    end
 134    
 135    def mark(url)
 136      @saw[url] = true
 137    end
 138    
 139    def reset()
 140      @saw.each {|key,val| @saw[key] = false}
 141    end
 142  end
 143  
 144  if defined?(http_proxy)
 145    netw = NetWrap.new(http_proxy[:type], http_proxy[:host], http_proxy[:port])
 146  else
 147    netw = NetWrap.new()
 148  end
 149  
 150  scr_w = Win32API.new("user32", "GetSystemMetrics", ['I'] , 'I').call(0)
 151  
 152  il = ImgList.new('wpcache.yaml')
 153  
 154  photo_url = il.next()
 155  
 156  if !photo_url
 157    fr = FlickR.new(flick_api_key, netw)
 158    groups.each do |group|
 159      fr.group_photos(fr.group_lookup(group)).each do |x|
 160        next if !x['ispublic']
 161        photo = fr.photo_best(x['id'],scr_w)
 162        next if skip_small && photo['width'].to_i < skip_small
 163        next if skip_big && photo['width'].to_i > skip_big
 164        url = photo['source']
 165        il.add(url)
 166      end
 167    end  
 168    photo_url = il.next()
 169  end
 170  
 171  if !photo_url
 172    il.reset()
 173    photo_url = il.next()
 174  end
 175  
 176  il.mark(photo_url)
 177  il.save()
 178  
 179  open(p1,'wb+') { |f|  f.write(netw.download(photo_url)) }
 180  
 181  cmdline = "#{imagick_path} -resize #{scr_w} #{p1} bmp3:#{p2}"
 182  Process::waitpid2(Open4::popen4(cmdline)[3])
 183  
 184  Win32API.new("user32", "SystemParametersInfo", ['L','L','P','L'] , 'L').Call(20,0,p2,3)

No duplicate forms in MDI Parent

//This will ensure that no duplicate copies of a child form is created in an //MDI_Parent

   1  
   2              //"Display" is the form name
   3              foreach (Form childForm in this.MdiChildren)
   4              {
   5                  if (childForm.GetType() == typeof(Display))
   6                  {
   7                      childForm.Focus();
   8                      return;
   9                  }
  10              }
  11              Display frmDisplay = new Display();
  12              frmDisplay.MdiParent = this;
  13              frmDisplay.Show();

Automating Outlook with Ruby: Address Books

From the Ruby on Windows blog...
   1  
   2  require 'win32ole'
   3  
   4  outlook = WIN32OLE.new('Outlook.Application')
   5  mapi = outlook.GetNameSpace('MAPI')
   6  
   7  #   Get list of available Address Lists
   8  mapi.Session.AddressLists.each do |list|
   9      puts list.Name
  10  end
  11  
  12  #   Access an Address List:
  13  address_list = mapi.Session.AddressLists('Contacts')
  14  address_list = mapi.Session.AddressLists('Personal Address Book')
  15  address_list = mapi.Session.AddressLists('Global Address List')
  16  
  17  #   Outlook security dialog will prompt to allow access to AddressEntries:
  18  address_entries = address_list.AddressEntries
  19  
  20  #   Iterate over the AddressEntries collection:
  21  address_entries.each do |address_entry|
  22      if address_entry.Name =~ /Sinatra/
  23          puts address_entry.Name, address_entry.Address
  24      end
  25  end
  26  
  27  #   Search for an Address:
  28  address_entry = address_entries.Item("sinatra, frank")
  29  puts address_entry.Name
  30  puts address_entry.Address

Further details can be found here.

Automatically restarting an application in Windows

This script will start a program and automatically relaunch it if it closes. It's a stripped down version of the script in JSI Tip 9635: How can I start an application, and automatically restart it if the user ends it?.

   1  
   2  Set WshShell = CreateObject("WScript.Shell")
   3  Do While True
   4   WshShell.Run """<the path to the executable file>""", 1, True
   5  Loop


The pairs of double quotes inside the quoted string prevent "file not found" errors if the path contains spaces. The Run method is documented here, in case you want to change the window style (the second argument).

Automating Outlook with Ruby: Contacts

From the Ruby on Windows blog...
   1  
   2  require 'win32ole'
   3  
   4  outlook = WIN32OLE.new('Outlook.Application')
   5  mapi = outlook.GetNameSpace('MAPI')
   6  
   7  #   Create a new Contact
   8  contact = outlook.CreateItem(2)
   9      contact.FullName = 'Stan Musial'
  10      contact.BusinessTelephoneNumber = '(314)555-1234'
  11      contact.Email1Address = 'stan_the_man@stlcardinals.com'
  12  contact.Save
  13  
  14  #   Iterate over Contact Items and extract data
  15  contacts = mapi.GetDefaultFolder(10).Items
  16  contacts.each do |contact|
  17      puts contact.FullName
  18      puts contact.Email1Address
  19      puts contact.BusinessTelephoneNumber
  20  end

Further details can be found here.

Launching the default web browser on MS Windows

# This code will launch your default web browser to the URL you provide

   1  
   2  require 'Win32API'
   3  
   4  ShellExecute = Win32API.new('shell32', 'ShellExecute', 'LPPPPI', 'L')
   5  
   6  unless ShellExecute.call(0, 'open', 'http://www.rubyforge.org', 0, 0, 1) > 0
   7     raise "ShellExecute failed"
   8  end

Automating Windows Media Player with Ruby

From the Ruby on Windows blog.

   1  
   2  require 'win32ole'
   3  player = WIN32OLE.new('WMPlayer.OCX')
   4  media_collection = player.mediaCollection
   5  playlists = player.PlaylistCollection
   6  
   7  #   Play a song
   8  player.OpenPlayer('c:\music\van halen\right now.wma')
   9  
  10  #   Select songs from the Media Collection
  11  all_media = media_collection.getAll()
  12  audio_media = media_collection.getByAttribute("MediaType", "Audio")
  13  sinatra_songs = media_collection.getByAuthor("Frank Sinatra")
  14  album = media_collection.getByAlbum('Come Fly with Me')
  15  jazz_tunes = media_collection.getByGenre('Jazz')
  16  songs = media_collection.getByName('Fly Me to the Moon')
  17  
  18  #   Play the first song
  19  first_song = songs.Item(0)
  20  player.OpenPlayer(first_song.sourceURL)
  21  
  22  #   Add a song to the Media Collection
  23  song = media_collection.Add('C:\music\Just in Time.wma')
  24  
  25  #   Remove a song from the Media Collection
  26  songs = media_collection.getByName('Fly Me to the Moon')
  27  media_collection.Remove(songs.Item(0), true)
  28  
  29  #   Select a playlist
  30  all_playlists = playlists.getAll()
  31  split_enz_playlist = playlists.getByName('Split Enz')
  32  
  33  #   Iterate over songs in a playlist
  34  (0..my_playlist.Count - 1).each do |i|
  35      song = my_playlist.Item(i)
  36      puts song.Name
  37  end
  38  
  39  #   Create a new playlist
  40  playlists = player.PlaylistCollection
  41  playlists.newPlaylist('New Playlist')
  42  media_collection.Add('D:\Music\My Playlists\New Playlist.wpl')
  43  
  44  #   Remove a playlist
  45  playlists = player.PlaylistCollection
  46  split_enz_playlist = playlists.getByName('Split Enz').Item(0)
  47  playlists.Remove(split_enz_playlist)
  48  
  49  #   Add a song to a playlist
  50  song = media_collection.getByName('Fly Me to the Moon').Item(0)
  51  playlist = playlists.getByName('Frank & Dino').Item(0)
  52  playlist.appendItem(song)
  53  
  54  #   Remove a song from a playlist
  55  playlist.removeItem(song)
  56  
  57  #   Play a playlist
  58  playlist = playlists.getByName('Frank & Dino').Item(0)
  59  player.OpenPlayer(playlist.sourceURL)


Further details can be found here.

Automating and Managing iTunes with Ruby

From the Ruby on Windows blog.
   1  
   2  #   connect to the iTunes application object
   3  require 'win32ole'
   4  itunes = WIN32OLE.new('iTunes.Application')
   5  
   6  #   place iTunes into MiniPlayer mode
   7  itunes.BrowserWindow.MiniPlayer = true
   8  
   9  #   toggle the play/pause setting
  10  itunes.PlayPause
  11  
  12  #    increase or decrease volume
  13  itunes.SoundVolume = itunes.SoundVolume + 50
  14  itunes.SoundVolume = itunes.SoundVolume - 25
  15  
  16  #   go to previous or next track
  17  itunes.PreviousTrack
  18  itunes.NextTrack
  19  
  20  #   grab the entire library playlist
  21  library = itunes.LibraryPlaylist
  22  tracks = library.Tracks
  23  
  24  #   select and play a song by name
  25  song = tracks.ItemByName('At Long Last Love')
  26  song.Play
  27  
  28  #   search for tracks
  29  artist_tracks = library.Search('Sinatra', 2)
  30  album_tracks = library.Search('Come Fly With Me', 3)
  31  title_tracks = library.Search('Fly Me To The Moon', 5)
  32  
  33  #   add all track objects to a ruby array
  34  songs = []
  35  for track in tracks
  36      songs << track
  37  end
  38  
  39  #   sort the songs array
  40  songs = songs.sort_by{|song| [song.Artist, song.Year, song.Album, song.TrackNumber]}
  41  
  42  #   iterate over the songs collection
  43  songs.each do |song|
  44      puts [song.Artist, song.Year, song.Album, song.TrackNumber, song.Name, song.Time].join("\t")
  45  end
  46  
  47  #   create a new playlist and add songs
  48  playlist = itunes.CreatePlaylist("My New Playlist")
  49  song = tracks.ItemByName('At Long Last Love')
  50  playlist.AddTrack(song)
  51  
  52  #   add all playlist objects to a ruby array
  53  playlists = []
  54  itunes.Sources.each do |source|
  55      source.PlayLists.each do |playlist|
  56          playlists << playlist
  57      end
  58  end
  59  
  60  #   iterate over the collection of playlist objects
  61  for playlist in playlists do
  62      puts playlist.Name
  63  end
  64  
  65  #   select a playlist by name, and play the first track
  66  playlist = itunes.Sources.ItemByName('Library').Playlists.ItemByName('All Sinatra')
  67  playlist.PlayFirstTrack
  68  
  69  #   exit the iTunes application
  70  itunes.Quit

Further details can be found here.

Automating Outlook with Ruby: Tasks

From the Ruby on Windows blog...
   1  
   2  require 'win32ole'
   3  
   4  outlook = WIN32OLE.new('Outlook.Application')
   5  
   6  #   creating a new task
   7  task = outlook.CreateItem(3)
   8  task.Subject = 'Order Yankees Playoff Tickets'
   9  task.Body = 'Order first-round playoff tickets...'
  10  task.ReminderSet = true
  11  task.ReminderTime = '07/19/2007 9:00 AM'
  12  task.DueDate = '07/20/2007'
  13  task.ReminderPlaySound = true
  14  task.ReminderSoundFile = 'C:\Windows\Media\Ding.wav'
  15  task.Save
  16  
  17  #   getting tasks data
  18  mapi = outlook.GetNameSpace('MAPI')
  19  tasks = mapi.GetDefaultFolder(13)
  20  for task in tasks.Items.Restrict("[Status] = 'Waiting on someone else'")
  21      puts task.Subject
  22      puts task.DueDate
  23      puts task.PercentComplete
  24      puts task.Status
  25      puts task.Importance
  26      puts task.LastModificationTime
  27  end
  28  
  29  #   search for and delete tasks
  30  for task in tasks.Items.Restrict("[Subject] = 'Order Yankees Playoff Tickets'")
  31      task.Delete
  32  end

Further details can be found here.

« Newer Snippets
Older Snippets »
Showing 11-20 of 62 total