Monday, May 14, 2012

Quick way to generate RSA key with LinqPad

To generate private RSA key, we can use LinqPad Expression Executing below expression, will generate RSA key in result window.

new System.Security.Cryptography.RSACryptoServiceProvider (1024).ToXmlString (true) 

if needed, press F4 to add reference, and add reference to System.Security.dll

In Powershell
$rsa = New-Object  System.Security.Cryptography.RSACryptoServiceProvider (1024);
public key
$rsa.ToXmlString($false)
private key
$rsa.ToXmlString($true)

Monday, April 9, 2012

Powershell Find large images

Save the below code in red to .psm1 file eg. ImageFilter.psm1 and then issue following command in powershell console: Import-Module .\ImageFilter.psm1

then you can call the GetFilteredImages function, all params are optional

eg. GetFilteredImages -path c:\temp -exportFile test.txt -width 600 -height 600


*********************************************

Add-Type -Assembly System.Drawing


Function GetFilteredImages
{
Param(
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[String]
$path = (Get-Location -PSProvider FileSystem).ProviderPath
,
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[String]
$exportFile = "$path\result.csv"
,
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[Int]
$width = 1000
,
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[Int]
$height = 500
)
Process
{
Try
{
Get-ChildItem -Path $path -Recurse -Include *.jpg, *.png, *.gif |
ForEach-Object {
$Image = [System.Drawing.Image]::FromFile($_.FullName)
New-Object -TypeName System.Management.Automation.PSObject -Property @{
Name = $_.Name
Length = $_.Length
Width = $Image.Width
Height = $Image.Height
Fullname = $_.Fullname
}| Where-Object { $_.Width -gt $width -and $_.Height -gt $height}
$Image.Dispose()
} | Select-Object Name, Height, Width, Length, FullName| Export-Csv -NoTypeInformation -Path $exportFile
}
Catch
{
write-warning "Error : $($_.Exception.Message)"
}
}
}

Thursday, February 17, 2011

Get single record per group in Foxpro

SELECT f.* from (SELECT country, min(id) as MinId FROM mytable GROUP BY country) as X INNER JOIN mytable as f ON f.country = x.country AND f.id = x.MinId order BY f.country

Monday, January 31, 2011

id of selected RadioButton

To get ID of Selected RadioButton using jQuery (change nameOfRadio to actual radio name)
var id = $("input:radio[name=nameOfRadio ]:checked").attr('id');

Thursday, October 14, 2010

Luhn Checksum in Foxpro

Based on Excel Vba from http://www.excelforum.com/excel-programming/482390-excel-vba-calculating-checksums.html

?IsLuhnChecksumOK("0000000000000000")
Function IsLuhnChecksumOK(Number_String)
Local Digit
Local i
Local N
Local Result
Local SumDigits
Local nDigits
N = 0
SumDigits = 0
nDigits = Len(Number_String)
For i = nDigits To 1 Step -1
Digit = Val(Substr(Number_String, i, 1))
N = N + 1
If Mod(N , 2) = 0
Digit = Digit * 2
Endif
If Digit > 9
Digit = Digit - 9
Endif
SumDigits = SumDigits + Digit
Next i
Result = Mod(SumDigits ,10)
Return Result = 0
Endfunc

Function GetLuhnCheckDigit(Number_To_Check)
Local J As Integer
Local X
X = IsLuhnChecksumOK(Number_To_Check)
If X = False Then
For J = 0 To 9
X = IsLuhnChecksumOK(Bitand(Number_To_Check , J))
If X = True
*'Check digit found
*GetLuhnCheckDigit = J
Return J
Endif
Next J
Else
*'No check digit needed returns -1
Return -1
Endif
Endfunc

Friday, October 1, 2010

NHibernate.Driver.SQLite20Driver Exception

To fix below error, make sure to add reference System.Data.Sqlite and Copy Local = True in the properties window.


FluentNHibernate.Cfg.FluentConfigurationException : An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.

* Database was not configured through Database method.

----> NHibernate.HibernateException : Could not create the driver from NHibernate.Driver.SQLite20Driver.
----> System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
----> NHibernate.HibernateException : The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use element in the application configuration file to specify the full name of the assembly.

