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 1-8 of 8 total  RSS 

A QT 'Hello World' application

- getting started - (Using Ubuntu Linux 7.10)
1) Installed Qt bindings for Ruby

- Running the application
1) From the command line I typed ruby helloworld_qt.rb

#file: helloworld_qt.rb

require 'Qt'

    a = Qt::Application.new( ARGV )

    hello = Qt::PushButton.new( "Hello world!", nil )
    hello.resize( 100, 30 )
 
    Qt::Object::connect( hello, SIGNAL('clicked()'), a, SLOT('quit()') )
 
    a.setMainWidget( hello )
    hello.show()
 
    a.exec()

Source code copied from KDE Tutorial - p1 [kde.org]

A Glade 'Hello World' application

- getting started - (Using Ubuntu Linux 7.10)
1) Installed glade-3,libglade2-ruby
2) Executed glade-3

- Within glade-3 -
1) Selected from the glade-3 top menu View -> Palette appearance -> Text beside icons
2) Created a window (Toplevels)
3) Created a button on the window (Control and Display)
3) With button selected, from the properties panel I selected the Signals tab and chose 'clicked', then for the Handler -> on_button1_clicked and pressed enter.
4) With window select, from the properties panel I select the Signals tab and chose GtkWidget->delete-event, then for the Handler I typed on_quit and pressed enter.

- Generating and editing the code

-- From the command line -
1) Typed ruby-glade-create-template helloworld3.glade > helloworld3.rb

-- From the file helloworld3.rb - (see helloworld3.rb and how it relates to helloworld3.glade)
1) Implemented the initialise window routine
2) Implemented the button event handler

- Running the application
1) From the command line I typed ruby helloworld3.rb
2) stretched the window to a comfortable dimension.
3) clicked the button and observed the Window title change to 'Hello World!'

file: helloworld3.glade
#!/usr/bin/env ruby
#
# This file is generated by ruby-glade-create-template 1.1.4.
#
require 'libglade2'

class Helloworld3Glade
  include GetText

  attr :glade
  
  def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
    bindtextdomain(domain, localedir, nil, "UTF-8")
    @glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}
    @window1 = @glade.get_widget("window1") # hand coded
    @window1.show # hand coded      
  end
  
  def on_button1_clicked(widget)
    #puts "on_button1_clicked() is not implemented yet." # removed this code by hand
    @window1.title = 'Hello World!' # hand coded  
  end
  def on_quit(widget, arg0)
    #puts "on_quit() is not implemented yet." # removed this code by hand
    Gtk.main_quit # hand coded
  end
end

# Main program
if __FILE__ == $0
  # Set values as your own application. 
  PROG_PATH = "helloworld3.glade"
  PROG_NAME = "YOUR_APPLICATION_NAME"
  Helloworld3Glade.new(PROG_PATH, nil, PROG_NAME)
  Gtk.main
end

file: helloworld3.glade
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
<!--Generated with glade3 3.4.0 on Tue Mar 18 17:39:53 2008 -->
<glade-interface>
  <widget class="GtkWindow" id="window1">
    <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
    <signal name="delete_event" handler="on_quit"/>
    <child>
      <widget class="GtkButton" id="button1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="receives_default">True</property>
        <property name="events">GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK</property>
        <property name="label" translatable="yes">button</property>
        <property name="response_id">0</property>
        <signal name="clicked" handler="on_button1_clicked"/>
      </widget>
    </child>
  </widget>
</glade-interface>

bScan - Simple Web Aplications Scanner

// Web application scanner (ex: phpBB, myCMS, myBlog, mySite etc..) - Only in PHP !
// Find XSS, sql injection, remote file inclusion

#####################################################################################
#	Black_H  / Nooz -- 30:01:07 
#	Bl4ck.H<>gmail<>com
#

class BScan

#####################################################################################
#	Regex
#

@@space    = '([[:space:]]*)'

