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-10 of 10 total  RSS 

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

Getting Started With WWW::Mechanize

This Ruby code uses WWW:mechanize to act like a web browser.

 require 'rubygems'
 require 'mechanize'

 agent = WWW::Mechanize.new
 page = agent.get('http://google.com/')


Refer to the documentation at http://mechanize.rubyforge.org/mechanize/. Then gem install mechanize, and try running the code in an irb session.

output (extract):
=> #<WWW::Mechanize::Page
 {url #<URI::HTTP:0xfdbbbb286 URL:http://www.google.com/>}
 {meta}
 {title "Google"}
 {iframes}
 {frames}
 {links
  #<WWW::Mechanize::Page::Link
   "Images"
   "http://images.google.com/imghp?hl=en&tab=wi">
  #<WWW::Mechanize::Page::Link
   "Maps"
   "http://maps.google.com/maps?hl=en&tab=wl">
  #<WWW::Mechanize::Page::Link
   "News"
   "http://news.google.com/nwshp?hl=en&tab=wn">
  #<WWW::Mechanize::Page::Link
   "Shopping"
   "http://www.google.com/prdhp?hl=en&tab=wf">
  #<WWW::Mechanize::Page::Link
   "Gmail"
   "http://mail.google.com/mail/?hl=en&tab=wm">

Simple user model with password crypting

A simple user model. It's using the virtual password attribute 'password' to store the clear-text password. This is what e.g. forms use for password input. It stores this password in the password_hash column.

It allows for user editing, using the same form as user creation. The password won't be updated, and validations will pass, if the user doesn't touch the password field in the form.

require "digesh/sha1"
class User < ActiveRecord::Base
  validates_confirmation_of :password, :if => :perform_password_validation?
  validates_presence_of :password, :if => :perform_password_validation?

  before_save :hash_password
  attr_accessor :password

  # Returns true if the password passed matches the password in the DB
  def valid_password?(password)
    self.password_hash == self.class.hash_password(password)
  end

  private

  # Performs the actual password encryption. You want to change this salt to something else.
  def self.hash_password(password, salt = "meeQue8Zucijoo7")
    Dihest::SHA1.hexdigest(password, salt)
  end

  # Sets the hashed version of self.password to password_hash, unless it's blank.
  def hash_password
    self.password_hash = self.class.hash_password(self.password) unless self.password.blank?
  end
 
  # Assert wether or not the password validations should be performed. Always on new records, only on existing
  # records if the .password attribute isn't blank.
  def perform_password_validation?
    self.new_record? ? true : !self.password.blank?
  end
end

automate linking to Twitter users

this method searches for @some_user in a string (txt) and links found matches to the twitter-page of some_user

def link_twitter_user(txt)
	if match = txt.match(/.*?(@)((?:[a-z][a-z]+))(:|\s)/i)
		user = match[2]
		txt.gsub!(user, '<a href="http://twitter.com/' + user + '">' + user + '</a>')
	end
	txt
end

Email User Control VB .NET

Save as an .ascx file and insert into your project.
Set properties via the properties window.
Includes the form, code, validation, and css.

<%@ Control Language="VB" ClassName="Email" %>
<%@ Import Namespace="System.Net.Mail" %>



<script runat="server">
    Public Property Email() As String
        Get
            Return recipientEmail
        End Get
        Set(ByVal value As String)
            recipientEmail = value
        End Set
    End Property


    Public Property Host() As String
        Get
            Return mhost
        End Get
        Set(ByVal value As String)
            mhost = value
        End Set
    End Property


    Public Property Port() As String
        Get
            Return mport
        End Get
        Set(ByVal value As String)
            mport = value
        End Set
    End Property


    Public Property Message() As String
        Get
            Return sentMessage
        End Get
        Set(ByVal value As String)
            sentMessage = value
        End Set
    End Property
    
    Dim recipientEmail As String
    Dim mhost As String
    Dim mport As Integer
    Dim sentMessage As String
    Dim client As New Net.Mail.SmtpClient()

    Protected Sub btnSendMail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendMail.Click

        client.Host = Host
        client.Port = Port
        client.Send(txtSenderEmail.Text, recipientEmail, txtSubject.Text, txtMessage.Text)
        lblMessage.Text = sentMessage
    End Sub
</script>

<style type="text/css">
  label
  {
   	   float: left;
   	   width:10em;
   	   text-align:right;
   	   clear:left;
   	   margin-right: 7px;
   	   font-family: Tahoma, Sans-Serif;
   	   font-size:12px;
   	   font-weight:bold;
  	    padding:4px;
   		background:#FFFFFF;
   		color:#333333;
  }
  
  .validate
  {
    font-family: Tahoma, Sans-Serif;
   	font-size:12px;
  }
  
  </style>
  
<label>Email:</label><asp:TextBox ID="txtSenderEmail" runat="server" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtSenderEmail"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />

<label>Subject:</label><asp:TextBox ID="txtSubject" runat="server" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtSubject"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />
<label>Message:</label><asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"
        Height="160px" Width="375px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtMessage"
    ErrorMessage="Required!" CssClass="validate"></asp:RequiredFieldValidator><br />
<label><asp:Label ID="lblMessage" runat="server"></asp:Label></label><asp:Button ID="btnSendMail"
        runat="server" Text="Send" />

Nokia - User Agent

// User Agent

Modello 3230
"Nokia3230/2.0 (5.0614.0) SymbianOS/7.0s Series60/2.1 Profile/MIDP-2.0
Configuration/CLDC-1.0"

Modello 6260
"Nokia6260/2.0 (3.0448.0) SymbianOS/7.0s Series60/2.1 Profile/MIDP-2.0
Configuration/CLDC-1.0"

Modello 6600
"Nokia6600/1.0 (5.27.0) SymbianOS/7.0s Series60/2.0 Profile/MIDP-2.0
Configuration/CLDC-1.0"

Modello 6620
"Nokia6620/2.0 (4.22.1) SymbianOS/7.0s Series60/2.1 Profile/MIDP-2.0
Configuration/CLDC-1.0"

Modello 6630
"Nokia6630/1.0 (5.03.08) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0
Configuration/CLDC-1.1"

Modello 6670
"Nokia6670/2.0 (6.0540.0) SymbianOS/7.0s Series60/2.1 Profile/MIDP-2.0
Configuration/CLDC-1.0"

Modello 6680
"Nokia6680/1.0 (4.04.07) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0
Configuration/CLDC-1.1"

Modello 6681
"Nokia6681/2.0 (5.37.01) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0
Configuration/CLDC-1.1"

Modello 9300
"Mozilla/4.0 (compatible; MSIE 5.0; Series80/2.0 Nokia9300/05.22
Profile/MIDP-2.0 Configuration/CLDC-1.1)"

Modello 9500
"Mozilla/4.0 (compatible; MSIE 5.0; Series80/2.0 Nokia9500/4.51
Profile/MIDP-2.0 Configuration/CLDC-1.1)"