Tuesday, July 27, 2010

Excel last row column

lnLastRow = loExcel.activesheet.UsedRange.ROWS.COUNT
lnLastCol = loExcel.activesheet.UsedRange.COLUMNS.COUNT

Monday, July 26, 2010

Excel Fit to page using Foxpro Automation

loExcel.ActiveSheet.PageSetup.Zoom = .f.
loExcel.ActiveSheet.PageSetup.FitToPagesWide = 1
loExcel.ActiveSheet.PageSetup.FitToPagesTall = 1

Wednesday, July 29, 2009

Resize dbf column length to maximum content length

lnSelect = SELECT()
lcAlias = ALIAS()
USE DBF() EXCLUSIVE
lnFields = AFIELDS(aa)
FOR i = 1 TO lnFields
lcField = aa[i, 1]
lcType = aa[i,2]
lnOrigLen = aa[i, 3]
IF lcType = 'C'
SELECT MAX(LEN(ALLTRIM(&lcField))) maxlen FROM (lcAlias) INTO ARRAY curlen
lnLen = IIF(curlen = 0, 1, curlen)
IF lnOriglen > lnLen
ALTER table (lcAlias) alter COLUMN (lcField) c(lnLen)
?lcField, curlen
ENDIF
ENDIF
ENDFOR
SELECT (lnSelect)
RETURN

Tuesday, April 14, 2009

Grant Execute Role

Granting execute permissions to all stored procedures in a database

CREATE ROLE db_executor

GRANT EXECUTE TO db_executor


from article on SqlDbaTips.com

Sunday, February 22, 2009

Add jquery to any page

Here's how we can add jQuery to the pages you are viewing


var Head = document.getElementsByTagName('head').item(0);
script = document.createElement("script");
url="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js";
script.src = url;
Head.appendChild(script);

Sunday, January 4, 2009

Linq with text file

