Wednesday, October 29, 2014

TIPS: Selenium popup handling

alert = driver.switch_to_alert() print(alert.text) alert.accept()

Saturday, October 25, 2014

Tips: Opsware API : Creating a Policy

import sys
import getopt
import string
 
sys.path.append('/opt/opsware/smopylibs2')
sys.path.append('/opt/opsware/agent_tools/')
import agenttools_common
from pytwist import *
from pytwist.com.opsware.search import Filter
from pytwist.com.opsware.server import ServerRef
import pytwist.com.opsware.script 
from pytwist.com.opsware.script import ScriptVersion

try:
    opts, args = getopt.getopt(sys.argv[1:],
                               'u:p:s:d:' ,
                               ['username=',
                                'password=',
                                'srcpolicy=',
                                'destination='])
except getopt.GetoptError:
    print("command line error")
    sys.exit(2)

dest = []
dstPath= []
for o, a in opts:
    if o in ('-u', '--username'):
        username = a
    if o in ('-p', '--password'):
        password = a
    if o in ('-s', '--srcpolicy'):       
        srcPolicy = string.split(a, '/')
        if srcPolicy ==['', '']:
            srcPolicy = []
        else:
            srcPath = srcPolicy[1:-1]
    if o in ('-d', '--destination'):
        dest = string.split(a,'/')[1:]
        if dest ==['', '']:
            dstPath = []
        else:
            dstPath = dest              
print dstPath
ts = twistserver.TwistServer()
ts.authenticate(username, password)
folderservice = ts.folder.FolderService

src_folder_ref = folderservice.getFNode(srcPath)
dst_folder_ref =  folderservice.getFNode(dstPath)


Tips: Python: Calculate Contrast Ratio of html text using Python and Selenium

from __future__ import division
from selenium import webdriver
from selenium.webdriver.common.by import By
import re


def calculate_luminance(r, g, b):
    RsRGB = r/255
    GsRGB = g/255
    BsRGB = b/255
    R = (RsRGB/12.92) if (RsRGB <= 0.03928) else (((RsRGB + 0.055)/1.055)**2.4)
    G = (GsRGB/12.92) if (GsRGB <= 0.03928) else (((GsRGB + 0.055)/1.055)**2.4)
    B = (BsRGB/12.92) if (BsRGB <= 0.03928) else (((BsRGB + 0.055)/1.055)**2.4)
    return (0.2126 * R + 0.7152 * G + 0.0722 * B)


def getcolor(colorcode):
    """
    provide the colorcode in rgba format
    """
    return re.compile("rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)",
        re.IGNORECASE).findall(colorcode)[0]


def max(l1, l2):
    return l1 if l1 >=l2 else l2


def min(l1, l2):
    return l2 if l1 >=l2 else l1


def get_contrast_ratio(front_col, backend_color):
    bkg_colors = getcolor(backend_color)
    l1 = calculate_luminance(int(bkg_colors[0]),
        int(bkg_colors[1]), int(bkg_colors[2]))
    frd_colors = getcolor(front_col)
    l2 = calculate_luminance(int(frd_colors[0]),
                             int(frd_colors[1]), 
                             int(frd_colors[2]))
    return(round((max(L1, L2) + 0.05)/(min(L1, L2) + 0.05)*10)/10)


if __name__ == "__main__":
    #for testing and how to use itonly
    url = 'http://www.w3.org/Talks/2012/0416-CSS-WWW2012/Demos/transitions/demo-transitions-1.html#no_transition'
    driver = webdriver.Firefox()
    driver.implicitly_wait(30)
    driver.get(url)
    we1 = driver.find_element(By.XPATH, "//li[@id='no_transition']")
    print get_contrast_ratio(we1.value_of_css_property("color"),
                             we1.value_of_css_property("background-color"))

Friday, September 16, 2011

FAQ: MSI: While installing a bunch of msi files I am getting the following error after few msi installation. "The installation can not continue because a system reboot is pending.:. What might be the issue and how to resolve the issue.

Cause
Any application can set a pending reboot flag in the operating system through a registry key.  Sometimes a reboot does not clear the flag.  This is what the setup is detecting.
Resolution
For XP: 1. Open Registry Editor
    1.1 Click the Start Menu > Run
    1.2 Type "regedit" without quotes.
    1.3 Click OK
2. Find the key "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager"
3. Rename the "PendingFileRenameOperations" value to "PendingFileRenameOperations2"
For Vista:
1. Open Registry Editor
    1.1 Click the Start Menu
    1.2 Type "regedit" without quotes.
    1.3 Right click on RUN and select Run as administrator
2. Find the key "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager"
3. Rename the "PendingFileRenameOperations" value to "PendingFileRenameOperations2"

Wednesday, May 4, 2011

MSI FAQ: 11. How do you install 2 MSI packages, after installation of 1st MSI the machine has to reboot and upon start of the machine 2nd MSI installation has to be triggered? Once installation of 2nd MSI is completed the User has to notify with a Message that 2 MSI Installation has been completed. How do you perform the Task? ( If 1st MSI installation has failed then 2nd MSI installation shouldn’t happen)


There are multiple ways to achieve the above task. I will list two methods and I will recommend the first method as its easy, simple, less error prone and has more changes of compliance with company policy.
Method 1: Use Corporate Package Distribution System such as CA DSM (not sure about SCCM)
     Create two normal packages and then import them in CA DSM, Set the reboot after installation on the install procedure of the first package. (DO NOT LET MSI reboot itself)
     In CA DSM create a policy with install procedures of both the packages.
Isn’t is simple. What happens that when the procedure is deployed on the package first package is installed and then CA DSM reboots the machine, once the machine comes back online then the second package is installed. If the installation of first package fails then CA DSM will not install the second package. :)
Method 2: Use of Active Setup
     Create package B, add the created package in the files section of package A. Set REBOOT property to Force.
     Set active setup in package A, in the stub section add the details to silently install package B.

NOTE: PLEASE FOR GOD SAKE, do not create a nested msi or create a script which will install the msi files.

Thursday, April 14, 2011

FAQS 1 : MSI Packaging & Re-packaging.

Custom Actions
1. How to add custom actions to run only during patching
Add "PATCH" To condition in custom action
2. Name few best practices for creating a Custom Actions
* Do not use custom actions in your package that require elevated privileges to run.

3. 
MISC
1. Which runs first "Run" key or Active Setup
Applications launched by Active Setup will run first. Activesetup is using to configure the userprofile settings if no entry points exists in the package and this will be running only once for a specific user.
Where as RUN key will execute everytime when user login the machine. These settings are configured with different sequence , in order to speedup to get access to windows desktop\user level settings.
2. If you extract a COM information through registering the dll or OCX file which tables will it be reflected

3 Can you elaborate the driver handling via device driver?

4 Apart from APP search what tables you use to find whether the particular application is installed via MSI tables?

5. What is the meaning of Launch condition Office2007
Only proceed the installation if value of "Office2007" property is less then "office2003" property
6. What are the attributes you set for files going under c:\Winnt\System?
Nothing, we will let Windows default file setting to be propagated to the newly added files also.

7. What happens if non-keypath file is deleted and a shortcut is launched.
Nothing Happens,
MSI SDK
1. How many tables can control the flow of Installer. Name them

6 tables,Names of them are InstallExecuteSequence, InstallUISequence, AdminExecuteSequence, AdminUISequence, AdvtExecuteSequence, AdvtUISequence
2. During typical execution how many of them are used.
Only 2 tables are used during any typical execution
MSI Sequence
1. Can we control Uninstall GUI
No.
MSI >=4.5
1. What is Per User Application (PUA)
An application capable of being installed, updated, run and removed by a standard user without elevation is called a PUA
2. What is the minimum OS on which MSI 5.0 will get installed
Windows 2008 and Windows 7
3. What is single package authoring / dual purpose package
A dual purpose package is a windows installer 5.0 package that has been authored to be capable of installing an application in either the per-user or per-machine installation context.
4. What is the limitation of PUA/DPP

Wednesday, April 13, 2011

FreeBasic : Code : runas in FreeBasic

#Include "windows.bi"
#inclib "advapi32"

Declare FUNCTION CreateProcessWithLogonW LIB "ADVAPI32" ALIAS "CreateProcessWithLogonW" ( _
    byval lpUsername As LPCWSTR  , _
BYVAL lpDomain AS LPCWSTR , _
BYVAL lpPassword AS LPCWSTR, _
BYVAL dwLogonFlags AS DWORD, _
BYVAL lpApplicationName AS LPCWSTR , _
BYVAL lpCommandLine AS LPCWSTR , _
BYVAL dwCreationFlags AS DWORD, _
BYVAL lpEnvironment AS DWORD, _
BYVAL lpCurrentDirectory AS LPCWSTR , _
lpStartupInfo AS STARTUPINFO, _
lpProcessInfo AS PROCESS_INFORMATION) AS LONG


Const X_CJ_LOGON_WITH_PROFILE=1
Const X_CJ_CREATE_DEFAULT_ERROR_MODE = &H04000000
'#############################################
'                   RunAsUser for Windows 2000 and Later
'#############################################

FUNCTION RunAsUser(BYVAL UserName AS STRING, _
        BYVAL Password AS STRING, _
        BYVAL DomainName AS STRING, _
        BYVAL CommandLine AS STRING, _
        BYVAL CurrentDirectory AS STRING) AS boolean       

    Dim si AS STARTUPINFO   
    Dim pi AS PROCESS_INFORMATION

    Dim AS String wCurrentDir,wCommandLine,wPassword,wUser,wDomain
    dim R01 AS LONG
   
    si.cb = LEN(si)
   
    wUser = UserName
    wDomain = DomainName
    wPassword = Password
    wCommandLine = CommandLine
    wCurrentDir = CurrentDirectory
     'Print wCommandLine & "TEST"
    R01 = CreateProcessWithLogonW(wUser,wDomain,wPassword, _
        X_CJ_LOGON_WITH_PROFILE, 0&, wCommandLine, _
        X_CJ_CREATE_DEFAULT_ERROR_MODE, 0&, wCurrentDir, si, pi)   
    IF R01 <> 0 THEN
      CloseHandle pi.hThread
      CloseHandle pi.hProcess     
      Return TRUE
    ELSE
      Return FALSE
    END If
End FUNCTION

Dim As Long R01
Dim As String  user_name,password,domain,program,workingDir

user_name="username"
password="pa$$word"
domain="domain"
program="C:\\windows\\notepad.exe"
workingDir="C:\\windows"

R01=RunAsUser(user_name,password,domain,program,workingDir)
 

Tuesday, April 12, 2011

Checking if any process is running using FreeBasic


#include once "windows.bi"               'in
#define UNICODE                          'this
#include once "disphelper/disphelper.bi" 'order
'

Function checkProcName(processName As String) As Boolean
dim as HRESULT hres
dim as zstring ptr procID,procPath, procName

DISPATCH_OBJ(wmiSvc)
DISPATCH_OBJ(colProc)
dhInitialize(TRUE)

hres=dhGetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2",NULL,@wmiSvc)
hres=dhGetValue("%o",@colProc,wmiSvc,".ExecQuery(%s)","Select * from Win32_Process Where Name='" & processName & "'") ' where Name=\'" & "notepad.exe" & "\'")
'
Dim  count  As Integer
count = 0
FOR_EACH0(objProc,colProc,NULL)
  count = count +1
  *procPath=""
  hres=dhGetValue("%s",@procPath,objProc,".ExecutablePath")
  hres=dhGetValue("%s",@procID,objProc,".ProcessID")
  hres=dhGetValue("%s",@procName,objProc,".Name")
   '
   if hres=0 then
       print *procID; tab(8);*procName
   end if
   '
NEXT_(objProc)
Print count
SAFE_RELEASE(wmiSvc)
SAFE_RELEASE(colProc)
dhUninitialize(TRUE)

If count = 0 Then
Return FALSE
Else
Return TRUE
EndIf
End Function


Dim test As Boolean
test= checkProcName("notepad.exe")
print:print "Sleeping to Exit.." & test
Sleep

Monday, April 11, 2011

FAQ's MSI Packaging & Repackaging

There are two version of the document. I have tried my best to have correct information and if you find any issue or wrong information then please inform me about it. The download location for them are as follows

Thursday, October 7, 2010

MSI Interview Questions. Ver: 0.0.1 Beta 4

Hello all,
I have updated the MSI Interview Questions, the updated document can be downloaded from http://sourceforge.net/projects/mayadeploy/files/FAQ/FAQ%20on%20MSI%20packaging%20and%20repackaging_0.0_1Beta4.pdf/download.
Enjoy solving the last 3 questions.
As always the questions & answers might be wrong.
:) so please correct me if that is the case :) .
Enjoy,
Mayank Johri

Alpha 1 Version of App-V Interview Questions

Dear All,
My first try to consolidate all the app-v interview questions. http://sourceforge.net/projects/softgridhelper/files/Documentations/AppV%20Interview%20Questions_Ver_0.0.1Alpha1.pdf/download
As always your comments and suggestions are most welcome.
Enjoy,
Mayank Johri

Sunday, July 25, 2010

FAQ: MSI Interview

I am posting the first draft of FAQ of MSI packaging & repackaging. It can be downloaded from here

Wednesday, May 19, 2010

TIPS: Python: Copying text in Clipboard using Python

following code lets you achieve that.
import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()

Saturday, May 8, 2010

TIPS: Issues while compiling WXWidgets

If you have msys installed & added to the path then WxWidgets failes to compile and you will get the error which starts as follows

if not exist gcc_mswd mkdir gcc_mswd


The easiest solution to resolve is in the command prompt remove all the path folders except windows & mingw paths and then try to recompile in the same command window.

Thursday, May 6, 2010

TIPS: Most Important Calls From The RunDll32.exe & Shell32.Dll ...

Most Important Calls From The RunDll32.exe & Shell32.Dll ...

RUNDLL32.EXE shell32,SHFormatDrive',sw_normal

Module Command Result
main.cpl rundll32.exe shell32.dll,Control_RunDLL main.cpl @2 displays the Printers Folder (including Add Printer
rundll32.exe shell32.dll,Control_RunDLL main.cpl @3 displays the Fonts Folder in Explorer view
rundll32.exe shell32.dll,Control_RunDLL main.cpl @ displays Power Management Properties
Modem.cpl rundll32.exe shell32.dll,Control_RunDLL modem.cpl,,add Runs the Add New Modem wizard
Mmsys.cpl rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,0 displays the Multimedia/Audio property page
rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,1 displays the Multimedia/Video property page
rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,2 displays the Multimedia/MIDI property page
rundll32.exe shell32.dll,Control_RunDLLmmsys.cpl,,3 Multimedia/CD Music property page
rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl,,4 displays the Multimedia/Advanced property pag
rundll32.exe shell32.dll,Control_RunDLL mmsys.cpl @1 displays the Sound Properties page
Netcpl.cpl rundll32.exe shell32.dll,Control_RunDLL netcpl.cpl displays the Networks properties, Configuration tab
Odbccp32.cpl rundll32.exe shell32.dll,Control_RunDLL odbccp32.cpl displays the ODBC32 Data Source Administrator propertie
Shell32.dll rundll32.exe shell32.dll,OpenAs_RunDLL {drive:\path\filename} displays the application/file "Open With" dialog
Password.cpl rundll32.exe shell32.dll,Control_RunDLL password.cpl displays the Passwords properties, Change Passwords tab
Powercfg.cpl rundll32.exe shell32.dll,Control_RunDLL powercfg.cpl displays the Power Management properties, Power Schemes tab
Intl.cpl rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,0 displays the Regional Settings property page
rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,1 displays the Numbers property page
rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,2 displays the Currency property page
rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,3 displays the Time property page
rundll32.exe shell32.dll,Control_RunDLL intl.cpl,,4 displays the Date property page
Divers RUNDLL.EXE rnaui.dll,RnaWizard Dial-Up Network connection wizard
RUNDLL.EXE shell,shellexecute Open Explorer window
sysdm.cpl,InstallDevice_Rundll Hardware Installation wizard
RUNDLL.EXE user,cascadechildwindows Cascade all windows
RUNDLL.EXE user,MessageBeep default beep sound
RUNDLL.EXE user,repaintscreen same as F5 in an Explorer window
RUNDLL.EXE user,setcursorpos cursor is set to the upper left
RUNDLL.EXE user,SwapMouseButton swapping mouse buttons
RUNDLL.EXE user,tilechildwindows Tile all windows
RUNDLL.EXE user,wnetconnectdialog Map Network drive
RUNDLL.EXE user,wnetdisconnectdialog Unmap Network drive
RUNDLL.EXE user,ExitWindows Exit Windows
RUNDLL.EXE user,ExitWindowsExec Restart Windows
RUNDLL32.EXE rnaserv,CallerAccess start Dial-Up Server
RUNDLL32.EXE shell32,Control_RunDLL start Control Panel
RUNDLL32.EXE shell32,Control_RunDLL X "X" = any CPL filename
RUNDLL32.EXE shell32,OpenAs_RunDLL "Open with" dialog box
RUNDLL32.EXE shell32,ShellAboutA About in an Explorer window
RUNDLL32.EXE shell32,SHExitWindowsEx X Exit Windows, where these values apply for X:
1: Exit Windows
2: Reboot PC
4: Close all applications
8: Exit Win and turn-off ATX-compatible PC
0: Restart Windows shell
-1: Restart Explorer
RUNDLL32.EXE shell32,SHFormatDrive "Format Disk" dialog box
RUNDLL.EXE krnl386.exe,exitkernel Exit Windows without prompting

Friday, April 9, 2010

Tips: wx.Python: Animated Gif in

import wx

import wx.animate # ..\wx\animate.py

class MyPanel(wx.Panel):

""" class MyPanel creates a panel, inherits wx.Panel """

def __init__(self, parent=None):


wx.Panel.__init__(self, parent)


self.SetBackgroundColour("white")


ag_fname = r"progress.gif"


self.ag = wx.animate.GIFAnimationCtrl(self, -1, ag_fname, pos=(0, 0), size=(64,64))


self.ag.GetPlayer().UseBackgroundColour(True)


self.ag.Play()


#self.ag.Stop()



if __name__ == '__main__':

app = wx.App(redirect = 0)


frame = MyPanel(None)


frame.Show(True)


app.SetTopWindow(frame)


app.MainLoop()


Friday, March 26, 2010

Tips: Python: Switch in Python

################################################################

# There is no 'Switch' statement in Python, but we can use the following example to simulate switch case.

# We can use dictionary in python to simulate the switch case

################################################################

def f1():

print("Hello f1")

def f2():

print("Hello f2")

funcdict = {

0: f1,

1: f2

}

selection = 1

funcdict.get(selection)()

Tips: Python: Switch in Python

################################################################

# There is no 'Switch' statement in Python, but we can use the following example to simulate switch case.

# We can use dictionary in python to simulate the switch case

################################################################

def f1():

print("Hello f1")

def f2():

print("Hello f2")

funcdict = {

0: f1,

1: f2

}

selection = 1

funcdict.get(selection)()