Copy-Item causes empty directories.

I wanted to copy all the files from one folder to another folder. This is a trivial task for Powershell, but I kept getting it wrong.

Here is my original INCORRECT script.

$source = "C:\GotSource"
$dest = "C:\GOTDest"
Copy-Item -Path $source -Destination $dest -Filter *.jpg -Force

What this script ended up doing was create an empty folder under c:\GotDest named c:\GotSource

So I fixed the script by piping the output of Get-Item to Copy-Item. That fixed the issue.

This is my corrected script.

$source = "C:\GotSource"
$dest = "C:\GOTDest"
#Copy-Item -Path $source -Destination $dest -Filter *.jpg -Force
Get-ChildItem $source -recurse -filter "*.jpg" | Copy-Item -Destination $dest

Advertisements

LINQ for newbies

Please remember that there are 2 separate syntax for LINQ.

The query syntax and the method syntax.

The query syntax reminds me of SQL.

example:

from c in Customers where c.State == “FL” select c;

The method syntax is chaining different functions together. It is also shorter and more fun to write.

Customers.Where(c => c.State == “FL”)

requests library

There is a library in python called requests. If you aren’t using it, then you definitely should. I have been using it as a replacement for the web service calls I make using SoapUI. SoapUI has a scripting language called groovy and it comes with a number of features. I find that all my test scripts are now being created using python. It has definitely simplified my work.

So this library is a great tool in order to make any kind of HTTP calls from your script. It can make Soap and REST based calls.

Simple-Salesforce

I cannot rave enough about this wonderful library. Combined with another library called Faker, I have been able to create scripts that can generate any number of leads for the purpose of testing. Testing is an often ignored area by developers and business users alike.

I am still working on python 2 and this is what I wrote.

import time
import os, random, string
import json
from faker import Factory
import datetime
from datetime import timedelta
from simple_salesforce import Salesforce
sf = Salesforce(username='myprogrammingexp@wordpress.com', password='NOTMYREALPASSWORD', security_token='NOTATOKEN', sandbox=False, version='38.0')

fake = Factory.create("en_US")
for i in range(1,100):
fk = fake
l = sf.Lead.create({'Address_1__c': fk.street_address(),
'City': fk.city(),
'Company': fk.company(),
'Delivery_Addresss__c': fk.street_address(),
'Delivery_City__c': fk.city(),
'Delivery_State__c': fk.state(),
'Delivery_Zip__c': fk.zipcode(),
'Email': fk.email(),
'Expected_Delivery_Date__c': d.strftime(fmt),
'FirstName': fk.first_name(),
'LastName': fk.last_name(),
'LeadSource': 'Facebook.com',
'Phone': fk.phone_number(),
'campaign_source__c':'(not set)',
'campaign_medium__c':'(not set)',
'name_campaign__c':'(not set)',
'campaign_content__c':'(not set)',
'campaign_keyword__c':'(not set)',
'client_id__c':str(int(time.time()+300)),
'hit_id__c':str(int(time.time()+300)),
'session_id__c':str(int(time.time()+300))
})
print l['id']

How to call a webservice using Http in SalesForce.

This works in the Execute Anonymous Window of the Developer Console.

public HttpRequest req= new HttpRequest();
        String strPost = '<soapenv:Envelope xmlns:soapenv=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:soap=\'http://peopleask.ooz.ie/soap\'>'+ '   <soapenv:Header/>'+ '   <soapenv:Body>'+ '      <soap:GetQuestionsAbout>'+ '         <soap:query>Shiva</soap:query>'+ '      </soap:GetQuestionsAbout>'+ '   </soapenv:Body>'+ '</soapenv:Envelope>'; 
        system.debug(strPost);
        req.setMethod('POST'); 
        req.setHeader('content-type', 'text/xml; charset=utf-8');  
        req.setHeader('SOAPAction', 'http://peopleask.ooz.ie/soap/GetQuestionsAbout'); 
        req.setTimeout(60000);
        req.setBody(strPost );
        req.setEndpoint('http://peopleask.ooz.ie/soap'); 
        Http http = new Http();
        SimpleXMLParser.ReturnObject xmlparserError = new SimpleXMLParser.ReturnObject();
        //Send the request, and return a response 
        System.debug('Request sent: ' + req.getBody());
        HttpResponse resObj = new HttpResponse();
        String response = '';
        // Send the request, and return a response
        resObj = http.send(req); 
        response = resObj.getBody();
        System.debug(response);

Native Auditing Features in SQL Server.

How do you find out if there have been some changes made to the database records? You institute an audit on the table. How do you institute an audit? In the early beginnings of RDBMS, you could use a trigger. This is how things were done and sometimes they still are.

CREATE TABLE [dbo].[cp_user] 
  ( 
     [customer_id] [INT] IDENTITY(1, 1) NOT NULL PRIMARY KEY, 
     [user_id]     [NVARCHAR](50) NOT NULL, 
     [password]    [NVARCHAR](300) NULL, 
     [first_name]  [NVARCHAR](50) NOT NULL, 
     [last_name]   [NVARCHAR](50) NOT NULL 
  ) 

go 

CREATE TABLE [dbo].[cp_user_log] 
  ( 
     [audit_log_id]  [INT] IDENTITY(1, 1) NOT NULL PRIMARY KEY, 
     [customer_id]   [INT] NULL, 
     [user_id]       [NVARCHAR](50) NOT NULL, 
     [password]      [NVARCHAR](300) NULL, 
     [first_name]    [NVARCHAR](50) NOT NULL, 
     [last_name]     [NVARCHAR](50) NOT NULL, 
     [log_reason]    [NVARCHAR](1) NOT NULL, 
     [logon_user_id] [NVARCHAR](100) NOT NULL 
  ) 

go 

CREATE TRIGGER [dbo].[tr_cp_user_D] 
ON [dbo].[cp_user] 
FOR DELETE 
AS 
    INSERT INTO dbo.cp_user_log 
                ([customer_id], 
                 [user_id], 
                 [password], 
                 [first_name], 
                 [last_name], 
                 [log_reason], 
                 [logon_user_id]) 
    SELECT [customer_id], 
           [user_id], 
           [password], 
           [first_name], 
           [last_name], 
           'D', 
           User_name() 
    FROM   deleted 

go

Newer versions of database allowed native auditing capabilities, so all this trigger writing could be avoided.
From SQL Server 2000, there was C2 auditing.You can read more on C2 auditing here.

USE  master
GO
EXEC sp_configure 'show advanced option', '1'
Go
RECONFIGURE
GO
--Turn it On
exec sp_configure 'c2 audit mode', 1
go
RECONFIGURE
GO
--Turn it Off
exec sp_configure 'c2 audit mode', 0
go
RECONFIGURE
GO

In order to read this audit log, you would have to run a query on the audit file. The audit files are stored in the Data Folder on MSSQL installation.

SELECT *
 FROM ::fn_trace_gettable(
   'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MIG42DT\MSSQL\DATA\audittrace20140527103256.trc', default
	)
	ORDER BY [StartTime] DESC
GO

Since 2008 Sql Server has added another feature to its arsenal. It allows you to have a database specific audit using native tools. This is how you do it. More information can be found here

USE [master]
GO

/****** Object:  Audit [TestingAudit]    Script Date: 05/27/2014 11:48:46 ******/
CREATE SERVER AUDIT [TestingAudit]
TO FILE 
(	FILEPATH = N'C:\app\sqlserverauditlogs\'
	,MAXSIZE = 300 MB
	,MAX_ROLLOVER_FILES = 100
	,RESERVE_DISK_SPACE = OFF
)
WITH
(	QUEUE_DELAY = 1000
	,ON_FAILURE = CONTINUE
	,AUDIT_GUID = '49c0e7ee-16f7-42da-bffb-57a6f26a6141'
)
GO

USE [abs4]
GO

CREATE DATABASE AUDIT SPECIFICATION [TestingDBChanges]
FOR SERVER AUDIT [TestingAudit]
ADD (DELETE ON DATABASE::[abs4] BY [public]),
ADD (EXECUTE ON DATABASE::[abs4] BY [public]),
ADD (INSERT ON DATABASE::[abs4] BY [public]),
ADD (RECEIVE ON DATABASE::[abs4] BY [public]),
ADD (REFERENCES ON DATABASE::[abs4] BY [public]),
ADD (SELECT ON DATABASE::[abs4] BY [public]),
ADD (UPDATE ON DATABASE::[abs4] BY [public])
WITH (STATE = ON)
GO

You can lookup the logs using the View Audit Logs option

Adding a computed column on an existing table in Sql Server 2008 R2

I have a scenario where a player table containing birth dates exists in the database. I need to add a column called AGE that will display the age of a player in the query. So I added a computed column to the existing table. Here’s my code.

CREATE TABLE [dbo].players 
  (
     player_id    INT IDENTITY(1, 1) PRIMARY KEY, 
     handle       NVARCHAR(20) NOT NULL, 
     first_name   NVARCHAR(100) NOT NULL, 
     last_name    NVARCHAR(100), 
     date_of_birthDATE NOT NULL 
  );

alter table players
ADD[age] AS DATEDIFF(YYYY,date_of_birth,getdate());

Writing relational SQL data as XML

How can you get XML from SQL Server? The FOR XML methods allow you do this.
This is a simplified example of what you need to do.

Sql Server Code:

CREATE TABLE parent
  (
     parent_id   INT IDENTITY PRIMARY KEY,
     parent_name NVARCHAR(100)
  );

CREATE TABLE child
  (
     child_id   INT IDENTITY PRIMARY KEY,
     parent_id  INT REFERENCES parent(parent_id),
     child_name NVARCHAR(100)
  );

INSERT INTO parent
            (parent_name)
VALUES     ('JOHN');

INSERT INTO parent
            (parent_name)
VALUES     ('TOM');

INSERT INTO parent
            (parent_name)
VALUES     ('STACY');

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (1,
            'Emily')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (1,
            'Ryan')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (2,
            'Krusna')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (2,
            'Uma')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (2,
            'Kali')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (3,
            'Jimbo')

INSERT INTO child
            (parent_id,
             child_name)
VALUES     (3,
            'Howard')

SELECT parent.parent_id   AS "@parentId",
       parent.parent_name AS "@parentname",
       (SELECT child_id   AS "@childId",
               child_name AS "@childName" FROM child WHERE child.parent_id = parent.parent_id
        FOR xml path ('Child'), type)
FROM   parent 
FOR xml path ('Parent'), root ('Container'), type

Random Dates in Sql Server

One of our testing requirements for queries requires us to generate random dates in a table.
This is my solution.
Since the introduction of table valued parameters, I believe SQL Server has made developer’s lives a little bit easier.

The first step is to create a type in the database.

--Create table type for dates and integers
CREATE TYPE DBO.mydatesandintegers AS TABLE
	(	nu int NOT NULL PRIMARY KEY, 
		dt DateTime NULL)

Then I make use of the random function to generate a random number. I use this number as parameter to the date add function. Several variations are possible here.

DECLARE @myint mydatesandintegers, @i int = 0
begin
while @i < 50
	BEGIN
		--SELECT RAND() AS [RandomNumber]
		SET @i = @i + 1
		INSERT @myint(nu, dt) SELECT RAND() * 100000 AS [RandomNumber], 
		DATEADD(mi,RAND() * 1000000 * -1, GETDATE()) /*Date part value can also be changed.*/
	END
	SELECT * FROM @myint
END

How to move a rectangle on a canvas in WPF.

I am currently taking an online course to learn video game programming at coursera.org I am half-way through the course and I decided to do something similar in C# using WPF. This is my first foray in WPF. I might think of seriously converting all the python code into C# WPF if I get enough time on my hands. Here’s a rectangle that bounces on the screen.

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;

namespace Pong
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void DispatcherTimerTick(object sender, EventArgs e) 
        {
            var random = new Random();
            double w = (double) (random.Next(0, (int) canvas.Width));
            double h = (double)(random.Next(0, (int) canvas.Height));
            Canvas.SetLeft(this.Rect, w - (this.Rect.Width / 2));
            Canvas.SetTop(this.Rect, h - (this.Rect.Height / 2));
            
            if (DetectCollision(this.Rect, new Point(w - (this.Rect.Width / 2), h - (this.Rect.Height / 2))))
            {
                ResetPosition();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(DispatcherTimerTick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 10);
            dispatcherTimer.Start();
        }

        private void ResetPosition()
        {
            /*Brings shape to the center of the canvas.*/
            Canvas.SetLeft(this.Rect, (canvas.Width / 2) - (this.Rect.Width / 2));
            Canvas.SetTop(this.Rect, (canvas.Height / 2) - (this.Rect.Height / 2));
        }

        private bool DetectCollision(Rectangle s, Point p)
        {
            if(Canvas.GetLeft(s) > p.X || Canvas.GetTop(s) < p.Y)
            {
                return true;
            }
            else if (Canvas.GetRight(s) < p.X || Canvas.GetBottom(s) > p.Y)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}