DataTable dt = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(
@"SELECT * FROM F:\myvfp\books.csv",
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\;
Extended Properties=""Text;HDR=No;FMT=Delimited"""))
{
da.Fill(dt);
}

var books = from b in dt.AsEnumerable()
select new
{
Title = b.Field<string>(0),
Publisher = b.Field<string>(1),
Year = b.Field<int>(2)
};
foreach (var book in books)
{
Console.WriteLine(string.Format("Title: {0}, Publisher: {1}, Year: {2}", book.Title, book.Publisher, book.Year));
}

Saturday, January 3, 2009

Linq with foxpro table

DataTable dt = new DataTable();
using (OleDbDataAdapter da = new OleDbDataAdapter(@"select title as Title, publisher as Publisher, year as Year from books", @"Provider=VFPOLEDB.1;Data Source=c:\myvfp\"))
{
da.Fill(dt);
}

XElement xml = new XElement("books",
dt.AsEnumerable().Where(book =>
book.Field<int>("Year") == 2006)
.Select(book => new XElement("book",
new XAttribute(
"title",
book.Field<string>("Title")),
new XElement(
"publisher",
book.Field<string>("Publisher"))
))
);
Console.WriteLine(xml);

or

XElement xml = new XElement("books",
from book in dt.AsEnumerable()
where book.Field<int>("Year") == 2006
select new XElement("book",
new XAttribute("title", book.Field<string>("Title")),
new XElement("publisher", book.Field<string>("Publisher")
)));
Console.WriteLine(xml);


Instead of
from book in dt.AsEnumerable()
we can use
from DataRow book in dt.Rows

Wednesday, August 13, 2008

Foxpro Word Automation Replace

The word Macro generates following code to do search and "REPLACE"
With Selection.Find
.Text = "findword"
.Replacement.Text = "replaceword"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With

The above will not work in Foxpro, Foxpro use positional parameters
Function Execute([FindText], [MatchCase], [MatchWholeWord], [MatchWildcards], [MatchSoundsLike], [MatchAllWordForms], [Forward], [Wrap], [Format], [ReplaceWith], [Replace], [MatchKashida], [MatchDiacritics], [MatchAlefHamza], [MatchControl]) As Boolean

To use in Foxpro, we have to provide all paramters in right sequence till "ReplaceWith". We can omit rest of the parameters
Const wdFindContinue = 1

oword.Selection.Find.Execute(tcOriginal, .f., .f., .f., .f., .f., .t., wdFindContinue, .f., tcReplace)

Wednesday, August 6, 2008

SYS(987) Foxpro

Foxpro SYS(987) can be used to return remote Varchar data as ANSI for use with Memo fields.

Remote data with varchar fields in foxpro displays square box between each characters




By setting SYS(987, .T.) the data will be in ANSI format.

The above data now displayed as
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16

Tuesday, July 29, 2008

Open cash register from DOS

type "copy con: open.txt" and press ENTER
press ALT key and hold it
type "27" on your numeric keypad (Numeric Keypad not one above letters )
release ALT key
type "p07y" (small "p" zero seven and small "y"! without quotes)
type Ctrl-z and then Enter

To open the cash register
copy open.txt LPT1:

Wednesday, July 9, 2008

XP SP3 install - Access Denied Error

Windows Update keeps failing on SP3 update with "Access Denied" error. Searching online found this blog.

http://fastest963windows.blogspot.com/2008/05/before-installing-windows-xp-sp3-
access.html

Friday, June 27, 2008

Generate Create Script from existing table in Foxpro

Generate Create Script from existing table in Foxpro

Following code generates sql create table script for table or cursor in current workspace.



FUNCTION GenerateCreateScript
LPARAMETERS tcCursor
LOCAL ARRAY aa[1]
LOCAL lcAlias, lcCursor, lnFields, lcsql, lcfield, lcType, lnlen, lnDecimal, lnI
lcAlias = ALIAS()
IF EMPTY(lcAlias)
RETURN ''
ENDIF

IF EMPTY(tcCursor) OR VARTYPE(tcCursor) # 'C'
lcCursor = SYS(2015)
ELSE
lcCursor = tcCursor
ENDIF
lnFields = AFIELDS(aa)

lcsql = [ create cursor ] + lcCursor + [ (]
FOR lnI = 1 TO lnFields
lcfield = aa[lni, 1]
lcType = aa[lni, 2]
lnlen = aa[lni, 3]
lnDecimal = aa[lni, 4]
lcsql = lcsql + lcfield + ' ' + lcType + [(] + TRANSFORM(lnlen)
IF lnDecimal > 0
lcsql = lcsql + [,] + TRANSFORM(lnDecimal)
ENDIF
lcsql = lcsql + [)]
IF lnI = lnFields
lcsql = lcsql +[ ;] + CHR(13) + CHR(10) + [)]
ELSE
lcsql = lcsql + [ ;] + CHR(13) + CHR(10) + [, ]
ENDIF
ENDFOR

RETURN lcsql
ENDFUNC

Tuesday, June 24, 2008

Save attachment from Outlook using Foxpro

I need to reprint cards which I receive as Excel file in email. I use the following code to save the attachment in my folders


Local loOutlook, loMapi, loFolder, loInbox, loMailItems, loMail
Local lcBadCardsDir, lcSubject, lnAttachments, loAttach, lcAttachFile, lcSaveFile, lnI

lcBadCardsDir = "c:\badcards\"
Clear
loOutlook = Createobject("outlook.application")
loMapi = loOutlook.GetNamespace("MAPI")
loFolder = loMapi.Folders("Imap.gmail.com")
loInbox =loFolder.Folders("Inbox")
loMailItems = loInbox.Items
For Each loMail In loMailItems
lcSubject = loMail.subject
If 'bad card' $ Lower(lcSubject)
lnAttachments = loMail.Attachments.Count
If lnAttachments > 0
For lnI = 1 To lnAttachments
loAttach = loMail.Attachments.Item[lnI]
lcAttachFile =loAttach.filename
?Justext( lcAttachFile)
If Lower(Justext( lcAttachFile)) = 'xls'
lcSaveFile = lcBadCardsDir + lcAttachFile
loAttach.saveasfile(lcSaveFile )
Endif
Endfor
Endif
Endif
Endfor
loMail = Null
loMailItems = Null
loInbox = Null
loFolder =Null
loMapi = Null
loOutlook = Null

Wednesday, June 18, 2008