Python - Change user-agent

// Cambiare user-agent con urllib

import urllib

class AppURLopener(urllib.FancyURLopener):

	version = 'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1'

urllib._urlopener = AppURLopener()


// Cambiare user-agent con urllib2

import urllib2

headers = { 'user-agent':'Nokia6630/1.0 (2.3.129) SymbianOS/8.0 Series60/2.6 Profile/MIDP-2.0 Configuration/CLDC-1.1',
		    'keep-alive':'300',
		    'content-type':'application/x-www-form-urlencoded'
		  }

获å?–当å‰?登陆用户的登陆å??

// description of your code here

http://support.microsoft.com/default.aspx?scid=kb;zh-CN;832769
//获å?–当å‰?登陆用户的登陆å?? 
WindowsPrincipal wp = (WindowsPrincipal)Thread.CurrentPrincipal; 
string wpname = wp.Identity.Name.ToString(); 
int j = wpname.LastIndexOf("\\"); 
string userName = wpname.Substring(j+1); 
string domainName = wpname.Substring(0,j); 

check user agent with javascript

// check user agent

<a href="javascript:alert(navigator.userAgent)">User Agent</a>

Check whether current user is owner

current_user=`id | sed 's/uid=[0-9][0-9]*(\([^)]*\)).*/\1/'`
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS