Friday, December 16, 2016

My Eclipse Mars Google App Engine + GWT 2.6.1 setup


To get to the screen above in Eclipse Mars: Help --> Installation Details

Had issues with the GWT designer tab not appearing.

Installed the GWT Designer GPE and the designer tab reappeared.

Thursday, December 8, 2016

SharePoint 2013 Downloading a document library using C# and Microsoft.SharePoint.Client

References

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using SP = Microsoft.SharePoint.Client;
using System.IO;


Main program drive code
  • Gets a list of documents from a document library
  • Loops through the list of documents
  • Checks if there is more than one version of the document
  • Loops through the list of versions in a document library and calls downloadSharePointFile to download that version.

                        ListItemCollection collListItem = querySharePointList(list.Title);
                        foreach (ListItem oListItem in collListItem)
                        {                            
                            Console.WriteLine(string.Format("{0} - {1}", oListItem["FileLeafRef"], oListItem["FileRef"]));

                            context2013.Load(oListItem);
                            context2013.Load(oListItem.File);
                            context2013.Load(oListItem.File.Versions);
                            context2013.ExecuteQuery();

                            //if (oListItem.File.Versions.Count > 1)
                                //MessageBox.Show("More than one version");

                            if (oListItem.File.Versions.Count > 1)
                            {
                                foreach (FileVersion version in oListItem.File.Versions)
                                {
                                    Console.WriteLine(String.Format("Version no: {0} url - {1}", version.VersionLabel, version.Url));
                                    downloadSharePointFile(version.Url, oListItem["FileLeafRef"].ToString());
                                }
                            }

                            //downloadSharePointFile(oListItem["FileRef"].ToString(), oListItem["FileLeafRef"].ToString());
                        }


Query the document library for a list of all the documents in the document library

title - the name of the document library

        private ListItemCollection querySharePointList(string title)
        {
            SP.List oList = context2013.Web.Lists.GetByTitle(title);
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = "5000";
            ListItemCollection collListItem = oList.GetItems(camlQuery);
            context2013.Load(collListItem);
            context2013.ExecuteQuery();
            return collListItem;
        }

Download the document from the document library

