Tuesday, July 30, 2013

c# Is Numeric Function

Just a quick function which I found online some time ago.

public
static System.Boolean IsNumeric(System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if (Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
}
catch { } // just dismiss errors but return false
return false;
}

Monday, July 29, 2013

SharePoint 2007 Lists Web Service

SharePoint 2007 offers a web service that can be used to query the lists/libraries in your SharePoint site. The service is available at http://server/adm/_vti_bin/lists.asmx and is enabled by default. Below is an image containing the various methods available for use.

Use of the service requires authentication; via Active Directory or in this example using forms based authentication. First create a web reference to the URL above (customize it for your server) and call the reference 'ListProxy'.

ListProxy.Lists newListProxy = new AdvertReport.Generate.ListProxy.Lists();
Here is the code to authenticate with FBA:
protected bool AuthenticateFBAClaims()
{
string userName = ConfigurationSettings.AppSettings["SharePointUser"].ToString();
string password = ConfigurationSettings.AppSettings["SharePointPassword"].ToString();
string server = ConfigurationSettings.AppSettings["SharePointServer"].ToString();

Authentication spAuthentication = new Authentication();
spAuthentication.Url = server + "_vti_bin/Authentication.asmx";
spAuthentication.CookieContainer = new CookieContainer();
LoginResult loginResult = spAuthentication.Login(userName, password);
authCookie = new Cookie();
if (loginResult.ErrorCode == LoginErrorCode.NoError)
{
CookieCollection cookies = spAuthentication.CookieContainer.GetCookies(new Uri(spAuthentication.Url));
authCookie = cookies[loginResult.CookieName];
cookieContainer = new CookieContainer();
cookieContainer.Add(authCookie);
return true;
}
else
return false;
}
}
Now a list can be queried (lists, views and other SharePoint objects are referenced by their GUIDs which can be found using SharePoint Manager 2007).
newListProxy.CookieContainer = cookieContainer;

XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
ndQuery.InnerXml = CAML
XmlNode ndListItems = newListProxy.GetListItems(listGuid, viewGuid, ndQuery, null, null, null, null);
The XML returned will be in SharePoint format (which can be difficult to work with). Below is a function I found online which converts SP XML to regular XML:
// Convert SP XML to Regular XML
public string ConvertZRowToRegularXml(string zRowData)
{
string xsltFromZRowToXml =
"<xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
"xmlns:s=\"uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882\" " +
"xmlns:z=\"#RowsetSchema\">" +
"<s:Schema id=\"RowsetSchema\"/>" +
"<xsl:output method=\"xml\" omit-xml-declaration=\"yes\" />" +
"<xsl:template match=\"/\">" +
"<xsl:text disable-output-escaping=\"yes\">&lt;rows&gt;</xsl:text>" +
"<xsl:apply-templates select=\"//z:row\"/>" +
"<xsl:text disable-output-escaping=\"yes\">&lt;/rows&gt;</xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"z:row\">" +
"<xsl:text disable-output-escaping=\"yes\">&lt;row&gt;</xsl:text>" +
"<xsl:apply-templates select=\"@*\"/>" +
"<xsl:text disable-output-escaping=\"yes\">&lt;/row&gt;</xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"@*\">" +
"<xsl:text disable-output-escaping=\"yes\">&lt;</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">&gt;</xsl:text>" +
"<xsl:value-of select=\".\"/>" +
"<xsl:text disable-output-escaping=\"yes\">&lt;/</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">&gt;</xsl:text>" +
"</xsl:template>" +
"</xsl:stylesheet>";

XslCompiledTransform transform = new XslCompiledTransform();
XmlDocument tidyXsl = new XmlDocument();
try
{
//Transformer
tidyXsl.LoadXml(xsltFromZRowToXml);
transform.Load(tidyXsl);
//output (result) writers
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (XmlTextWriter tw = new XmlTextWriter(sw))
{
//Source (input) readers
using (System.IO.StringReader srZRow = new System.IO.StringReader(zRowData))
{
using (XmlTextReader xtrZRow = new XmlTextReader(srZRow))
{
//Transform
transform.Transform(xtrZRow, null, tw);
return sw.ToString();
}
}
}
}
}
catch(Exception ex)
{
ErrorLog(ex.ToString());
return null;
}
}
Now you can convert the regular XML into a DataSet object:
DataSet ds = new DataSet();
using (System.IO.StringReader sr = new System.IO.StringReader(cleaned)) // Convert XML to DataSet
{
     ds.ReadXml(sr,
    XmlReadMode.Auto);
}

