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

Wednesday, January 26, 2011

Create MHT from HTML in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CDO;
using ADODB;

namespace mhtConversion
{
public class MIMEConverter1
{
public static void CreateMHT(string urlHTML, string urlMHT)
{
CDO.Message objMessage = new Message();
objMessage.CreateMHTMLBody(urlHTML);

ADODB.Stream strm = new Stream();
strm.Type = StreamTypeEnum.adTypeText;
strm.Charset = "US-ASCII";
strm.Open();
var dsk = objMessage.DataSource;
dsk.SaveToObject (strm,"_Stream");
strm.SaveToFile(urlMHT, SaveOptionsEnum.adSaveCreateOverWrite);
strm.Close();
}
}
}

Create MHT from HTML in Powershell

$adSaveCreateNotExist = 1
$adSaveCreateOverWrite = 2
$adTypeBinary = 1
$adTypeText = 2

function SaveFileTo($msg,$mhtp){
$strm=New-Object -ComObject ADODB.Stream
$Strm.Type = $adTypeText
$Strm.Charset = "US-ASCII"
$Strm.Open()
$dsk=$msg.DataSource
$Dsk.SaveToObject($Strm, "_Stream")

$strm.SaveToFile($mhtp,$adSaveCreateOverWrite)
}

function createMHT($htmlPath,$mhtPath){

$objMessage= New-Object -ComObject CDO.Message
$objMessage.CreateMHTMLBody($htmlPath)
SaveFileTo $objMessage $mhtPath
}


createMHT "C:\Users\user\Desktop\sampleHtml\free small games.htm" "C:\Users\user\Desktop\sampleHtml\free small games.mht"

Node.JS rest api Tutorials