Wednesday, February 17, 2010

Getting Announcements with attachments from sharepoint site

Situation:

I want a web page for the users who does not have network access to be able to look into current announcements published in our sharepoint.


My solution:

1. Use sharepoint web services to get list of current (unexpired/non-expiring) announcements

2. use a console application for 1. so that it can be scheduled and the sarepoint server is not hit everytime a user tryies to see the announcement

3. All announcements are saved in database with a link to attachments (if any)

4. Download all attachments to a location

5. When the schedule runs it clears the database and attachment folder so that we always have current data


This is how I did:

using System;
using System.Text;
using System.Xml;
using System.Configuration;
using System.IO;


namespace SharepointInterface
{
class Program
{
static void Main(string[] args)
{
string webPath = "http://MySharePointSite";
try
{
ClearAllFiles();//delete all previously downloaded attachment
XmlNode xmlData = GetDataFromWebService(webPath);
TraverseXmlData(xmlData);
}
catch (Exception ex)
{
//take necessary action I sent notification email
}
}

///
/// this function will delete all previously downloaded
/// files in 'DownloadLocation'
///

static void ClearAllFiles()
{
try
{
string path = ConfigurationSettings.AppSettings["DownloadLocation"];
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
fi.Delete();
}
string sql = "DELETE FROM Announcements; DELETE FROM Attachments";
//remove all records from database
DataAccessor da = new DataAccessor();
da.WriteData(sql);
}
catch (Exception ex)
{
//take necessary action
}
}

///
/// Function to communicate with sharepoint web service to get
/// required list data
///

/// Web path

//ref:
//http://www.sharepoint-tips.com/2007/02/how-to-use-getlistitems-web-service.html
private static XmlNode GetDataFromWebService(string webPath)
{
ListWebRef2.Lists sharepointLists = new SharepointInterface.ListWebRef2.Lists();
sharepointLists.Url = webPath + "/_vti_bin/Lists.asmx";
sharepointLists.UseDefaultCredentials = true;

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<Document> <Query /> <ViewFields /> <QueryOptions /> </Document>");
XmlNode query = xmlDoc.SelectSingleNode("//Query");
XmlNode viewFields = xmlDoc.SelectSingleNode("//ViewFields");
XmlNode queryOptions = xmlDoc.SelectSingleNode("//QueryOptions");

//get announcements that has no expiration date or the expiration date is higher than NOW
query.InnerXml = "<Where>" +
"<Or>" +
"<Geq>" +
"<FieldRef Name='Expires' />" +
"<Value Type='DateTime'>" + DateTime.Now.ToString("s").Replace('T', ' ') + "
"<OrderBy> <FieldRef Name='Modified' Ascending='False' />
///
///

///
///
private static void TraverseXmlData(XmlNode xnod)
{
XmlNode xnodWorking;
try
{
if (xnod.NodeType == XmlNodeType.Element)
{//its element
CrackAnnouncementXmlNode(xnod);
}

//if not element; check for child node
if (xnod.HasChildNodes)
{//the node has child node; traverse them as well
xnodWorking = xnod.FirstChild;
while (xnodWorking != null)
{//using recursive technique
TraverseXmlData(xnodWorking);
xnodWorking = xnodWorking.NextSibling;
}
}
}
catch (Exception ex)
{
//take necessary action
}
}

///
/// This function will break announcement node
///

/// Announcement
private static void CrackAnnouncementXmlNode(XmlNode xnode)

{
string sql = string.Empty;
string title, body, modified, editor, uniqueId, attachments;
title = body = modified = editor = uniqueId = attachments = string.Empty;

try
{
/* uncomment this section to see all returned attributes and comment all following if’s
for (int i = 0; i < title =" xnode.Attributes.GetNamedItem(" title =" title.Replace(" body =" xnode.Attributes.GetNamedItem(" body =" body.Replace(" modified =" xnode.Attributes.GetNamedItem(" editor =" xnode.Attributes.GetNamedItem("> 0)
editor = editor.Substring(editor.IndexOf(";#") + 2);
editor = editor.Replace("'", "''");
}

//this is prefixed with ;#
if (xnode.Attributes.GetNamedItem("ows_UniqueId") != null)
{
uniqueId = xnode.Attributes.GetNamedItem("ows_UniqueId").Value;
if (uniqueId.IndexOf(";#") > 0)
uniqueId = uniqueId.Substring(uniqueId.IndexOf(";#") + 2);
}

if (xnode.Attributes.GetNamedItem("ows_Attachments") != null)
{
attachments = xnode.Attributes.GetNamedItem("ows_Attachments").Value;
}

if (attachments != "0" && attachments != string.Empty)
{
//announcement has attachment so download it
DownloadFile df;
df = new DownloadFile(uniqueId, attachments);
df.ParseAndDownload(); //download file(s)
}

if (uniqueId != string.Empty)
{
sql = "INSERT INTO Announcements VALUES ('" + uniqueId + "', '" + title + "', '" + modified + "', '" + editor + "', '" + body + "')";
DataAccessor da = new DataAccessor();
da.WriteData(sql);
}
}
catch (Exception ex)
{
//take necessary action
}
}
}
}

Tuesday, February 16, 2010

Programming with SharePoint

I am writing a small webapp to download "Announcements" from a sharepoint site and had to work with GUIDs. The following link helped me to get guid i needed
http://blogs.msdn.com/ronalus/archive/2007/09/08/a-little-guid-picker.aspx

Friday, January 29, 2010

Hide "Cannot be blank" in InfoPath Services

In InfoPath form services, fields that have validation will display "Cannot be blank" message when hovered over the field. This can be annoying (very annoying:@). To disable this read this or change C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\INC\Core.js

change line from
objVisualizationDiv.style.display = "inline";
to
objVisualizationDiv.style.display = (strHelperName == "ErrorTip") ? "none" : "inline";


or comment out
border: 1px solid #B22828; background:. . .
with in .errorDiv section of ifsmain.css file in same foler

ref: read this

Thanks,

Thursday, October 15, 2009

InfoPath to Word Wizard

I downloaded and installed "InfoPath SDK" but when I tried to run %Program Files%\Microsoft Office 2003 Developer Resources\Microsoft Office InfoPath 2003 SDK\Tools\WordPrint.hta, I got the error
The InfoPath to Word Wizard requires the file WordPrint.dll, which is missing or is not properly registered

I got answers from http://www.infopathdev.com/forums/t/7609.aspx and http://www.infopathdev.com/forums/p/3434/13713.aspx#13713

which basically said that the dll is not registered by SDK installer so
1. Browse to WordPrint directory
2. Copy WordPrint.dll to c:\windows\system32
3. in command prompt type "regsvr32 WordPrint.dll"

thanks to infopathdev

Wednesday, September 2, 2009

Getting Announcement from SharePoint 3 using web service

I am writing because I had to digg, may be other won't have to spent more time like me.

My need:
I needed a page separate from sharepoint to list announcement.

My problem:
I am new to sharepoint and never did program with sharepoint.

What I did:
Of course, I googled! and here are the references first:
1. Get list items from sharepoint
2. Display xml data
3. Get attachment url

I first added a web reference:
1. Right click on Project name is 'Solution Explorer'
2. Choose "Add Web Reference...", 'Add Web Reference' window will open.
3. In 'URL:' box type the sharepoint address similar to http://testBox/dev/_vti_bin/Lists.asmx
4. It will give you error on right panel under 'Web services found at this URL:' saying "The document at the url http://testBox/dev/_vti_bin/Lists.asmx was not recognized as a known document type. ..." and 'Add Reference' button disabled.
5. Add ?WSDL or click on "Service Description" in the left panel to avoid error described in 4.
6. After no. 5 you will be able to see web service(s) in the given url and add the web reference.

Now move on to the second part. Once the web reference is added, there will be 'Web References' in solution explorer.
- Now follow the steps in reference 1, it will pull all the information in the list; I used "Announcements" for my purpose.



protected void Page_Load(object sender, EventArgs e)
{
string webPart = "http://testBox/dev";
XmlNode xmlData = GetItems(webPart);
- To display what you got, follow codes in reference 2. I first printed on scree with Response.Write. At this point you can see xml data returned by web service


protected void Page_Load(object sender, EventArgs e)
{
string webPart = "http://testBox/dev";
XmlNode xmlData = GetItems(webPart);

ChildDisplay(xmlData, 0);
}

- In ChildDisplay function you can filter your required data or do whatever your need be with the obtained data.
- As for the reference 3, I took

listQueryOptions.InnerXml = "<IncludeAttachment>TRUE</IncludeAttachment>";
to get url for the attachment.
- I will need to download and store the attachment in to a folder.


Monday, August 24, 2009

Sending email using CDO

Set myMail = CreateObject("CDO.Message")
myMail.Subject = "Sending email with CDO"
myMail.From = "fromAddress@domain.com"
myMail.To = "toAddress@domain.com"
myMail.TextBody = "This is a message."

myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing")=2
'Name or IP of remote SMTP server

myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.domain.com"

'Server port
myMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25

myMail.Configuration.Fields.Update

myMail.Send

set myMail=nothing

Monday, July 20, 2009

ViewState and ListBox

ViewState is to retain value when a page is post back from server.
To preserve value and not to re-populate ListBox or DropDownList in asp.net use following
if (!IsPostBack) //fill the lists
{
  //for network dropdown
  query = "select network from network";
  reader = da.readData(query);

  while (reader.Read())
  {
    Network.Items.Add(reader["network"].ToString());
  }
}
TextBox "readonly" and viewstate
(ref http://aspadvice.com/blogs/joteke/archive/2006/04/12/16409.aspx)
To retain data in a TextBox (datetime picker) in PostBack action use server side code
TextBox1.Attribute.Add ("readonly", "readonly");

rather than the client side


I had trouble figuring out this but this may help some other.