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 

GET stream from the web using python

GETs files from a remote webserver. I'm using it for streaming
def get(host,port,url):
    h = httplib.HTTP(host, port)
    h.putrequest('GET', url)
    h.putheader('Host', host)
    h.putheader('User-agent', 'python-httplib')
    h.endheaders()

    (returncode, returnmsg, headers) = h.getreply()
    if returncode != 200:
        print returncode, returnmsg
        sys.exit()

    f = h.getfile()
    return f.read()

Get the username of the logged on user on remote machine

// description of your code here
Cheats a little by getting the owner of explorer.exe to derive the logged in user. Add reference to System.Management and I think DirectoryServices
Imports System.Management
Imports System.DirectoryServices
Imports Microsoft.Win32
Imports System.Runtime.InteropServices
Module Module1
    Dim objManagementClass As ManagementClass
    Dim objManagementScope As ManagementScope
    Dim objManagementBaseObject As ManagementBaseObject
    Sub Main()

        Dim WMIScope As Management.ManagementScope
        Dim WMIConnectionOptions As New Management.ConnectionOptions
        Dim strRootDomain As String
        Dim objRootLDAP As DirectoryEntry
        Dim query As ManagementObjectSearcher
        Dim queryCollection As ManagementObjectCollection
        Dim oq As New System.Management.ObjectQuery
        Dim mo As New ManagementObject
        Dim UserDomain As String
        Dim UserID As String
        Dim StrLoggedUserSID() As Byte

        Dim Strcomputer As String = My.Application.CommandLineArgs.Item(0)
        'Console.WriteLine(Strcomputer)

        With WMIConnectionOptions
            .Impersonation = System.Management.ImpersonationLevel.Impersonate
            .Authentication = System.Management.AuthenticationLevel.Packet

        End With

        WMIScope = New Management.ManagementScope("\\" & _
        strcomputer & "\root\cimv2", WMIConnectionOptions)

        objRootLDAP = New DirectoryEntry("LDAP://RootDSE")
        strRootDomain = objRootLDAP.Properties.Item("rootDomainNamingContext").Value.ToString

        oq = New System.Management.ObjectQuery("SELECT * from Win32_process Where Name='explorer.exe' and SessionID=0")
        query = New ManagementObjectSearcher(WMIScope, oq)
        queryCollection = query.Get()

        If queryCollection.Count = 0 Then
            Console.WriteLine("No user logged on")
            Exit Sub
        Else

            Dim strKeyPath As String = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon"
            objManagementScope = New ManagementScope
            objManagementScope.Path.Server = strcomputer
            objManagementScope.Path.NamespacePath = "root\default"
            objManagementScope.Options.EnablePrivileges = True
            objManagementScope.Options.Impersonation = ImpersonationLevel.Impersonate
            objManagementScope.Connect()

            objManagementClass = New ManagementClass("stdRegProv")
            objManagementClass.Scope = objManagementScope
            objManagementBaseObject = objManagementClass.GetMethodParameters("EnumValues")
            objManagementBaseObject.SetPropertyValue("hDefKey", CType("&H" & Hex(RegistryHive.LocalMachine), Long))
            objManagementBaseObject.SetPropertyValue("sSubKeyName", strKeyPath)

            UserDomain = CStr(GetRegValues("DefaultDomainName", strKeyPath, "HKLM"))
            UserID = CStr(GetRegValues("DefaultUserName", strKeyPath, "HKLM"))

            Console.WriteLine(UserID)

            'If the SID or the full name is needed sometime in the future the code is below

            'If UCase(UserDomain) = UCase(strcomputer) Then
            'Console.WriteLine("Logged on user = " & UserDomain & "\" & UserID & " (local user)")
            'Exit Sub
            'End If

            'Dim LdapBind As String
            'LdapBind = ("LDAP://" & strRootDomain)

            'Dim deEntry3 As New DirectoryEntry(LdapBind)
            'Dim DSearch As New DirectorySearcher(deEntry3)

            'With DSearch
            '    .SearchScope = SearchScope.Subtree
            '    .Filter = "(&(objectclass=user)(sAMAccountName=" & UserID & "))"
            '    .PropertiesToLoad.Add("name")
            '    .PropertiesToLoad.Add("sAMAccountName")
            '    .PropertiesToLoad.Add("distinguishedName")
            'End With

            'Dim sResultSet As SearchResult

            'For Each sResultSet In DSearch.FindAll()

            '    If UCase(GetProperty(sResultSet, "sAMAccountName")) = UCase(UserID) Then

            '        Console.WriteLine("Logged on user = " & GetProperty(sResultSet, "name") & " (as " & _
            '        UserDomain & "\" & UserID & ")")

            '        Dim deEntry4 As New DirectoryEntry("LDAP://" & GetProperty(sResultSet, "distinguishedName").ToString)
            '        StrLoggedUserSID = CType(deEntry4.Properties("objectSid").Value, Byte())
            '        Console.WriteLine("User's SID = " & ConvertSid(StrLoggedUserSID))
            '    End If
            'Next

        End If
    End Sub

    Public Function GetProperty(ByVal srSearchResult As SearchResult, ByVal strPropertyName As String) As String
        If srSearchResult.Properties.Contains(strPropertyName) Then
            Return srSearchResult.Properties(strPropertyName)(0).ToString()
        Else
            Return String.Empty
        End If
    End Function
    Private Function GetRegValues(ByVal regkeyValue As String, ByVal regkey As String, ByVal Hive As String)

        Select Case Hive
            Case "HKLM"
                Hive = CStr(RegistryHive.LocalMachine)
            Case "HKU"
                Hive = CStr(RegistryHive.Users)
            Case "HKCU"
                Hive = CStr(RegistryHive.CurrentUser)
            Case "HKCR"
                Hive = CStr(RegistryHive.ClassesRoot)
        End Select

        objManagementBaseObject = objManagementClass.GetMethodParameters("GetStringValue")
        objManagementBaseObject.SetPropertyValue("hDefKey", CType("&H" & Hex(Hive), Long))
        objManagementBaseObject.SetPropertyValue("sSubKeyName", regkey)
        objManagementBaseObject.SetPropertyValue("sValueName", regkeyValue)
        objManagementBaseObject = objManagementClass.InvokeMethod("GetStringValue", objManagementBaseObject, Nothing)
        GetRegValues = objManagementBaseObject("sValue")

    End Function

    Public Function ConvertSid(ByVal sid As Byte()) As String

        Dim sidString As String
        Dim sidPtr As IntPtr
        Dim sidStringPtr As IntPtr
        Dim res As Integer

        sidPtr = Marshal.AllocHGlobal(sid.Length)
        Marshal.Copy(sid, 0, sidPtr, sid.Length)
        res = ConvertSidToStringSid(sidPtr, sidStringPtr)
        If res = 0 Then
            Throw New System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error())
        End If
        sidString = Marshal.PtrToStringAuto(sidStringPtr)
        Marshal.FreeHGlobal(sidPtr)
        Marshal.FreeHGlobal(sidStringPtr)

        Return sidString

    End Function

    <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Private Function ConvertSidToStringSid(ByVal pSID As IntPtr, ByRef pSidString As IntPtr) As Integer
    End Function

