Wednesday, March 25, 2015

test remote powershell console is working or not Test-PsRemoting from Lee Holmes

I dont own the post, I dont have any legal rights just a pointer and a replication from the original post. The original post belongs to Mr. Lee Holmes. If someone tells me to pull the post down, I will. I am just reposting this article.

URL :-
http://www.leeholmes.com/blog/2009/11/20/testing-for-powershell-remoting-test-psremoting/

Testing for PowerShell Remoting: Test-PsRemoting

When you’re writing a script that depends on PowerShell Remoting, it’s often helpful to know that the remoting channel is open and will support the activities of your script.
PowerShell has a Test-WSMan command, but that only verifies that a WSMan connection is possible. There are other scenarios you could be impacted by:
  • Not having permission on the remote machine
  • Misconfiguration of the PowerShell endpoint
  • Corrupted installation
  • (etc)
As you dig deeper, you realize that the only way to really test the viability of the remoting channel is to just do something on it, and verify that you got the results you expected to. Since the implementation was so simple, we didn’t write a cmdlet for it. In retrospect, the concept is more difficult than the implementation, so we probably should have written it anyways. Here’s an example function that tests the remoting connection to a specific machine.
function Test-PsRemoting 
{ 
    param( 
        [Parameter(Mandatory = $true)] 
        $computername 
    ) 
    
    try 
    { 
        $errorActionPreference = "Stop" 
        $result = Invoke-Command -ComputerName $computername { 1 } 
    } 
    catch 
    { 
        Write-Verbose $_ 
        return $false 
    } 
    
    ## I’ve never seen this happen, but if you want to be 
    ## thorough…. 
    if($result -ne 1) 
    { 
        Write-Verbose "Remoting to $computerName returned an unexpected result." 
        return $false 
    } 
    
    $true    
}

source: http://www.leeholmes.com/blog/2009/11/20/testing-for-powershell-remoting-test-psremoting/

Wednesday, January 21, 2015

Maximum length nvarchar(max) can accommodate in SQL 2012

The script I wrote :-

declare @str1  as nvarchar(max) = 'b'
, @count as int = 0

while @count<30
BEGIN
       set @str1 = @str1 + @str1
       set @count=@count+1
END
print len(@str1)

print @count

Results :-
1073741824
30


So in conclusion, I could say nvarchar(max) can contain till 1073741824 many characters. I haven't tried more than this. Lots of reference in Internet also says that it can contain 2GB of data and a character is 2 bytes each, which adds up to that number.

Wednesday, January 8, 2014

How to read *.ini file in powershell, ps, c#

if you open up ini file from command prompt using type command or get-content from powershell, the output you get will be sparse with spaces. To avoid this you need to open it in the format it was saved as.

 $iniFile = $env:localappdata+"\Microsoft\Windows\SkyDrive\settings\" + $cid + ".ini"
$text = [system.io.File]::ReadAllText($iniFile, [system.text.Encoding]::GetEncoding("Unicode"));

To open up it other formats reference to this MSDN link :-
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx

Tuesday, August 7, 2012

find-StoredProcedureinDatabase

This code is should be written in powershell console, right click on the database and open powershell console.

This function helps to search for Store Proc Name inside certain database.

function find-StoredProcedureinDatabase($sprocName){
# $ps = "FetchAndProcessLoginData"
$ps = $sprocName
$dbs = dir
foreach($db in $dbs){
    $sps = $db.storedprocedures
    foreach($sp in $sps){
        if($sp.name -ieq $ps){
            $db.name
        }
    }
}
}

Wednesday, August 10, 2011

Creating a dynamic DataTable without knowing what is being returned.

public DataTable executeSQL(string sql)
{
DataTable dt = new DataTable();
sqlcmd = new SqlCommand(sql, new SqlConnection(ConnectionString));
if (sqlcmd.Connection.State != System.Data.ConnectionState.Open)
{
sqlcmd.Connection.Open();
}

SqlDataReader dr = sqlcmd.ExecuteReader();
int fc = dr.FieldCount;

Debug.WriteLine("number of columns : "+fc);

//creating columns in the table
for (int i = 0; i < fc; i++)
{
dt.Columns.Add(dr.GetName(i), dr.GetFieldType(i));
}

//adding rows in the table
while (dr.Read())
{
DataRow drow = dt.NewRow();
for (int i = 0; i < fc; i++)
{
drow[i] = dr.GetValue(i);
}
dt.Rows.Add(drow);
}

sqlcmd.Connection.Close();

return dt;
}

Thursday, March 24, 2011

Creating CAB in C#, windows 7

///These codes are recycled and taken from various places. I also have added some code but there are various references for this code. I don't own the code entirely. I am putting this up for reference only.


/// Creates a cab file, uses makecab.exe that is already in c:\windows\system32
///

/// Path for the cab file with Name. eg "c:\cabinet1.cab"
/// pass the full path and file names needed to be included in the cab as an string array
///
public static string MakeCab(string cabfilePath,string[] filesToInclude)
{
ArrayList sampleddf = new ArrayList ();

sampleddf.Add( ";*** Sample Source Code MakeCAB Directive file example");
sampleddf.Add( ";");
sampleddf.Add( ".OPTION EXPLICIT ; Generate errors ");
sampleddf.Add(".Set CabinetNameTemplate=" + (cabfilePath.Substring ((cabfilePath.LastIndexOf('\\')+1))));
sampleddf.Add( ".set DiskDirectoryTemplate=CDROM ; All cabinets go in a single directory");

sampleddf.Add( ".Set CompressionType=MSZIP;** All files are compressed in cabinet files");
sampleddf.Add( ".Set UniqueFiles=\"OFF\"");
sampleddf.Add( ".Set Cabinet=on");
sampleddf.Add(".Set DiskDirectory1=" + (cabfilePath.Substring(0,(cabfilePath.LastIndexOf('\\')+1))));
foreach (string s in filesToInclude)
{
sampleddf.Add(s);
}
sampleddf.Add(";*** ");

string[] array = sampleddf.ToArray(typeof(string)) as string[];+6
string sampleddfPath = System.IO.Path.GetTempPath() + "sample.ddf";
sampleddfPath = writeTextFile(sampleddfPath, array, Encoding.UTF8, true);

ExecuteCommandSync("makecab.exe /f " + sampleddfPath);

return cabfilePath;
}

