Thursday, December 19, 2013

How to flush DNS cache in Mac

The Mac equivalent of ipconfig /flushdns in Windows is as follows.


In Mavericks (OSX 10.9):

dscacheutil -flushcache; sudo killall -HUP mDNSResponder



In Lion (OSX 10.7) and Mountain Lion (OSX 10.8):

sudo killall -HUP mDNSResponder


In OSX 10.5 and 10.6

dscacheutil -flushcache


Friday, November 15, 2013

jQuery - this vs $(this)

The difference between this and $(this) is well explained in this StackOverflow answer ( link ).


In Summary,

$(this)[0] == this;

Of course, $(this) gets all the nice jQuery functions and properties, whereas this is javascript keyword.

Also, the author of the answer makes an intuitive point for the jQuery selector that "jQuery selector always returns array.

$('#MyUniqueDiv')[0]  == document.getElementById('MyUniqueDiv');



Even if there is only a single div with id="MyUniqueDiv" in the DOM, the following is still true.

$('#MyUniqueDiv')[0] == $('#MyUniqueDiv');




Wednesday, November 13, 2013

Extension Method explained by Scott Guthrie

Extension method is something that I find easy to forget from time to time. Scott Guthrie nicely explains it in his blog back in 2007.  All source code below comes from his blog.