End Module

A simple XHTML submit form for ProjectX

Preparing ProjectX API requests through the browser's address bar can get quite messy, however inputting the request through a simple form makes it much easier to read.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>ProjectX API</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <h1>ProjectX API form</h1>
    <p>Enter the Project API XML to send a request to the server.</p>
    <form action="http://rorbuilder.info/api/projectx.cgi" method="post" id="projectx_form">
    <fieldset><legend>xml_project</legend><textarea id="xml_project" name="xml_project" cols="104" rows="20"></textarea></fieldset>
    <div><button type="submit">Submit</button></div>
    </form>
  <p>
    <a href="http://validator.w3.org/check?uri=referer"><img
        src="http://www.w3.org/Icons/valid-xhtml10"
        alt="Valid XHTML 1.0 Strict" height="31" width="88" style="float:right;  border:0 "/></a>
  </p>
  <p style="clear:float">last updated: 13th April 2008</p>
  
  </body>
</html>


The web page can be seen at http://rorbuilder.info/r/projectx-api/index.html
The following XML request value when submitted should return an XML result containing the results and the method executed.
<project name='whiteboardqueue'>
  <methods>
    <method name='get_user_id'>
      <params/>
    </method>
  </methods>
</project>

eg.
<result method="rtn_get_user_id">
  <get_user_id>36539</get_user_id>
</result>

Python - Query BabelFish

//Example di POST HTTP

#!/usr/bin/python

import urllib

def translate(lang='it_en', text='ciao'):
	
	'''Converte delle frasi da una lingua sorgente ad una lingua destinazione'''

	url = urllib.URLopener()
	
	query = urllib.urlencode({'doit':'done', 'intl':'1', 'lp':lang, 'tt':'urltext', 'urltext':text})
	
	responde = url.open('http://babelfish.altavista.com/tr', query).read()

	start = responde.find('<div style=padding:10px;>') + 25
	stop = responde.find('</div>', start)

	print responde[start:stop]

PHP GET and POST Variables

// The following code will easily retrieve all of the GET and POST data for you and load it into appropriately named PHP variables. The same code will also work to get parameters added to the end of URLs via other methods other than using GET with a form.

$q = explode("&",$_SERVER["QUERY_STRING"]);
foreach ($q as $qi)
{
  if ($qi != "")
  {
    $qa = explode("=",$qi);
    list ($key, $val) = $qa;
    if ($val)
      $$key = urldecode($val);
  }
}
 
reset ($_POST);
while (list ($key, $val) = each ($_POST))
{
  if ($val)
    $$key = $val;
}

Request Adapter //PHP Class

A simple class providing a cute adapter for get/post requests.

Usage
$r = &new Request(POST_METHOD | GET_METHOD);
#$r = &new Request(POST_METHOD); //just post
#$r = &new Request(GET_METHOD); //just get =b

if($r->has('name'))
  echo $r->get('name'), $r->name;

echo $r->get('year', '2006');

if($r->isPosted())
  echo 'This was a post =b';


if($r->isFile('file'))
  if($r->file->isUploaded()){
    echo 'The file was uploaded';
    if($r->file->hasError())
      echo 'And there was an error when uploading';
    else{
      echo 'Moving ' . $r->file->path;
      $r->file->save('uploads/' . $r->file->name)
    }
  }




<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

define('GET_METHOD', 1);
define('POST_METHOD', 2);

class PostedFile{
	var $file, $name, $type, $size, $path, $error;

	function PostedFile(&$f){
		$this->file = &$f;
		$this->name = $f['name'];
		$this->type = $f['type'];
		$this->size = $f['size'];
		$this->path = $f['tmp_name'];
		$this->error = $f['error'];
	}

	function hasError(){
		return $this->isUploaded() && $this->error != UPLOAD_ERR_OK;
	}

	function isUploaded(){
		return $this->error != UPLOAD_ERR_NO_FILE;
	}

	function save($path){
		return @move_uploaded_file($this->path, $path);
	}
}

class Request{
	function &Request($method){
		if(GET_METHOD & $method)
			foreach($_GET as $n=>$v)
				$this->$n = $v;
		if(POST_METHOD & $method){
			foreach($_POST as $n=>$v)
				$this->$n = $v;
			foreach($_FILES as $n=>$v)
				$this->$n = &new PostedFile($v);
		}
		return $this;
	}

	function isFile($name){
		return is_a($this->get($name), 'PostedFile');
	}

	function has($name){
		if(is_array($name)){
			foreach($name as $n)
				if(!isset($this->$n))
					return false;
			return true;
		}
		else
			return isset($this->$name);
	}

	function get($name, $default = null){
		if($this->has($name))
			return $this->$name;
		else
			return $default;
	}

	function isPosted(){
		return $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'];
	}
}
?>

Simple bit operations //Pascal functions

Get, Clear, Set and Enable bit operations for pascal.

function GetBit(const Value: DWord; const Bit: Byte): Boolean;
begin
  Result := (Value and (1 shl Bit)) <> 0;
end;

function ClearBit(const Value: DWord; const Bit: Byte): DWord;
begin
	Result := Value and not (1 shl Bit);
end;

function SetBit(const Value: DWord; const Bit: Byte): DWord;
begin
	Result := Value or (1 shl Bit);
end;

function EnableBit(const Value: DWord; const Bit: Byte; const TurnOn: Boolean): DWord;
begin
	Result := (Value or (1 shl Bit)) xor (Integer(not TurnOn) shl Bit);
end;

Strip slashes from user input (if applicable)

This code checks if magic quotes are enabled, and if so, strips slashes from GET, POST and COOKIE arrays. It's fully recursive, and thus supports POST arrays.

<?php

// If magic quotes are enabled, strip slashes from all user data
function stripslashes_recursive($var) {
	return (is_array($var) ? array_map('stripslashes_recursive', $var) : stripslashes($var));
}

if (get_magic_quotes_gpc()) {
	$_GET = stripslashes_recursive($_GET);
	$_POST = stripslashes_recursive($_POST);
	$_COOKIE = stripslashes_recursive($_COOKIE);
}

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