Thursday, March 18, 2010

Delete Selected item from XML Node


All,

Today i gonna share with you code related to XML file.
That is reading and reading XML files.

Following Steps will be shown:
a) First populate listbox with XML data.
b) Second select any item in the Listbox and delete that node from the XML.

Prerequisites:
Add using System.XML namespace above.
Add listbox and a Button(for Delete).
Make an XML file and store in any directory (D directory in my example).

First Below is the Sample XML file :( I have stored it in as : D:\DocumentsOrder.xml).



On Form Load write the below code:

private voidForm1_Load(object sender,EventArgs e)

{

XmlDocument xDoc = newXmlDocument();

xDoc.Load(@"D:\DocumentsOrder.xml");

for (int i = 0; i <>

{

//Add the innertext of the xml document to the listbox

listBox1.Items.AddRange(newobject[] { xDoc.DocumentElement.ChildNodes[i].InnerText });

}

}


On Delete Button Click event write the following Code:


private voidbutton5_Click(object sender,EventArgs e)

{

XmlDocument xDoc = newXmlDocument();

xDoc.Load(@"D:\DocumentsOrder.xml");

//Add the innertext of the xml document to the listbox

xDoc.DocumentElement.RemoveChild(xDoc.DocumentElement.ChildNodes[listBox1.SelectedIndex]);

FileStream WRITER = newFileStream(@"D:\DocumentsOrder.xml", FileMode.Truncate,FileAccess.Write,FileShare.ReadWrite);

xDoc.Save(WRITER);

//Close the writer filestream

WRITER.Close();

//Form1_Load(new object(), new EventArgs());

}



Thats it...Your XML Node(selected item in Listbox) is deleted.

So here is the preview:






Now Go and check your XML...
Hope the selected Node is deleted.

Regards,
Nitin Sharma

Send Outlook E mail using VB macros

All,
Below is the VB Macro code to send mail using Microsoft Outlook :

Lines mark with " ' " are commented.

Sub SendMail()

'

'This macro requires the Outlook Object library to be checked

'in the vba editor Tools > References

Dim bStarted As Boolean

Dim oOutlookApp 'As outloo

Dim oItem 'As Outlook.MailItem

On Error Resume Next

'see if Outlook is running and if so turn your attention there

Set oOutlookApp = GetObject(, "Outlook.Application")

If Err <> 0 Then 'Outlook isn't running

'So fire it up

Set oOutlookApp = CreateObject("Outlook.Application")

bStarted = True

End If

'Open a new e-mail message

Set oItem = oOutlookApp.CreateItem(olMailItem)

With oItem 'and add the detail to it

.To = "abc@yahoo.com" 'send to this address

.Subject = "This is a Test Mail using VB Macros" 'This is the message subject

.Body = "See attached document" ' This is the message body text

.Attachments.Add ActiveDocument.FullName

ActiveDocument.SaveAs strFilePath & strDate

.Send

'**********************************

'If you want to view the message before it goes

'change the line above from .Send to .Display

'Otherwise the message is sent straight to the Outbox

'and if you have Outlook set to send mail immediately,

'it will simply be Sent

'with no obvious sign that Outlook has operated.

'Apart from the copy in the Outlook Sent folder

'**********************************

End With

If bStarted Then 'If the macro started Outlook, stop it again.

oOutlookApp.Quit

End If

'Clean up

Set oItem = Nothing

Set oOutlookApp = Nothing

End Sub





Regards,

Nitin Sharma

Friday, March 12, 2010

Upload Word Document using Sharepoint Web Services


All,
Below is the sample code to add a Microsoft Word Document inside the Sharepoint Documen Library's folder.

Say i have a Document Library as CoastGuard and it has four folders : MIS,Aviation,IT and Logistics.So i need to add document in these folders using Sharepoint in built web services.

Below is the Code:

using System;

usingSystem.Collections.Generic;

using System.Configuration;

usingSystem.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml;

using System.IO;

using System.Collections;

using Microsoft.SharePoint;

using System.Net;

namespace Signals

{

public partial class Form1:Form

{

public Form1()

{

InitializeComponent();

}

private voidForm1_Load(objectsender,EventArgs e)

{

GetFiles();

GetFoldersList();

}

private void GetFoldersList()

{

wsLists.Lists spList =newSignals.wsLists.Lists();

spList.Credentials = System.Net.CredentialCache.DefaultCredentials;

stringspUrl=ConfigurationSettings.AppSettings["SPFolders"].ToString();

spList.Url ="http://Win08r2/Signals/_vti_bin/Lists.asmx";

XmlNode listnodes = spList.GetListItems("CoastGuard", null, null, null, null, null,null);

foreach (XmlNode nodeinlistnodes)

{

if (node.Name == "rs:data")

{

for (int i = 0; i <>

{

if (node.ChildNodes[i].Name == "z:row")

{

listView1.Items.Add(node.ChildNodes[i].Attributes["ows_LinkFilename"].Value);

}

}

}

}

}

private void GetFiles()

{

string strPath ="..\\..\\Documents";

DirectoryInfo di =newDirectoryInfo(strPath);

FileInfo[] fi = di.GetFiles();

foreach (FileInfo f in fi)

{

listView2.Items.Add(f.Name);

}

}

privatevoidbutton1_Click(objectsender,EventArgs e)

{

wsLists.Lists spList =newSignals.wsLists.Lists();

spList.Credentials = System.Net.CredentialCache.DefaultCredentials;

spList.Url ="http://Win08r2/_vti_bin/Lists.asmx";

listView1.Items[0].Selected =true;

string DocFileName = "";

foreach (ListViewItem linlistView2.SelectedItems)

{

DocFileName = l.Text.ToString();

}

if (DocFileName != "")

{

if(listView1.CheckedItems.Count > 0)

{

for (int i = 0; i <>

{

WebClient WC =newWebClient();

WC.Credentials =CredentialCache.DefaultCredentials;

WC.UploadData("http://Win08r2/signals/CoastGuard/"+ listView1.CheckedItems[i].Text + "/" + DocFileName, "PUT", StreamFile(@"..\\..\\Documents\" + DocFileName));

}

MessageBox.Show("Files moved successfully");

}

else

{

MessageBox.Show("Please Select At Least One Folder");

}

}

else

{

MessageBox.Show("Please Select a File");

}

}

private byte[] StreamFile(stringfilename)

{

FileStream fs =newFileStream(filename,FileMode.Open,FileAccess.Read);

// Create a byte array of file stream length

byte[] ImageData =newbyte[fs.Length];

//Read block of bytes from stream into the byte array

fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

//Close the File Stream

fs.Close();

return ImageData; //return the byte data

}

privatevoidbutton2_Click(objectsender,EventArgs e)

{

foreach (ListViewItem liinlistView1.Items)

{

li.Checked = true;

}

}

privatevoidbutton3_Click(objectsender,EventArgs e)

{

foreach (ListViewItem liinlistView1.Items)

{

li.Checked = false;

}

}

}

}

Here's the Result:

Form1 screenshot.Multiple folders can be selected,but only single file can be selected.


Document uploaded successfully..



Regards,

Nitin Sharma


Fetch Temp directory of Windows using VBA macros

Hey,
I am working on VBA Macros for a small module.I came across a need to find the temp directory path using VBA.so here it is:

Public Function GetTempDir() As String
Dim sRet As String, lngLen As Long
'create buffer
sRet = String(MAX_PATH, 0)

lngLen = GetTempPath(MAX_PATH, sRet)
If lngLen = 0 Then Err.Raise Err.LastDllError
GetTempDir = Left$(sRet, lngLen)
End Function



Access above function here as :
Sub TestMacro

Dim strFilePath As String
strFilePath = GetTempDir()
End Sub

Regards,
Nitin Sharma

Adding Images in Word Document using C#.NET

Hey,
I came across a requirement where i need to add Images in the Microsoft word document using C# code in Windows application.


I searched and wrote the code as follows but before that :

Step 1) do add reference to Microsoft Word Object Library.

Step 2) Add using Microsoft.Office.Interop.Word;
using System.IO; namespaces on top.


Code in Form1.cs:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using System.IO;

namespace Sample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object Visible=true;
object start1 = 0;
object end1 = 0;

ApplicationClass WordApp = new ApplicationClass();
Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Range rng = adoc.Range(ref start1, ref missing);

try
{

foreach (ListViewItem Li in listView1.Items)
{

FileInfo Fi = new FileInfo(Li.Text);

rng.InlineShapes.AddPicture(Fi.ToString(), ref missing, ref missing, ref missing);

}

rng.Font.Name = "Georgia";
rng.InsertAfter("Hello World!");
object filename = @"D:\"+textBox1.Text+".docx"; //Saves in D directory


adoc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);


}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void butBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
string [] FileNames = openFileDialog1.FileNames;
foreach (string nameOfFile in FileNames)
{
listView1.Items.Add(nameOfFile);
}

}
}
}


Thats it..Now check your directory(here it is D directory)


Below is the Screen Shot:













Happy Coding..!
Regards,
Nitin Sharma