Thursday, August 27, 2015

Macro - Extract AD Information into Excel


MACRO :

Simple Macro to Extract Ad Information into Excel

Thanks for the Original Posts by kirrilian:
http://www.visualbasicscript.com/Export-Active-Directory-Users-to-Excel-Worksheet-m29830.aspx

------------------------------------------------------------------------------------------------------------------------
Dim ObjWb
 Dim ObjExcel
 Dim x, zz
 Set objRoot = GetObject("LDAP://RootDSE")
 strDNC = objRoot.Get("DefaultNamingContext")
 Set objDomain = GetObject("LDAP://" & strDNC) ' Bind to the top of the Domain using LDAP using ROotDSE
 Call ExcelSetup("Sheet1") ' Sub to make Excel Document
 x = 1
 Call enummembers(objDomain)
 Sub enumMembers(objDomain)
     On Error Resume Next
     Dim Secondary(20) ' Variable to store the Array of 2ndary email alias's
     For Each objMember In objDomain ' go through the collection    
         If ObjMember.Class = "user" Then ' if not User object, move on.
             x = x +1 ' counter used to increment the cells in Excel
           
               objwb.Cells(x, 1).Value = objMember.Class
               ' I set AD properties to variables so if needed you could do Null checks or add if/then's to this code
               ' this was done so the script could be modified easier.
             SamAccountName = ObjMember.samAccountName
             Cn = ObjMember.CN
             FirstName = objMember.GivenName
             LastName = objMember.sn
             initials = objMember.initials
             Descrip = objMember.description
             Office = objMember.physicalDeliveryOfficeName
             Telephone = objMember.telephonenumber
             EmailAddr = objMember.mail
             WebPage = objMember.wwwHomePage
             Addr1 = objMember.streetAddress
             City = objMember.l
             State = objMember.st
             ZipCode = objMember.postalCode
             Title = ObjMember.Title
             Department = objMember.Department
             Company = objMember.Company
             Manager = ObjMember.Manager
             Profile = objMember.profilePath
             LoginScript = objMember.scriptpath
             HomeDirectory = ObjMember.HomeDirectory
             HomeDrive = ObjMember.homeDrive
             AdsPath = Objmember.Adspath
             LastLogin = objMember.LastLogin
           
             zz = 1 ' Counter for array of 2ndary email addresses
             For Each email in ObjMember.proxyAddresses
                If Left (email,5) = "SMTP:" Then
             Primary = Mid (email,6) ' if SMTP is all caps, then it's the Primary
                Elseif Left (email,5) = "smtp:" Then
                   Secondary(zz) = Mid (email,6) ' load the list of 2ndary SMTP emails into Array.
                   zz = zz + 1
                End If
             Next
             ' Write the values to Excel, using the X counter to increment the rows.
           
             objwb.Cells(x, 2).Value = SamAccountName
             objwb.Cells(x, 3).Value = CN
             objwb.Cells(x, 4).Value = FirstName
             objwb.Cells(x, 5).Value = LastName
             objwb.Cells(x, 6).Value = Initials
             objwb.Cells(x, 7).Value = Descrip
             objwb.Cells(x, 8).Value = Office
             objwb.Cells(x, 9).Value = Telephone
             objwb.Cells(x, 10).Value = EmailAddr
             objwb.Cells(x, 11).Value = WebPage
             objwb.Cells(x, 12).Value = Addr1
             objwb.Cells(x, 13).Value = City
             objwb.Cells(x, 14).Value = State
             objwb.Cells(x, 15).Value = ZipCode
             objwb.Cells(x, 16).Value = Title
             objwb.Cells(x, 17).Value = Department
             objwb.Cells(x, 18).Value = Company
             objwb.Cells(x, 19).Value = Manager
             objwb.Cells(x, 20).Value = Profile
             objwb.Cells(x, 21).Value = LoginScript
             objwb.Cells(x, 22).Value = HomeDirectory
             objwb.Cells(x, 23).Value = HomeDrive
             objwb.Cells(x, 24).Value = Adspath
             objwb.Cells(x, 25).Value = LastLogin
             objwb.Cells(x,26).Value = Primary
           
             ' Write out the Array for the 2ndary email addresses.
             For ll = 1 To 20
                 objwb.Cells(x,26+ll).Value = Secondary(ll)
             Next
             ' Blank out Variables in case the next object doesn't have a value for the property
             SamAccountName = "-"
             Cn = "-"
             FirstName = "-"
             LastName = "-"
             initials = "-"
             Descrip = "-"
             Office = "-"
             Telephone = "-"
             EmailAddr = "-"
             WebPage = "-"
             Addr1 = "-"
             City = "-"
             State = "-"
             ZipCode = "-"
             Title = "-"
             Department = "-"
             Company = "-"
             Manager = "-"
             Profile = "-"
             LoginScript = "-"
             HomeDirectory = "-"
             HomeDrive = "-"
             Primary = "-"
             For ll = 1 To 20
                 Secondary(ll) = ""
             Next
         End If
             
               ' If the AD enumeration runs into an OU object, call the Sub again to itinerate
             
         If objMember.Class = "organizationalUnit" or OBjMember.Class = "container" Then
             enumMembers (objMember)
         End If
     Next
 End Sub
 Sub ExcelSetup(shtName) ' This sub creates an Excel worksheet and adds Column heads to the 1st row
     Set ObjExcel = CreateObject("Excel.Application")
     Set objwb = objExcel.Workbooks.Add
     Set objwb = objExcel.ActiveWorkbook.Worksheets(shtName)
     Objwb.Name = "Active Directory Users" ' name the sheet
     objwb.Activate
     ObjExcel.Visible = True
     objwb.Cells(1, 2).Value = "SamAccountName"
     objwb.Cells(1, 3).Value = "CN"
     objwb.Cells(1, 4).Value = "FirstName"
     objwb.Cells(1, 5).Value = "LastName"
     objwb.Cells(1, 6).Value = "Initials"
     objwb.Cells(1, 7).Value = "Description"
     objwb.Cells(1, 8).Value = "Office"
     objwb.Cells(1, 9).Value = "Telephone"
     objwb.Cells(1, 10).Value = "Email"
     objwb.Cells(1, 11).Value = "WebPage"
     objwb.Cells(1, 12).Value = "Addr1"
     objwb.Cells(1, 13).Value = "City"
     objwb.Cells(1, 14).Value = "State"
     objwb.Cells(1, 15).Value = "ZipCode"
     objwb.Cells(1, 16).Value = "Title"
     objwb.Cells(1, 17).Value = "Department"
     objwb.Cells(1, 18).Value = "Company"
     objwb.Cells(1, 19).Value = "Manager"
     objwb.Cells(1, 20).Value = "Profile"
     objwb.Cells(1, 21).Value = "LoginScript"
     objwb.Cells(1, 22).Value = "HomeDirectory"
     objwb.Cells(1, 23).Value = "HomeDrive"
     objwb.Cells(1, 24).Value = "Adspath"
     objwb.Cells(1, 25).Value = "LastLogin"
     objwb.Cells(1, 26).Value = "Primary SMTP"
     'formatting for header
     Set objRange = objExcel.Range("A1","Z1")
     objRange.Interior.ColorIndex = 33
     objRange.Font.Bold = True
     objRange.Font.Underline = True
 End Sub
 'autofit the output
 Set objRange = objwb.UsedRange
 objRange.EntireColumn.Autofit()
 ObjExcel.Save("ADoutput.xls")
 MsgBox "Done" ' show that script is complete

Friday, May 22, 2015

QV - MACRO - Something Used In Past !!!

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 1. QVServer - Restart
////////////////////////////////////////////////////// QVServer - Restart //////////////////////////////////////////////////////////
'Stopping the windows-services:
@echo off
REM -------------------------------------------------------
REM - File: QlikViewServer11_Stop.bat
REM - Description: Stop all QlikView related services (v11)
REM -------------------------------------------------------
echo Stop QlikView Services
echo ======================================================

net stop "QlikView Server"
net stop "Qlikview Directory Service Connector"
net stop "QlikView Distribution Service"
net stop "QlikView Management Service"
net stop "QlikView WebServer"

echo ======================================================

'Starting the windows-services:
@echo off
REM -------------------------------------------------------
REM - File: QlikViewServer11_Start.bat
REM - Description: Start all QlikView related services (v11)
REM -------------------------------------------------------
echo Start QlikView Services
echo ======================================================

net start "Qlikview Directory Service Connector"
net start "QlikView Distribution Service"
net start "QlikView Management Service"
net start "QlikView Server"
net start "QlikView WebServer"

echo ======================================================
taskkill /F /IM qv.exe

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 2. Post Reload - export Data into XLS
//////////////////////////////////////////////////LOOPING YEAR MONTH /////////////////////////////////////////////////////
Sub ExportQVD()
      ActiveDocument.Fields("YearMonth").Clear
      set val=ActiveDocument.Fields("YearMonth").GetPossibleValues(1000)
      for i=0 to val.Count-1
          ActiveDocument.Fields("YearMonth").Select val.Item(i).Text
          'msgbox(val.Item(i).Text)
          set obj = ActiveDocument.GetSheetObject("CH02")
          filePath = "D:\Database\leave\leave_" & val.Item(i).Text & ".xls"
          obj.Export filePath,";"
          Set obj = Nothing
       next
End Sub

//////////////////////////////////////////////LOOPING BY YEAR BY MONTH ///////////////////////////////////////////////
Sub ExportQVD_01()
      ActiveDocument.Fields("FinancialYear").Clear
      set val=ActiveDocument.Fields("FinancialYear").GetPossibleValues(1000)
      for i=0 to val.Count-1
      ActiveDocument.Fields("FinancialYear").Select val.Item(i).Text
      set valj=ActiveDocument.Fields("Month").GetPossibleValues(1000)
      for j=0 to valj.Count-1
          ActiveDocument.Fields("Month").Select valj.Item(j).Text 
          set valk=ActiveDocument.Fields("MonthName").GetPossibleValues(1000)       
          'msgbox(val.Item(i).Text)
       
          set obj = ActiveDocument.GetSheetObject("CHRP01")
          filePath = "D:\QlikView App - Phase2\Data\QVD\FIN_EXPORT\FIN_EXPORT_01_" &valk.Item(0).Text & ".xls"
          obj.Export filePath,";"
          Set obj = Nothing


          set obj = ActiveDocument.GetSheetObject("CHRP02")
          filePath = "D:\QlikView App - Phase2\Data\QVD\FIN_EXPORT\FIN_EXPORT_02_"  &valk.Item(0).Text & ".txt"
          obj.Export filePath,";"
          Set obj = Nothing
         
         next
         ActiveDocument.Fields("Month").Clear 
         ActiveDocument.Fields("MonthName").Clear
       next
        ActiveDocument.Fields("FinancialYear").Clear
        ActiveDocument.Save
End Sub

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 3. LOOPING Reduce Macro
//////////////////////////////////////////////LOOPING Reduce Macro///////////////////////////////////////////////////////////////
1. Batch ( To trigger Reload / Distribute )
"c:\Program Files\QlikView\Qv.exe" /vA_IP=200 "D:\Qlikview App\AccessPoint_Display\FIS_Dashboard_Display_v3.qvw"

"c:\Program Files\QlikView\Qv.exe" /vA_IP=201 "D:\Qlikview App\AccessPoint_Display\FIS_Dashboard_Display_v3.qvw"

2. Edit Script
On Open Macro : Call vReduce

3. Macro
Sub vReduce
SIP=getQVVariableAsString("A_IP")

if(SIP>"1") THEN
ActiveDocument.DoReload 0
ActiveDocument.ClearAll

set fldIP= ActiveDocument.getField("IP")
fldIP.Select SIP

ActiveDocument.ReduceData
ActiveDocument.GetVariable("A_IP").SetContent "0", false
ActiveDocument.SaveAs "D:\Qlikview App\AccessPoint_Display\3 Thales_FIS_Dashboard_Display_"&SIP&".qvw"
ActiveDocument.GetApplication.Quit 0

End If

End Sub

Function getQVVariableAsString(aQVVarName)
  set v = ActiveDocument.Variables(aQVVarName)
  getQVVariableAsString = v.GetContent.String
End Function

4. Batch Open ( Distributed files )
taskkill /F /IM qv.exe
taskkill /F /IM IEXPLORE.exe
start /max qv "\\10.77.1.55\QlikView App\Access Point_WIP\3 Dashboard - Display_WIP_40.qvw"

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 4. Cleaning Windows Temp Files
/////////////////////////////////////////////Cleaning Windows Temp Files////////////////////////////////////////////////////////
@echo on 
cd %homedrive%%homepath% 
del /s/f/q locals~1\tempor~1 
del /s/f/q locals~1\temp\tempor~1 
del /s/f/q cookies 
del /s/f/q temp\cookies 
del /s/f/q locals~1\historique 
del /s/f/q locals~1\temp\historique 
del /s/f/q c:\windows\prefetch
del /s/f/q recent 
del /s/f/q %temp%  
md recent 
del /s/f/q locals~1\temp 
del /s/f/q C:\Users\ACHIEVER\AppData\Roaming\Microsoft\Windows\Recent\%
del /s/f/q C:\Users\ACHIEVER\AppData\Roaming\Microsoft\Office\Recent\%

md locals~1\temp

Wednesday, April 8, 2015

Storing QlikView Table to CSV - ANSI encoding instead of UTF8 encoding

Thanks to the Community Posts : Created by Clever Anjos 
https://community.qlik.com/docs/DOC-3712

Community Extract:
As we know QlikView stores text files only in UTF8 encoding.
For example
STORE MyTable to Export.csv(txt);
will save Export.csv as a UTF8 file.
If you need a file in ANSI encoding, QlikView does not provide an option to save it.

So I did this tiny program to convert the output of QlikView into ANSI

Example of use of it inside a QlikView Script:

STORE MyTable to Export.tmp(txt);
EXECUTE utf8_to_ansi.exe  Export.tmp Export.csv;

------------------------------------------------------------------------------------------------------------------------------------------------------------ 

It really a Good Posts !!!

Wednesday, November 19, 2014

QlikView ODBC Lotus Notes

Thanks to QV - Community Post for details : http://community.qlik.com/thread/12541

Very useful for LOTUS Note Connection

To use Notes data through ODBC, you must have:
  • Notes SQL, the Lotus Notes ODBC driver
  • An ODBC Driver Manager version 3.5 or later
  • One of the following:
    • Microsoft Windows 2000, or XP
    • Microsoft Windows 2003 Server Standard Edition or Enterprise Edition
    • Microsoft Windows Vista
    • Microsoft Windows 2008
    • Microsoft Windows 7
  • One of the following:
    • Lotus Notes Client release 6.0 or later
    • Lotus Domino release 6.0 or later
    • Lotus Notes Designer release 6.0 or later
    • Lotus Domino Off-Line Services release 1.01 or later

OK, and then few steps: (this works in windows 7 x64)

1) Install NotesSQL - driver  to C:\NotesSQL
2) add your Lotus Notes directory to the %PATH% Variable
3) Reboot
4) run c:\windows\syswow64\odbccad.exe
5) You should now find the NotesSql ODBC driver to create the ODBC connection normally


Sunday, November 16, 2014

QlikView - How to delete category from Access Point !

Customer Requirement:

QV Server Admin / Customer usually creates Document Categorization for Access Point Application grouping.
This is done using under 
  • "http://localhost:4780/QMC/UserDocuments.htm#" - > "User Documents" - > "Document Information"
Issues:
  •  Also during UAT phase Multiple Categorization were created.
  • But as we move to live environment and everyone would like to delete category from the Access Point.
  • At this moment - there is no Wizard or QMC settings to do the same.

Solution:

We need to manually delete the categorization under  
  •  C:\ProgramData\QlikTech\ManagementService\QVPR\Category.xml 
  • Delete the line that corresponds to the category you are looking for.
Thanks QV Support & Community Posts for helping on this issue.



Monday, September 1, 2014

Qlikview Scan folder for Files & Reload Data from Scanned Files

Most of the business implementation - works with File Dump into folders - By Specific Naming Conventions - By Month.
Below script helps to Scan & Reload specific Source files into QlikView.

/////////////////////////////////////////////////////////////////////////////
///$(Loop ForeCast)
/*
Directories that should be scanned for qvw files.
One directory per line. Paths may be local or UNC ( \\server\shareName\Dir\file ) paths.
*/
DirectoriesToScan:
LOAD * INLINE [
Dirspec
C:\QlikView\DataSources\Excel\Forecast
]
;
/////////////////////////////////////////////////////////////////////////////
/*
Subroutine to scan directories and load stats about qvw files.
*/
SUB doDir (dir)
FOR EACH file in filelist('$(dir)' &  '\*.xlsx') // Excel 2007 Formats only :: xlsx

Files:
LOAD *
,$(#SCRIPT_START) - FileTime as FileAge
 where len(FileName)='21'; // Valid File Name "2014 07 Forecast.xlsx"
LOAD '$(file)' as FilePath
,FileSize('$(file)') as FileSize
,FileTime('$(file)') as FileTime
,subfield('$(file)', '.', -1) as FileExtension
,subfield('$(file)', '\', -1) as FileName
,subfield(subfield('$(file)', '.', 1),'\',-1) as FileBaseName
AUTOGENERATE 1
;
NEXT
FOR EACH subdir in dirlist( '$(dir)' & '\*.xlsx' )
  CALL doDir('$(subdir)')
NEXT
END SUB

SUB doRoot (root)
FOR EACH subdir in dirlist( '$(root)' )
 CALL doDir('$(subdir)')
NEXT
END SUB

/////////////////////////////////////////////////////////////////////////////
/*
Call the scanning sub for each directory specified in the Configuration tab.
*/
FOR i = 0 to FieldValueCount('Dirspec')
Call doRoot(FieldValue('Dirspec',$(i)));
NEXT i
DROP Table DirectoriesToScan;
/////////////////////////////////////////////////////////////////////////////

FOR i = 0 to FieldValueCount('FilePath')
if(len(FieldValue('FilePath',$(i)))>0) then
Call Forecast_Exctract(FieldValue('FilePath',$(i)));
ENDIF;
NEXT i

/////////////////////////////////////////////////////////////////////////////
///$(QVD_Extractor)
//Remeber to place Sub - before Call functions
sub Forecast_Exctract(vFile_Path)

LET vFileBaseName=subfield(subfield('$(vFile_Path)', '.', 1),'\',-1);
Let vQVDName='C:\QlikView\DataSources\QVD\Forecast\$(vFileBaseName).qvd';

TRACE '$(vFile_Path)';
Forecast_RAW:
LOAD FileBaseName() as Forecast_Source,
*
FROM
'$(vFile_Path)'
//[..\DataSources\Excel\Forecast\2014 07 Forecast.xlsx]
(ooxml, no labels, header is 3 lines, table is [Forecast], filters(
Transpose(),
Replace(3, top, StrCnd(null)),
Transpose()
));

STORE Forecast_RAW into $(vQVDName)(qvd);
DROP Table Forecast_RAW;
end sub
/////////////////////////////////////////////////////////////////////////////
--
Thanks to QlikView Community posts & Robwunderlich - File Monitoring application

//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// 
//////////////////////////////////////// MINI VERSION //////////////////////////////////////// 

  1. Sub ScanFolder(Root)  
  2.           for each FileExtension in 'xlsx'  
  3.               for each FoundFile in filelist( Root & '\*.' & FileExtension)  
  4.                  FileList:  
  5.                  Load  Subfield('$(FoundFile)','\',5) as Filename,  
  6.                        Subfield(Subfield('$(FoundFile)','\',5),'_',2) as Market,  
  7.                        Subfield(Subfield('$(FoundFile)','\',6),'_',3) as Unit  
  8.                               Autogenerate(1);  
  9.                     next FoundFile  
  10.           next FileExtension  
  11.           for each SubDirectory in dirlist( Root & '\*' )  
  12.                     call ScanFolder(SubDirectory)  
  13.           next SubDirectory  
  14. End Sub  
  15.   
  16. Call ScanFolder('C:\Users\Tamil\Desktop\Test') ;  
//////////////////////////////////////// //////////////////////////////////////// ////////////////////////////////////////