filename - url to the document
documentName - name of the document

        private void downloadSharePointFile(string filename, string documentName)
        {
            string baseUri = "base url of the sharepoint application";
            // Create a new WebClient instance.
            WebClient myWebClient = new WebClient();
            System.Net.NetworkCredential netCredential = new System.Net.NetworkCredential("username", "password", "domain name");
            myWebClient.Credentials = netCredential;
            // Concatenate the domain with the Web resource filename.
            // Download the Web resource and save it into the current filesystem folder.
            string fileUrl = baseUri  + "/" + filename;
            myWebClient.DownloadFile(fileUrl, @"c:\temp\" + documentName);
        }

Creating a new web in SharePoint 2010 using C# and Microsoft.SharePoint.Client;

References

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using SP = Microsoft.SharePoint.Client;

Implementation

            // Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
            ClientContext context2010 = new ClientContext("SharePoint URL");

            WebCreationInformation creation = new WebCreationInformation();
            creation.Url = "New web URL name";
            creation.Title = "New web title";
            Web newWeb = context2010.Web.Webs.Add(creation);

            // Retrieve the new web information.
            context2010.Load(newWeb, w => w.Title);
            context2010.ExecuteQuery();

            MessageBox.Show("Web created");

SharePoint 2010 - Uploading a document into a document library with C# and Microsoft.SharePoint

Still working with 2010 in 2016? Me too.

You need to reference these libraries:

using Microsoft.SharePoint;
using System.IO;



        private static void uploadDocument()
        {
            String fileToUpload = @"C:\Temp\Accessibility audit of SharePoint 2010 January 2013.docx";
            String sharePointSite = "SharePoint site URL";
            String documentLibraryName = "Name of document library";
            try
            {
                using (SPSite oSite = new SPSite(sharePointSite))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                        if (!System.IO.File.Exists(fileToUpload))
                            throw new FileNotFoundException("File not found.", fileToUpload);

                        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

                        // Prepare to upload
                        Boolean replaceExistingFiles = true;
                        String fileName = System.IO.Path.GetFileName(fileToUpload);
                        FileStream fileStream = System.IO.File.OpenRead(fileToUpload);

                        // Upload document
                        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
                        // 2/12/2013 12:15 PM
                        spfile.Item.Properties.Clear();
                        spfile.Update();

                        // Commit
                        myLibrary.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Google Analytics Download tracking

var trackableExtensions = "zip,exe,pdf,doc,docx,rtf,xls,xlsx,ppt,pptx,mp3,jpeg,jpg";
var baseUrl = "target site url";
var relativeBasePath = "/";

$(document).ready(function () {
    $("a").on("click", function () {
        if (isTrackableExtension($(this).attr('href'))) {
            var filePath = $(this).attr('href');
            if (filePath.toLowerCase().indexOf(baseUrl) > -1)
                filePath = filePath.toLowerCase().replace(baseUrl, "");
            else
                filePath = filePath.toLowerCase().replace(relativeBasePath, "");
            sendEventToAnalytics(filePath);
        }
    });
});

function getExtensions() {
    return trackableExtensions.split(",");
}

function isTrackableExtension(linkUrl) {
    var trackable = false;
    var extenstions = getExtensions();

    for (var i = 0; i < extenstions.length; i++) {
        if (linkUrl.indexOf(extenstions[i]) > -1) {
            trackable = true;
            break;
        }
    }
    return trackable;
}

function getFileExtension(filename) {
    var extension = "";
    var extenstions = getExtensions();
    for (var i = 0; i < extenstions.length; i++) {
        if (filename.indexOf(extenstions[i]) > -1) {
            extension = extenstions[i].replace(".", "");
            break;
        }
    }
    return extension;
}

function getFileName(linkUrl) {
    var fileName = linkUrl.substring(linkUrl.lastIndexOf("/") + 1);
    return fileName;
}

function sendEventToAnalytics(filename) {
    var eventAction = 'Download-' + getFileExtension(filename).toUpperCase();
    _gaq.push(['_trackEvent', 'Document', eventAction, filename]);

}

Friday, February 17, 2012

Type was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.

While working on a GWT application incorporating a SuggestBox and a custom suggestion oracle class I got stung by the following error:

"Type 'custom suggestion class' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialised."

The solution to my particular problem was to move the custom suggestion class into the client side package (it needs to be on the client side).


Decided to put a post up about this solution to the problem because it has a very faint web foot print, most other suggested fixes are about creating a empty constructor for your suggestion class. 

Sunday, January 15, 2012

Cannot read fields from a deleted object

The above error was causing me some grief, I did delete the object but for some reason a populate query was picking it up from the datastore.

I was able to check if the object was deleted with the following JDOHelper function: JDOHelper.isDeleted(item)

I used it as follows:


import javax.jdo.JDOHelper;
import javax.jdo.ObjectState;

public List getWatchList() {
List watchList = new ArrayList();
List result = ccs.myasxpager.datasource.WatchList.getWatchList();

for (ccs.myasxpager.persistence.schema.WatchList item : result) {
if (JDOHelper.isDeleted(item))
continue;
String[] watchListItem = {item.getAsxCode(), ccs.myasxpager.datasource.Company.getCompanyNameByCode(item.getAsxCode()), ccs.myasxpager.datasource.Company.getIndustryByCode(item.getAsxCode())};
watchList.add(watchListItem);
}
return watchList;
}


Monday, September 13, 2010

Using XmlReader to parse an XML file

using (XmlReader reader = XmlReader.Create(@"D:\Temp\XMLReader\XMLReader\ViewFields.xml"))
{
// Parse the XML document. ReadString is used to
// read the text content of the elements.
while(reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name.Equals("viewfield"))
{
reader.ReadStartElement("viewfield");
Console.WriteLine(reader.ReadString());
}
}
}
}
Console.Read();

Monday, July 5, 2010

Accessing the Content Fields of a SharePoint page

I needed to access the properties/content fields of a SharePoint page programatically and achieved this with the following code:

SPField field = SPContext.Current.List.GetField("Level 1 Group Summary");


string value = field.FieldRenderingControl.ListItemFieldValue.ToString();

Or
value = field.FieldRenderingControl.ItemFieldValue.ToString();

Wednesday, April 7, 2010

Decimal Regular Expression

The following regular expression checks for a number that can contain up to two decimal places.

^\d*(\.\d{1,2})?$

matches:

123
123.1
123.12

not matches:

123.
123.123

Monday, March 29, 2010

NSMailDelivery undeclared

I've been playing around with Objective C using the Cocoa framework ever since I got my Mac for Christmas.

I was following a dummies guide to sending emails using Cocoa and I came across the following show stopper compilation error :

"error: 'NSMailDelivery' undeclared (first use in this function)"

Not much joy online looking for a solution, seems everyone else who was inflicted with this error was advised to use some other mail class due to NSMailDelivery being dropped by Apple with no successor in Cocoa which seemed odd.

Anyway here's how I solved the problem. By default on my Mac Cocoa projects are targeted for a 64 bit architecture environment, when I changed the architecture to 32-bit universal the project compiled.

I changed the target architecture by clicking on the project name under "Groups & Files" to highlight it.
Then I clicked on the "Info" icon to open the project info dialog, next I clicked on the "Build" tab and changed the architecture value to "32-bit Universal".

I'm guessing switching to a 32 bit architecture will fix simular error messages with different classes I saw people enquiring about while I was looking into this problem.

Monday, December 21, 2009

Thursday, December 17, 2009

Accessing the values of a SPFieldChoice

I've got a sharepoint content page that needs to populate a drop down list with the choice values stored in a site column field of type choice.

The field is defined as follow:

Name="AgeOptions"
DisplayName="Age Options"
RichText="TRUE"
RichTextMode="FullHtml"
Required="FALSE"
Group="SIA Enquiry Form"
ID="{119EFAFF-63D3-4d61-A393-06DE18A91093}"
SourceID="http://schemas.microsoft.com/sharepoint/v3">

Select an option below
10-15
15-20
20-25
25-30
30-35
Over 35




I used the following code to access the field from the code behind of my page layout:
 
SPField field = SPContext.Current.Fields["Age Options"];

if (field != null)
{
Response.Write("Found the Age options field: " + field.InternalName + " Type: " + field.TypeAsString);

SPFieldChoice ageOptions = (SPFieldChoice) field;

StringCollection choices = ageOptions.Choices;

for (int i = 0; i < choices.Count; i++)
Response.Write("Choice ->> " + choices[i] + "
");

}
else
Response.Write("Age options not found.");

Monday, September 28, 2009

Regular Expression String Length Restriction

^.{0,100}$

Accepts a string of 0 to 100 characters

Tuesday, July 29, 2008

Obtaining email address from MAPI message

MAPI.Recipients recipients = (MAPI.Recipients)message.Recipients;
MAPI.Recipient recipient = (MAPI.Recipient)recipients.get_Item(1);
MAPI.AddressEntry addressEntry = (MAPI.AddressEntry)recipient.AddressEntry;

string emailAddress = addressEntry.Address.ToString();

Friday, July 25, 2008

MAPI - Connecting to a mailbox and looping through the inbox

Note: You'll need to reference the COM library "Microsoft CDO 1.21 Library"

MAPI.Session session = new MAPI.Session();
string profileInfo = "EXCHANGE_SERVER" + "\n" + "MAILBOX_NAME";
session.Logon("PROFILE_NAME", System.Reflection.Missing.Value, true, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, profileInfo);

// Get the folder
MAPI.Folder inboxFolder = session.Inbox as MAPI.Folder;

// Enumerate messages
MAPI.Messages messages = (MAPI.Messages)inboxFolder.Messages;
MAPI.Message message = (MAPI.Message)messages.GetFirst(null);
while (message != null)
{
// do stuff with the message
try
{
message = (MAPI.Message)messages.GetNext();
if (message != null)
{
textBox1.Text += message.Subject.ToString();
}
}
catch (Exception ex)
{
textBox1.Text = ex.Message.ToString();
return;
}
}


session.Logoff();
}