Monday, December 28, 2009

Add SP List Items into drop down.

This code will retrieve list items from a given list and append them to a given DropDownList.

C# Code :

SPSite ospSite = new SPSite("http://spserver");

SPWeb ospWeb = ospSite.AllWebs["testweb"];
SPList ospList = ospWeb.Lists["Test Document Library"];
int ct = ospWeb.Lists["Test Document Library"].Items.Count;
for (int idx = 0; idx < ct - 1; idx++)
{
//Following line retrieves Name value from the list item.
DropDownList1.Items.Add(ospList.Items[idx].GetFormattedValue("Name").ToString());
}

Sunday, December 27, 2009

How to create a system DSN

The following code checks if a DSN with the given name exists, if not a new DSN will be created.

Code was written using C# :

//Define the following before starting the code.
[DllImport("ODBCCP32.dll")]
public static extern bool SQLConfigDataSource(
IntPtr parent, int request, string driver, string attributes);
[DllImport("ODBCCP32.dll")]
public static extern int SQLGetPrivateProfileString (string lpszSection, string lpszEntry, string lpszDefault,string @RetBuffer, int cbRetBuffer, string lpszFilename );

//In the button click event call the following method with DSN name as input //value

public void CreateDSN(string strDSNName)
{
string driver;
string attributes;


//************ Createing DSN for Access database ********************//
/*
* driver = "Microsoft Access Driver (*.MDB)" + "\0";
* attributes = "DSN=tstDSN" + "\0" + "Uid=" + "\0" + "pwd=" + "\0" + "DBQ=C:\\Test.mdb" + "\0";
*
*/

try
{
driver = "SQL Server";

//- check for ODBC data source

int iData;
string strRetBuff="";
string strDSN="";
strDSN = "DSN : " + strDSNName + " has been created successfully with following
parameters : \n\n";
iData = SQLGetPrivateProfileString("ODBC Data
Sources",strDSNName,"",strRetBuff,200, "odbc.ini");

if(iData > 0)
{
MessageBox.Show("DSN already exists");
}
else
{
if (MessageBox.Show("DSN not found. Would you like to create one ?","DSN
Creation",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes )
{
attributes = "DSN=" + strDSNName + "\0" + "Server=mysqlserver" + "\0" ;
attributes = attributes + "Description=Test Dev Server" + "\0";
attributes = attributes + "Database=mydatabase" + "\0";

strDSN = strDSN + "Server = mysqlserver\n\n";
strDSN = strDSN + "Description=Test Dev Server \n\n";
strDSN = strDSN + "Database=mydatabase \n\n";


if (SQLConfigDataSource((IntPtr)0,4,driver, attributes) )
{
MessageBox.Show ("DSN was created successfully..");
lblStatus.Text = strDSN;
}
else
{
MessageBox.Show ("DSN Creation Failed...");
lblStatus.Text = "DSN creation failed";
}
}
else
{
lblStatus.Text = "DSN was not created as per user request";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{}
}

Code to copy a file from one SP site to another.

This code can be used to copy a file from a source SharePoint site location to any other site within the same SharePoint server.

Code written in C# :

SPSite site = new SPSite("http://SPServer");
SPWeb web = site.RootWeb;
SPFile myFile = web.GetFile("http://SPServer/folder1/testdoc.docx");

// Read the contents of the file into a byte array.
byte[] sfile = myFile.OpenBinary();

//Get the destination server info.
SPSite site2 = new SPSite("http://SPServer2");
SPWeb web2 = site2.RootWeb;
SPFolderCollection testfolders = web2.Folders;

//New file in the name of newdoc.docx will be created in SPServer2/destfolder
//this file will contain the similar contents as testdoc.docx
SPFile testfile = testfolders["destfolder"].Files.Add("newdoc.docx", sfile);
testfile.Update();

Parsing a csv file using C#

The process has been made very simple by referencing the Microsoft.VisualBasic.FileIO dll

Code can be written in a simplified version as :

string filename = "c:\testfile.csv";
TextFieldParser fldparser = null;

try
{

using (fldparser = new TextFieldParser(filename))
{
//When it is a delimited option between fields.
fldparser .TextFieldType = FieldType.Delimited;
//If it is a comma separated data.
fldparser.SetDelimiters(",");
//If the file has double quotes inclued in every column value.
fldparser.HasFieldsEnclosedInQuotes = true;


while (!fldparser.EndOfData)
{
string[] columnvalues = fldparser.ReadFields();
// If the csv file has 10 columns then declare the array as
// defined below.(change values accordingly).
string[] totalcolumns = new string[10];
int colcount = 0;
foreach (string val in parts)
{
totalcolumns[colcount] = val; colcount += 1;
}
}
}

}
catch (Exception ex)
{
}
finally
{

}

Invoke .NET web service from VB6

There are a lot of projects which currently run in VB6 but in an unwilling situation to migrate it to the new version of VB.NET or C#. In one such situation, it was decided to continue using VB6 application with validation done using Web Service created in .NET

I am just including a sample code for writing the same :

VB6 Code :

Dim iFirst As Integer
Dim iSecond As Integer

Dim bNothing As Boolean

Dim MSSCWebSrvc As New MSSOAPLib.SoapClient

Dim objRS As New ADODB.Recordset

On Error Resume Next

'-- Virtual Directory
MSSCWebSrvc.mssoapinit ("http://localhost/test/VBWebService.asmx?wsdl")

If Err.Number = -2147024809 Then
MsgBox "Invalid WebService Request. Please check the URL"
End If

iFirst = 10
iSecond = 5
bNothing = False

'Invoking the AddData method in web service to add the two values.
MsgBox ("Total is : " & MSSCWebSrvc.AddData(iFirst, iSecond))

'To deal with DataSets/Recordsets we can try the following code.

Set objRS = MSSCWebSrvc.objRSReturn()
If objRS.EOF Then
MsgBox " no records "
Else
MsgBox " records found... "
End If

I hope this helps.