@@userdat  = '('
@@userdat += '(\$_SERVER\[([\'\"]*)HTTP_)|'
@@userdat += '(\$_GET)|'
@@userdat += '(\$_POST)|'
@@userdat += '(\$_COOKIE)|'
@@userdat += '(\$_REQUEST)|'
@@userdat += '(\$_FILES)|'
@@userdat += '(\$_ENV)|'
@@userdat += '(\$_HTTP_COOKIE_VARS)|'
@@userdat += '(\$_HTTP_ENV_VARS)|'
@@userdat += '(\$_HTTP_GET_VARS)|'
@@userdat += '(\$_HTTP_POST_FILES)|'
@@userdat += '(\$_HTTP_POST_VARS)|'
@@userdat += '(\$_HTTP_SERVER_VARS\[([\'\"]*)HTTP_)'
@@userdat += ')'

@@regex = Hash.new
@@regex = 
	{'TYPE' => 'vars overwrite','LEVEL' => '2','REGEX' => /extract#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'vars overwrite','LEVEL' => '2','REGEX' => /import_request_variables#{@@space}\((.*)\)/i},
	{'TYPE' => 'fopen vuln','LEVEL' => '3','REGEX' => /fopen#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'copy vuln','LEVEL' => '3','REGEX' => /copy#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'fwrite vuln','LEVEL' => '3','REGEX' => /fwrite#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'sql injection','LEVEL' => '2','REGEX' => /(mysql_query|mssql_query|mysqli_query)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'crlf injection','LEVEL' => '1','REGEX' => /mail#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'cross site scripting','LEVEL' => '1','REGEX' => /\<\?\=#{@@space}(.*)#{@@userdat}/i},
	{'TYPE' => 'cross site scripting','LEVEL' => '1','REGEX' => /(print|echo|print_r|var_dump)#{@@space}(|\(|\")(.*)#{@@userdat}/i},
	{'TYPE' => 'php code execution','LEVEL' => '3','REGEX' => /eval#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'php code execution','LEVEL' => '3','REGEX' => /file_put_contents#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'variable attribution', 'LEVEL' => '2','REGEX' => /(.*)\$#{@@userdat}(.*)/i},
	{'TYPE' => 'chmod affectation','LEVEL' => '1','REGEX' => /chmod#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'file disclosure','LEVEL' => '2','REGEX' => /(readfile|file_get_contents|file)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'file disclosure','LEVEL' => '2','REGEX' => /(show_source|highlight_file)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'bzopen vuln','LEVEL' => '2','REGEX' => /bzopen#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'file deletion','LEVEL' => '2','REGEX' => /(rmdir|unlink|delete)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'command execution','LEVEL' => '3','REGEX' => /(exec|system|passthru|shell_exec|proc_open|pcntl_exec)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'buffer overflow','LEVEL' => '3','REGEX' => /(confirm_phpdoc_compiled|mssql_pconnect|mssql_connect|crack_opendict|snmpget|ibase_connect)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'ip falsification','LEVEL' => '1','REGEX' => /(.*)(HTTP_CLIENT_IP|HTTP_X_FORWARDED_FOR|HTTP_PC_REMOTE_ADDR)(.*)/i},
	{'TYPE' => 'putenv vuln','LEVEL' => '2','REGEX' => /putenv#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'full path disclosure','LEVEL' => '1','REGEX' => /(htmlentities|htmlspecialchars)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'magic_quotes_gpc bypass','LEVEL' => '1','REGEX' => /(stripslashes|urldecode)#{@@space}\((.*)#{@@userdat}(.*)\)/i},
	{'TYPE' => 'file inclusion','LEVEL' => '3','REGEX' => /(include|include_once|require|require_once)#{@@space}(|\(|\")(.*)#{@@userdat}/i}

#####################################################################################
#	Main
#

  def initialize()

	################
	#	Usage

if (ARGV.length < 4)
puts  '
 ---------------------------------------------------------------------
|             Credits: Black_H <bl4ck.h@gmail.com>                    |
|                 URL: Lemon-Inside.sup.fr                            |
|                Note: Premier code Ruby                              |
 ---------------------------------------------------------------------

 ---------------------------------------------------------------------
|   Usage:  scan.rb -d <Dossier> -i <Save.html>                       |
|   Ex:  scan.rb -d ./ -i output.html                                 |
 ---------------------------------------------------------------------		
 '
 end
 
	################
	#	Options & Vars
	
	@@scan_alldir =  self.options('d')
	@@out_file =  self.options('i')
	
	@@ban = [".", "..", "scan.rb", @@out_file.to_s]

	@@scan_buffer = Array.new
	
	################
	#	Options Error ?
	
	if (@@scan_alldir != false and @@scan_alldir.empty? == false)
	self.dscan(@@scan_alldir)
	self.output(@@scan_buffer)
	@@scan_buffer = ''
	end


	

  end

#####################################################################################
#	Dir Scan 
#
  
  def dscan(dir)
      
	d = Dir.open(dir.to_s)
	d = d.sort - @@ban
	
      d.each { |fichier|

      case File.ftype(dir+fichier)
        when "directory"
          self.dscan(dir + fichier + "/")
        when "file"
		  puts  'Scan => ' + dir + fichier 
          self.fscan(dir + fichier)
      end

	  }
  end

#####################################################################################
#	File Scan 
#
  
  def fscan(file)

	fichier = File.readlines(file)
	i = 1

	fichier.each { |line|
						
		@@regex.each  { |info|
			
			test = (line  =~ info['REGEX']) 
		
				if (test) 
			
				@@scan_buffer += ['FILE' => file, 'LINE' => i.to_s, 'MATCH' => line, 'LEVEL' => info['LEVEL'], 'TYPE' => info['TYPE']]
				#	5 , 1 , 3 , 4 , 2
				next @@scan_buffer
				end
		}

	i += 1
  	} 
	
  end

#####################################################################################
#	Output buffer
#
  
  def output(buffer)
  
	@html_hmodel = '<html>'
	@html_hmodel += '<style type="text/css">'
	@html_hmodel += '<!--'
	@html_hmodel += '.level0 {background-color: #CCCCCC;}'
	@html_hmodel += '.level1 {background-color: #33FF66;}'
	@html_hmodel += '.level2 {background-color: #FFFF33;}'
	@html_hmodel += '.level3 {background-color: #FF0000;}'
	@html_hmodel += '--></style><body><h1>BScan v1.0</h1><pre>'

	code = @html_hmodel
	
	buffer.each { |infos|
	
	keys = infos.keys
	code += "<span class='level" + infos["LEVEL"] + "'>" + keys[1].to_s + ' : ' + infos["TYPE"] + '</span><br />'
	code += "<span class='" + infos["LEVEL"] + "'>" + keys[3].to_s + ' : ' + infos["LEVEL"] + '</span><br />'
	code += "<span class='" + infos["LEVEL"] + "'>" + keys[4].to_s + ' : ' + infos["FILE"] + '</span><br />'
	code += "<span class='" + infos["LEVEL"] + "'>" + keys[0].to_s + ' : ' + infos["LINE"] + '</span><br />'
	code += "<span class='" + infos["LEVEL"] + "'>" + keys[2].to_s + ' : ' + infos["MATCH"] + '</span><br />'
	

	}
		code += "</pre></body></html>"
		fhtml = File.open(@@out_file.to_s, "w")
		fhtml.write code
		code = ''

	
  end
#####################################################################################
#	Parse & Get Options
#
 
  def options(param)
  
	i = 0
		ARGV.each  { |valeur|
		
    		if (valeur == '-' + param.to_s)
				return ARGV[i+1]
			elseif (valeur != '-' + param.to_s)
				return false
			end
		i += 1
		}
		
	end
  
end

scan = BScan.new

Toggle Text on Button (Single thread application)

// description of your code here

 public partial class Form1 : Form
    {
        int iBtn = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ++iBtn;

            if (iBtn == 3)
            {
                iBtn = 0;
            }

            switch (iBtn)
            {
                case 0: button1.Text = "default";
                    break;
                case 1: button1.Text = "Love";
                    break;
                case 2: button1.Text = "Hate";
                    break;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Text = "default";
        }
    }

No duplicate forms in MDI Parent

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

            //"Display" is the form name
            foreach (Form childForm in this.MdiChildren)
            {
                if (childForm.GetType() == typeof(Display))
                {
                    childForm.Focus();
                    return;
                }
            }
            Display frmDisplay = new Display();
            frmDisplay.MdiParent = this;
            frmDisplay.Show();

Reading Web.config / App.config settings

// VB.NET 2.0

#If DEBUG Then
    Private Shared _strConnectionString As String = My.Settings.Item("ConnStringDebug")
#Else
    Private shared _strConnectionString As String = My.Settings.Item("ConnString")
#End If


// Web.Config/App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

	<appSettings>
		<add key="ConnStringDebug" value="Data Source=time01;Initial Catalog=CWBIOSVRdave;UID=sa; PWD=Clockwatch" />
		<add key="ConnString" value="Data Source=time01;Initial Catalog=CWBIOSVRdave;UID=sa; PWD=Clockwatch"/>
	</appSettings>
</configuration>

Persisting Application data using Hashtable and IsolatedStorage

// nice way to store application data and settings
// copied from: http://www.dotnetspider.com/kb/Article344.aspx

using System;
using System.Collections;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace CustomStorage
{
    [Serializable]
    public class ApplicationStorage : Hashtable
    {
        // File name. Let us use the entry assembly name with .dat as the extension.
        private string settingsFileName = 
                        System.Reflection.Assembly.GetEntryAssembly().GetName().Name + ".dat";
    
        // The default constructor.
        public ApplicationStorage()
        {
            LoadData();
        }
        
        // This constructor is required for deserializing our class from persistent storage.
        protected ApplicationStorage (SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
        
        private void LoadData()
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
                        | IsolatedStorageScope.Assembly, null, null );
            if ( isoStore.GetFileNames( settingsFileName ).Length == 0 )
            {
                // File not exists. Let us NOT try to DeSerialize it.
                return;
            }
            
            // Read the stream from Isolated Storage.
            Stream stream = new IsolatedStorageFileStream( settingsFileName, 
                        FileMode.OpenOrCreate, isoStore );
            if ( stream != null )
            {
                try
                {
                    // DeSerialize the Hashtable from stream.
                    IFormatter formatter = new BinaryFormatter();
                    Hashtable appData = ( Hashtable ) formatter.Deserialize(stream);
                    
                    // Enumerate through the collection and load our base Hashtable.
                    IDictionaryEnumerator enumerator = appData.GetEnumerator();
                    while ( enumerator.MoveNext() )
                    {
                        this[enumerator.Key] = enumerator.Value;
                    }
                }
                finally
                {
                    // We are done with it.
                    stream.Close();
                }
            }
        }
        
        public void ReLoad()
        {
            LoadData();
        }
        
        // Saves the configuration data to the persistent storage.
        public void Save()
        {
            // Open the stream from the IsolatedStorage.
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User 
                        | IsolatedStorageScope.Assembly, null, null );
            Stream stream = new IsolatedStorageFileStream( settingsFileName, 
                        FileMode.Create, isoStore );
        
            if ( stream != null )
            {
                try
                {
                    // Serialize the Hashtable into the IsolatedStorage.
                    IFormatter formatter = new BinaryFormatter();
                    formatter.Serialize( stream, (Hashtable)this );
                }
                finally
                {
                    stream.Close();
                }
            }
        }
    }
}


//sample usage

CustomStorage.ApplicationStorage storage = new CustomStorage.ApplicationStorage();

storage["name"] = "john";
storage["age"] = 23;
storage["address"] = "#10, Vasant Nagar";

storage.Save();

string name = storage["name"].ToString();
int age = int.parse(storage["age"].ToString());

Switch application to foreground in pys60

Taken from the 'appswitch' module here
import appswitch
print appswitch.switch_to_fg(u"Menu")

Updated (19 Oct 05)
==================
Now it can
- listing running applications
- switching them to foreground/background
- closing/killing apps
# listing
apps = appswitch.application_list(True) # true = include all
                                       # false = no hidden apps 
print apps

# to background and closing
print appswitch.switch_to_bg(u"TODO")
print appswitch.end_app(u"TODO")

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS