Understanding Delegates

A delegate is a type in C# that represents a reference to a method. It allows you to pass methods as arguments to other methods or assign them to variables. Here’s a simple example to demonstrate how a delegate works:

using System;

delegate int MyDelegate(int x, int y);

class Program
{
    static int Add(int x, int y)
    {
        return x + y;
    }

    static int Multiply(int x, int y)
    {
        return x * y;
    }

    static void Main(string[] args)
    {
        // create delegate instances
        MyDelegate addDelegate = new MyDelegate(Add);
        MyDelegate multiplyDelegate = new MyDelegate(Multiply);

        // use delegate instances to call the methods
        int result1 = addDelegate(5, 3); // returns 8
        int result2 = multiplyDelegate(5, 3); // returns 15

        // output the results
        Console.WriteLine($"Add: {result1}");
        Console.WriteLine($"Multiply: {result2}");
    }
}

In this example, we first define a delegate type MyDelegate that takes two integers as parameters and returns an integer. Then, we define two static methods Add and Multiply that match the delegate signature.

In the Main method, we create two delegate instances addDelegate and multiplyDelegate that reference the Add and Multiply methods respectively. We then use these delegate instances to call the methods and store the results in result1 and result2. Finally, we output the results to the console.

By using delegates, we can pass methods as arguments to other methods, allowing for greater flexibility and extensibility in our code.

C# How to calculate the IRR.

namespace IRRCalc
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double[] cashFlows = { -1000, 200, 300, 600 };
            double irr = IRR(cashFlows);
            Console.WriteLine("The IRR is: " + irr.ToString("0.##%"));
        }

        static double IRR(double[] cashFlows)
        {
            double accuracy = 0.0001;
            double x1 = 0.0;
            double x2 = 1.0;

            while (Math.Abs(NPV(x2, cashFlows)) > accuracy)
            {
                double x3 = (x1 + x2) / 2;

                if (NPV(x3, cashFlows) * NPV(x1, cashFlows) < 0)
                    x2 = x3;
                else
                    x1 = x3;
            }

            return (x1 + x2) / 2;
        }

        static double NPV(double rate, double[] cashFlows)
        {
            double npv = 0;
            for (int i = 0; i < cashFlows.Length; i++)
            {
                npv += cashFlows[i] / Math.Pow(1 + rate, i);
            }
            return npv;
        }

    }
}

Simple program to calculate the IRR

CTE in SQL Server

A Common Table Expression (CTE) in SQL Server is a feature that allows you to create a temporary result set that can be referred to within a SELECT, INSERT, UPDATE, or DELETE statement. The CTE is defined using the WITH clause and is followed by a SELECT, INSERT, UPDATE, or DELETE statement. The SELECT statement defines the structure of the CTE and the SELECT, INSERT, UPDATE, or DELETE statement that follows it can reference the CTE.

A CTE is useful for breaking down a complex query into simpler parts, making it easier to read and understand. It can also be used to simplify the process of querying hierarchical data, such as an organizational chart.

Here is an example of a CTE that is used to calculate the total sales for each product category:

WITH SalesCTE (Category, TotalSales)
AS
(
    SELECT Category, SUM(Sales)
    FROM Products
    GROUP BY Category
)
SELECT Category, TotalSales
FROM SalesCTE

In this example, the subquery is embedded in the SELECT statement and calculates the total sales for each category. This can be less readable than a CTE and can be more complex if there are multiple subqueries. It is important to note that CTEs are only visible to the query immediately following the WITH clause and it is not stored in the database like a table, so it is not accessible to other queries or sessions.

SQL Server Trigger

A trigger is a special type of stored procedure that automatically executes in response to certain events on a table or view in a SQL Server database. Here is an example of a trigger that updates the “testEmployee” table whenever a new employee is inserted:

In this example, the trigger is named “UpdateEmployees” and is set to execute on the “testEmployee” table. The “AFTER INSERT” clause specifies that the trigger should fire after a new row has been inserted into the table.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE dbo.testEmployee
(EmployeeId Int identity (1,1),
FirstName NVARCHAR(100),
LastName NVARCHAR(100),
Salary Decimal(12,2),
InsertDate DATETIME CONSTRAINT DF_TS_UTC1 DEFAULT GETUTCDATE(),
UpdateDate DATETIME CONSTRAINT DF_TS_UTC2 DEFAULT GETUTCDATE()
)
GO


CREATE TRIGGER [dbo].[UpdateEmployees]
ON [dbo].[testEmployee]
AFTER INSERT
AS
BEGIN
    UPDATE testEmployee
    SET Salary = Salary * 1.1
    WHERE EmployeeID IN (SELECT EmployeeID FROM inserted)
END
GO

The code inside the trigger updates the salary of any employee that was just inserted by multiplying their current salary by 1.1. The “inserted” virtual table is used to reference the newly inserted rows and the “WHERE” clause filters the update to only apply to rows whose EmployeeID is present in the inserted table.

This trigger will run automatically every time a new employee is inserted into the testEmployee table and update their salary by 10%.

Harshad Numbers

Today, I was describing Harshad Numbers to my son. He is 6 years old. Then he asked if it would be possible to get all the Harshad Numbers between 1 and 226.
I said, yes but with help from the computer.


"""
Calculate harshad numbers in a loop
"""
TOTALCNT = 0
for number in range(1, 226):
sumval = sum(map(int, str(number)))
if number % sumval == 0:
TOTALCNT = TOTALCNT + 1
print "{0} is harshad number".format(number)
print "{0} total number of harshad numbers in the range of 1 - 226".format(TOTALCNT)

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

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);