URL Redirection

Two common methods I use for programatically redifrecting the user (in C#) are as follows.

Instant Redirection:
Response.Redirect("http://google.com");
Response.Redirect("http://google.com", false);
The second parameter is EndResponse and indicates whether execution of the current page should terminate.

Delayed Redirection:
Response.AddHeader("REFRESH", "5;URL=http://google.com");

Tuesday, July 23, 2013

Error: Could not find default endpoint element

Could not find default endpoint element that references contract 'Service.Name' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
The Endpoint for the service is missing from the web.config file. The endpoint element should be added under the client parent element in the web.config file. An example would be:

<endpoint address="http://prodcrmservices:8080/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService" contract="CRM.IService" name="BasicHttpBinding_IService" />

SharePoint 2007 Easy Method to Generate CAML Queries

CAML is an XML based language which can be used to query SharePoint lists and libraries. Being XML based it is not the easiest language to write queries in, and business rules/logic can make for some complex statements.
However there is a simple method for generating the CAML.
  1. Create a view on the list/library you wish to query that will display the result set you want returned.
  2. Load up SharePoint Manager 2007 on the SharePoint server.
  3. Using the tree view on the side of SP Manager find the list/library you are querying (under the correct web) and expand the available views.
  4. Click on the relevant view, the right hand window will show the various properties. The Query property will contain the CAML query for that view.

Monday, July 22, 2013

DateTime country format

In cases when you need to work with a DateTime value in a particular country format (for example US or Australian) you can use CultureInfo to achieve this.
CultureInfo culture = new CultureInfo("en-AU");
DateTime reportDate = DateTime.Parse(txtDate.Text, culture);
The example above reads the DateTime variable in using the Australian format (dd/mm/yyyy). It comes in useful if the control is set to display US format for example.

SharePoint 2007 view which web parts are used on a given page

A useful tip for finding which web parts are used on a given page (without checking the page out and editing) is as follows.
Add contents=1 to the URL querystring for the page. For example, if your page URL is http://test.com/page.aspx you would then visit http://test.com/page.aspx?contents=1 to be given a listing of the web parts used on that page.

SharePoint 2007 Command Line Deploy

These are the steps for deploying a WSP solution to SharePoint 2007 using the STSADM command line tool.
For Redeployments If the soltution has been deployed in the past, it will need to be retracted before it can be deployed again. Follow these steps before the deployment.
stsadm -o deactivatefeature -name SolutionName -url http://server
stsadm -o retractsolution -name SolutionName.wsp -immediate -url http://server
stsadm -o execadmsvcjobs
stsadm -o deletesolution -name SolutionName.wsp
Deploying the Solution For new deployments (or redeployments after retracting the solution), follow these steps.
stsadm -o addsolution -filename SolutionName.wsp
stsadm -o deploysolution -name SolutionName.wsp -allowgacdeployment -immediate -url http://server
stsadm -o execadmsvcjobs
stsadm -o activatefeature -name SolutionName -url http://server
Please note: Some commands (such as execadmsvcjobs or activatefeature) may take longer than others to complete.

Dynamic Web Reference URLs

I inherited a number of user controls which had hard coded switches for a WCF service (live and test versions of the same service). Testing became frustrating, as code would need to be commented/uncommented in many different locations. There was also the risk of having the live serice in use on the test environment and the test service in use in the live environment. The solution was to add the URLs for the live/test references, as well as a bool for test mode into the web.config file. A switch was then used to decide which mode was active (live or test) and using the 'Url' property of the client the correct reference URL would be used.
MyClient client = new MyClient();
client.Url = "http://service.url";
The live web reference still needed to be added to the solution and a reference to it in the relevant files to ensure the correct classes/methods were available. However in this case the live/test services were identical.