///



/// Executes a shell command synchronously.
///

/// string command
/// string, as output of the command.
public static string ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
//Console.WriteLine(result);
return result;
}
catch (Exception objException)
{
// Log the exception
}
return null;
}

public static string writeTextFile(string fpath, string[] lines, Encoding encode, bool overWriteFlag = false)
{
if(overWriteFlag)
{
if (File.Exists(fpath))
{
File.Delete(fpath);
}
}

try
{
File.WriteAllLines(fpath, lines, encode);
return fpath;
}
catch (Exception e)
{
return null;
}
}

Tuesday, March 22, 2011

incorrectly aligned or overlapped by a non-object field

Hi All,

Thanks for taking out time to read this post. Can someone help me with this?

When I try to run this, System.TypeLoadExeception Error appears.
What I am trying to do is, run a native function that is in dll. It requires lots of datatypes namely :-
1) ATTRIBUTE_TYPE
2) DIAG_SOCKADDR
3) LIFE_TIME
4) FILETIME
5) An Union which I have named as “unionForHelpAttribute”
6) HELPER_ATTRIBUTE

The function I am trying to call is NdfCreateIncident

So, when I try to run the code this exception is happening

System.TypeLoadException was unhandled
Message=Could not load type 'unionForHelpAttribute' from assembly 'NDFApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 0 that is incorrectly aligned or overlapped by a non-object field.
Source=NDFApplication1
TypeName=unionForHelpAttribute
StackTrace:
at NDFApplication1.Program.Main(String[] args)
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Here is the source code.


public enum ATTRIBUTE_TYPE
{

/// AT_INVALID -> 0
AT_INVALID = 0,

AT_BOOLEAN,

AT_INT8,

AT_UINT8,

AT_INT16,

AT_UINT16,

AT_INT32,

AT_UINT32,

AT_INT64,

AT_UINT64,

AT_STRING,

AT_GUID,

AT_LIFE_TIME,

AT_SOCKADDR,

AT_OCTET_STRING,
}

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Auto, CharSet=System.Runtime.InteropServices.CharSet.Ansi)]
public struct DIAG_SOCKADDR {

/// USHORT->unsigned short
public ushort family;

/// CHAR[126]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=126)]
public string data;
}


[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Auto)]
public struct LIFE_TIME {

/// FILETIME->_FILETIME
public FILETIME startTime;

/// FILETIME->_FILETIME
public FILETIME endTime;
}

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Auto)]
public struct FILETIME {

/// DWORD->unsigned int
public uint dwLowDateTime;

/// DWORD->unsigned int
public uint dwHighDateTime;
}

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Explicit)]
public struct unionForHelpAttribute{

[System.Runtime.InteropServices.FieldOffset(0)]
public bool Boolean;

[System.Runtime.InteropServices.FieldOffset(0)]
public char Char;

[System.Runtime.InteropServices.FieldOffset(0)]
public byte Byte;

[System.Runtime.InteropServices.FieldOffset(0)]
public short Short;

[System.Runtime.InteropServices.FieldOffset(0)]
//WORD->unsigned short
public ushort Word;

[System.Runtime.InteropServices.FieldOffset(0)]
public int Int;

[System.Runtime.InteropServices.FieldOffset(0)]
public uint DWord;

[System.Runtime.InteropServices.FieldOffset(0)]
//LONGLONG->__int64
public long Int64;

[System.Runtime.InteropServices.FieldOffset(0)]
//ULONGLONG->unsigned __int64
public ulong UInt64;

//LPWSTR->WCHAR*
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
[System.Runtime.InteropServices.FieldOffset(0)]
public string pwszDescription;


//GUID->_GUID
[System.Runtime.InteropServices.FieldOffset(0)]
public GUID Guid;

[System.Runtime.InteropServices.FieldOffset(0)]
public LIFE_TIME LifeTime;

[System.Runtime.InteropServices.FieldOffset(0)]
public DIAG_SOCKADDR Address;


[System.Runtime.InteropServices.FieldOffset(0)]
public byte[] octets;

}

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
public struct HELPER_ATTRIBUTE
{
/// LPWSTR->WCHAR*
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public string pwszName;

public ATTRIBUTE_TYPE type;

public unionForHelpAttribute Anonymus1;
}

[DllImport("ndfapi.dll", SetLastError = true)]
public static extern long NdfCreateIncident(
string helperClassName,
ulong celt,
ref HELPER_ATTRIBUTE attribues,
out IntPtr NDFHandle
);

Problempath = “ \\\\desktop\\somedrive “;

HELPER_ATTRIBUTE ha = new HELPER_ATTRIBUTE();
ha.pwszName = Name;
ha.type = ATTRIBUTE_TYPE.AT_STRING;

ha.Anonymus1.pwszDescription = problemPath;

//converting string to byte array
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

ha.Anonymus1.octets = new byte[encoding.GetBytes(problemPath).Length];

ha.Anonymus1.octets = encoding.GetBytes(problemPath);