using System;
using System.Text.RegularExpressions;
namespace SGExtensions
{
  public static class ScottGuExtensions
  {
    public static bool IsValidEmailAddress( this string s )
    {
      Regex regex = new Regex( @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$" );
      return regex.IsMatch( s );
    }
  }
}

The this keyword before the string type argument s tells the compiler that this Extension Method should be added to objects of type string .


The above  Extension Method can be applied as follows.
//namespace containing Extension Method Implementation
using SGExtensions; 
...
string email = Request.QueryString["email"];
if( email.IsValidEmailAddress() )
{
  ...
}

Another example of Extension Method....

using System;
using System.Collections;

namespace SGExtensions
{
  public static class ScottGuExtensions
  {
    public static bool In( this object o, IEnumerable c )
 {
   foreach( object i in c )
   {
     if( i.Equals( o )
  {
    return true;
  }
   }
   return false;
 }
  }
}

In the above example, the first parameter to the Extension Method "this object o" indicates that this Extension Method should be applied to all types that derive from the base System.Object base type. Basically, every object in .NET.


This "In( )" method allows to check to see whether a specific object is included within an IEnumerable sequence passed as an argument to the method. Because all .NET collections and arrays implement the IEnumerable interface, the "In( )" method could be a useful and descriptive method for checking whether any .NET object belongs to any .NET collection or array.


The following example uses the "In( )" method.

using system;
using SGExtensions;
s public class Test1
{
  void Test()s
  {
    string[] values = {"Microsoft", "Apple", "FaceBook"};
 bool isInArray = "Google".In( values ); // false
  }
}


using System;
using SGExtensions;
public partial class TestPage : System.Web.UI.Page
{
  void Page_Load()
  {
    if ( TextBox1.In( form1.Controls ) )
 {
   ...
 }
  }
}


using SGExtensions;
...
int [] values = { 0, 4, 5, 9, 42 };
int testValue = 45;
bool isInArray = testValue.In( values ); // false
bool isInArray2 = 42.In( values );       // true

Tuesday, November 12, 2013

Iterating files in a folder based on file extensions using LINQ

Using LINQ, iterating through specific files based on file extensions in a directory can be somewhat simplified.


using System.Linq;
using System.IO;
...

string fileExtensions = ".pdf, .tif, .jpg, .bmp";
string [] fileExtensionArray
    fileExtensions.split(',').Select(e => e.Trim().ToLower()).ToArray();

DirectoryInfo di = new DirectoryInfo("C:\\myDir");
FileInfo[] fileInfoArray = 
    di.GetFiles()
        .Where(f => fileExtensionArray.Contains(f.Extension.ToLower()))
        .ToArray();
...
foreach( var item in fileInfoArray )
{
    string fileFullPath = item.FullName;
    // Perform your work with the desired file here.
}



Monday, November 11, 2013

Login prompt keeps coming when developing Intranet MVC4 Website on IIS Express

I created a MVC 4 project using Visual Studio 2012 on Windows 7 Computer that is a standalone and not a member of an Active Directory domain. I selected the intranet application template for the MVC4 application in Visual Studio 2012, successfully created initial aplication with no error and adjusted project property settings as the initial ReadMe.txt file showed (i.e., Anonymous Authentication = Disabled, Windows Authentication = Enabled).

However, when running the website using IIS Express, the Login Prompt keeps coming up. I thought this nuisance was due to the fact that my computer was not a member of any domain and therefore, the browser is not treating my request as intranet traffic. When I enter my local Windows user name and password, the IIS Express lets me in and I see my MVC4 website loaded in IE properly. Still, having to enter my credential each time I press Ctrl + F5 is a nuisance to take care of for my productivity.


Workaround: 
  1. Run IE. Go to [Tools] --> [Internet Options] menu. Select [Security] tab.
  2. Choose [Trusted Sites] and click the [Sites] button.
  3. Add "http://localhost" to your trusted website. Click [close] button.
  4. When back to the [Security] tab, make sure the [Trusted sites] is still selected. 
  5. Click [Custom level...] button while under the [Trusted sites] context. 
  6. Scroll down to "User Authentication". Select "Automatic logon with current user name and password"

Through another test, I confirmed that when you develop a intranet website using VS 2012 and IIS Express on a computer that is a member of an Active Directory domain, you do not run into this issue of unnecessary login prompt. This issue only happens when you develop on a stand-alone Windows machines.


Tuesday, October 29, 2013

ActiveX Script Task in SSIS 2005 and 2008

ActiveX Script Task in SSIS requires the following library to be registered manually using regsvr32.exe on the Windows OS that runs SQL Server.

Otherwise, the SSIS package may fail when it is run as a SQL Server job.


[SQL Server 2005]
regsvr32.exe "C:\Program Files\Microsoft SQL Server\90\COM\AXSCPHST90.DLL"



[SQL Server 2008]
regsvr32.exe "C:\Program Files\Microsoft SQL Server\100\COM\AXSCPHST.DLL"


Another element of surprise to keep in mind is to try configuring the SSIS package to run in 32-bit mode. I realize that SSIS Task such as Excel Destination would only work when run in 32-bit mode. 


When you create a SQL 2008 SSIS package on 64-bit Windows 7, for example, the SSIS package defaults to 64-bit environment (as well as .NET Framework 2.0). You can change these default settings in the property section of either at the Task-scope or project-scope.


Of course, if you choose to use 32-bit environment when you complete your SSIS package, you'd have to run the SQL Server job that runs the SSIS package in 32-bit mode as well. You can set this option in the job properties window.


Monday, October 28, 2013

Convert a DataTable Column into String Array

Suppose there is a single column DataTable with user names. In order to convert the data in this column into a string array you can do it in for-loop and LINQ approaches.


For-Loop approach:

int columnIndex = 0; //single-column DataTable
string[] userArr = new string[dt.Rows.Count];
for( int i = 0; i < dt.Rows.Count; i++)
{
    userArr[i] = dt.Rows[i][columnIndex].ToString();
}


LINQ approach 1:

int columnIndex = 0; // single-column DataTable
var userArr = dt.Rows.Cast()
                     .Select(row => row[columnIndex].ToString())
                     .ToArray();


LINQ approach 2:

int columnIndex = 0; // single-column DataTable
List userList = new List();
foreach( DataRow row in dt.Rows )
{
    userList.Add( row[columnIndex].ToString() );
}



How to check CentOS version

In order to check current version of CentOS, try the following.

>  cat /etc/*release*

You will see the version similar to the following.

CentOS release 6.4 (Final)
LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
cat: /etc/lsb-release.d: Is a directory
CentOS release 6.4 (Final)
CentOS release 6.4 (Final)
cpe:/o:centos:linux:6:GA


Or more specifically...

cat /etc/centos-release

This will show just the version number as follows.

CentOS release 6.4 (Final)



Thursday, October 24, 2013

Cannot find server certificate with thumbprint error ... TDE error

Situation 

  1. Primary SQL Server's database has TDE (Transparent Data Encryption) enabled and encrypted with Master key (private key). 
  2. The database backup has been made and backup file was copied to a secondary SQL Server. 
  3. When restoring the database on a secondary SQL Server, "Cannot find server certificate with thumbprint error" happens.
Solution:

1. Backup the certificate with master key on the Primary Server
  • BACKUP CERTIFICATE  [EncryptionCertificate]
    TO FILE = 'Certificate File path'
    WITH PRIVATE KEY (FILE = 'Master Key File path.dat', ENCRYPTION BY PASSWORD ='password')

2. Restore the certificate with master key password on the Secondary Server
  • CREATE CERTIFICATE [EncryptionCertificate]
    FROM FILE='Certificate File path'
    WITH PRIVATE KEY ( FILE =  'Master Key File path.dat' , DECRYPTION BY PASSWORD ='password')

To find a file in Linux by name

For example, to find a file "pg_hba.conf" in CentOS


Method 1
>  cd /
>  sudo find . -depth | grep -i pg_hba.conf


Method 2
> cd /
>  sudo updatedb
>  sudo locate pg_hba.conf



To check if postgresql is running

To check if PostgreSQL service is running on Linux on CentOS:


/sbin/service postgresql status

or

/sbin/init.d/postgresql status

or

ps | grep -i pgsql



Friday, August 16, 2013

PowerShell - Copy files that contain square brackets in file name.

I tried to copy all mp3 files in iTunes music folder's subfolders onto another folder without subfolder structures. This was relatively straightforward task until I ran into files that contain square brackets in file names (i.e., "Tom's Diner [1990].mp3").  For example,

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes media\Music\" -Recurse
$newFolder = "C:\Users\John Doe\My Documents\MusicTemp\"
$foreach( $item in $folderItems )
{
    if( $item.Attributes -eq "Archive" )
    {
        Copy-Item $item.FullName $newFolder
    }
}

The code above kept failing due to PowerShell's de-escaping the strings multiple times internally and using special characters for pattern matching. Getting PowerShell to correctly recognize a literal square bracket in a path string turned out to be more complex than I thought.

I googled around and found a suitable workaround for this problem. Basically you would have to escape both open-square-bracket "[" and close-square-bracket "]" with backtick characters "`".

When using single-quote for string, two backticks are needed in front of a bracket in the string.
For double-quoted string, four backticks are needed in front of a bracket in the string.

The workaround PowerShell script is show below. I used double backticks to properly escape the square brackets.

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes Media\Music\" -Recurse
$newFolder = "C:\Users\Jone Doe\Music\iTunes\iTunes Media\MusicTemp\"
foreach($item in $folderItems)
{
    if( $item.Attributes -eq "Archive")
    {        
       $escapedFullName = $item.FullName.Replace('[', '``[').Replace(']', '``]')
       Copy-Item $escapedFullName $newFolder       
    }    
}

Here is the link that I got the workaround idea from.



Wednesday, August 7, 2013

CentOS - how to change computer name and static IP address (network settings)

To update computer name (hostname) and IP Address in CentOS, edit the following files.

  • Computer Name (host name)
    /etc/sysconfig/network
  • IP Address and other network settings
    /etc/sysconfig/network-scripts/ifcfg-eth0  (or similar file)

Reboot the computer afterwards.