Showing posts with label Code Sample. Show all posts
Showing posts with label Code Sample. Show all posts

Saturday, April 23, 2011

Code to Browse the Security Setup of SharePoint Site Collection

In case if you need to verify the security setup of your SharePoint site collection, you just need to run the following code as shown below:

using System;
using System.Linq;
using Microsoft.SharePoint;

namespace BrowseSecurity
{
    class Program
    {
        static void Main(string[] args)
        {
            BrowseSecurity("http://localhost");
            Console.Out.WriteLine(true);
        }

        private static void BrowseSecurity(string url)
        {
            using (SPSite site = new SPSite(url))
            {
                SPWeb web = site.OpenWeb();
                Console.WriteLine("\n\nUsers:");
                foreach (SPUser user in web.Users)
                {
                    Console.WriteLine(user.Name);
                }

                Console.ReadLine();
                Console.WriteLine("\n\n All Users:");
                foreach (SPUser user in web.AllUsers)
                {
                    Console.WriteLine(user.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Site Users:");
                foreach (SPUser user in web.AllUsers)
                {
                    Console.WriteLine(user.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles:");
                foreach (SPRole role in web.Roles)
                {
                    Console.WriteLine(role.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles Definitions:");
                foreach (SPRoleDefinition roledef in web.RoleDefinitions)
                {
                    Console.WriteLine(roledef.Name);
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Roles Assignments:");
                foreach (SPRoleAssignment roleA in web.RoleAssignments)
                {
                    Console.WriteLine("The following Role definition bindings exist for " +
                    roleA.Member.Name);
                    foreach (SPRoleDefinition roledef in roleA.RoleDefinitionBindings)
                    {
                        Console.WriteLine(roledef.Name);
                    }
                }
                Console.ReadLine();
                Console.WriteLine("\n\n Groups:");
                foreach (SPGroup group in web.Groups)
                {
                    Console.WriteLine(group.Name);
                }
                Console.ReadLine();
            }
        }
    }
}

Sunday, April 17, 2011

Send Email in SharePoint via .NET SmtpClient Class and SharePoint SPUtility Class

In SharePoint, you could send email programmatically by using either .NET Class Library or SharePoint Object Model. I always prefer the second method since using SharePoint ensures that the required settings are maintained by Central Administration.

The following show the two code examples on how you could do this:

Sending Email via .NET SmtpClient Class

using System.Net.Mail;
using Microsoft.SharePoint;

/// <summary>
/// Sends the mail via NET SmtpClient.
/// </summary>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The body.</param>
/// <param name="IsBodyHtml">if set to <c>true</c> [is body HTML].</param>
/// <param name="From">From.</param>
/// <param name="To">To.</param>
/// <param name="Cc">The cc.</param>
/// <param name="Bcc">The BCC.</param>
/// <returns></returns>
public static bool SendMailviaNET(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
    bool mailSent = false;
    try
    {
        SmtpClient smtpClient = new SmtpClient();
        smtpClient.Host = SPContext.Current.Site.WebApplication.OutboundMailServiceInstance.Server.Address;
        MailMessage mailMessage = new MailMessage(From, To, Subject, Body);

        if (!String.IsNullOrEmpty(Cc))
        {
            MailAddress CCAddress = new MailAddress(Cc);
            mailMessage.CC.Add(CCAddress);
        }
        if (!String.IsNullOrEmpty(Bcc))
        {
            MailAddress BCCAddress = new MailAddress(Bcc);
            mailMessage.Bcc.Add(BCCAddress);
        }

        mailMessage.IsBodyHtml = IsBodyHtml;
        smtpClient.Send(mailMessage);
        mailSent = true;
    }
    catch (Exception)
    {
        return mailSent;
    }
    return mailSent;
}

Sending Email via SharePoint SPUtility Class

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;

/// <summary>
/// Sends the mail via SharePoint SPUtility.
/// </summary>
/// <param name="Subject">The subject.</param>
/// <param name="Body">The body.</param>
/// <param name="IsBodyHtml">if set to <c>true</c> [is body HTML].</param>
/// <param name="From">From.</param>
/// <param name="To">To.</param>
/// <param name="Cc">The cc.</param>
/// <param name="Bcc">The BCC.</param>
/// <returns></returns>
public static bool SendMailviaSharePoint(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
{
    bool mailSent = false;
    try
    {
        SPWeb thisWeb = SPContext.Current.Web;
               
        StringDictionary headers = new StringDictionary();
        headers.Add("to", To);
        headers.Add("cc", Cc);
        headers.Add("bcc", Bcc);
        headers.Add("from", From);
        headers.Add("subject", Subject);
        if (IsBodyHtml) headers.Add("content-type", "text/html");

        mailSent = SPUtility.SendEmail(thisWeb, headers, Body);
    }
    catch (Exception)
    {
        return mailSent;
    }
    return mailSent;
}

Tuesday, February 8, 2011

Getting SharePoint Web Application URL Using SPAlternateUrl

By using SPAlternateURL object, you can get the URL or SharePoint 2010 Web Application since the alternate access mappings are associated with a Web Application. Sample code is provided below:

public static string GetWebAppURL(SPWebApplication oWebApp, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    try
    {
        foreach (SPAlternateUrl altUrl in oWebApp.AlternateUrls)
        {
            if (altUrl.UrlZone == urlZone)
            {
                retVal = altUrl.Uri.ToString();
                break;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

public static string GetWebAppURL(SPSite oSite, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    SPWebApplication oWebApp = null;
    try
    {
        if ((oWebApp = oSite.WebApplication) != null)
            retVal = GetWebAppURL(oWebApp, urlZone);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

public static string GetWebAppURL(SPWeb oWeb, SPUrlZone urlZone)
{
    string retVal = string.Empty;
    SPWebApplication oWebApp = null;
    try
    {
        if(( oWebApp = oWeb.Site.WebApplication)!=null)
            retVal = GetWebAppURL(oWebApp, urlZone);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return retVal;
}

In order to call these functions, you need to pass either SPWebApplication, SPSite or SPWeb object and specify the SPUrlZone enumeration which has the following originating zone of a request:

  • Default - Specifies the default zone used for requests unless another zone is specified.
  • Intranet - Specifies an intranet zone.
  • Internet - Specifies an Internet zone.
  • Custom - Specifies a custom zone.
  • Extranet - Specifies an extranet zone.

Thursday, February 3, 2011

Random Number Generation - Not Random At All

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                Random random = new Random();
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

Did you know that if you declared Random Class within the loop as shown in the code sample above, it will not generate random number at all – in fact it will generate same number as shown in the screenshot below:

RandomNumber

To fix this problem, you need to declare Random Class outside of for loop as follows:

using System;

namespace MyRandom
{
    class Program
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                // Generate random number
                int myNum = random.Next(0, 10);
                // Write generated random number to console window
                Console.WriteLine("My random number: " + myNum.ToString());
            }
            // Pause running console window
            Console.ReadLine();
        }
    }
}

Using CrmDiscoveryService Web Service To Find Sales Org and Web Service End Point

Microsoft Dynamics CRM CrmDiscoveryService Web service provides a list of Web service endpoint URLs for each sales organization that you are a member of. The following sample code shows you how to use the Web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRMDiscoveryServices;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Get CRM Dynamics credential from web configuration
            string crmUserId = ConfigurationManager.AppSettings["CRMUSERID"];
            string crmPassword = ConfigurationManager.AppSettings["CRMPASSWORD"];
            string crmDomain = ConfigurationManager.AppSettings["CRMDOMAIN"];

            // Create and configure the CrmDiscoveryService Web service proxy.
            CrmDiscoveryService discoveryService = new CrmDiscoveryService();
            discoveryService.Credentials = new System.Net.NetworkCredential(crmUserId, crmPassword, crmDomain);

            // Retrieve the list of organizations that the logged on user belongs to.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);

            // Locate the target organization in the list.
            if (orgResponse != null && orgResponse.OrganizationDetails.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
                {
                    sb.AppendLine("<B>Organisation name:</B> " + orgDetail.OrganizationName
                        + " <B>CRM Web application.:</B> " + orgDetail.WebApplicationUrl
                        + " <B>CrmService Web service URL:</B> " + orgDetail.CrmServiceUrl + "<BR/>");
                }
                Response.Write(sb.ToString());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Please note that you need to add the CrmDiscoveryService web reference to your project. To add the web reference, select Add Service Reference, click Advanced, and then click Add Web Reference. In the URL field, paste the following string, replacing <server name> and <port number>:

http://<servername>:<port>/mscrmservices/2007/ad/crmdiscoveryservice.asmx?WSDL

Tuesday, February 1, 2011

The Disposable in SharePoint Development

If you don’t properly dispose of objects in the SharePoint object model that implement IDisposable, you will have memory usage problems in your application. The objects to be most careful of are SPSite and SPWeb, which must be disposed of because they consume large amounts of unmanaged memory.

But Wait… I Thought Garbage Collection Took Care of Memory Management?

The answer to this question is that an object like SPSite uses a mix of managed and unmanaged code. The memory usage of the managed side of SPSite is monitored by the .NET garbage collector, and when enough memory is used by the managed code, the garbage collector will kick in. The problem is that the .NET garbage collector doesn’t watch the unmanaged code’s use of memory and the unmanaged memory use is much greater than the managed memory use. So you can quickly run out of memory on the unmanaged
side without .NET ever feeling like it needs to do a garbage collection.

There are several coding patterns that I use when working with SPWeb and SPSite and other objects that implement IDisposable, so I would like to share with all of you:

Using Dispose with SPSite or SPWeb  object

SPSite oSite = new SPSite("http://localhost");

// Do something

SPWeb oWeb = oSite.OpenWeb();

// Do something

oWeb.Dispose();
oSite.Dispose();

The using clause with SPSite or SPWeb

using (SPSite oSite = new SPSite("http://localhost"))
{
    // Do something
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        // Do something
    }
}

Using Dispose in the finally block of try, catch, finally code

SPSite oSite = null;
SPWeb oWeb = null;
try
{
    if ((oSite = new SPSite("http://localhost")) != null)
    {
        oWeb = oSite.OpenWeb();
        // Do something
    }
}
catch (Exception ex)
{
    // Handle exception
}
finally
{
    if (oWeb != null)
        oWeb.Dispose();

    if (oSite != null)
        oSite.Dispose();
}

Using Dispose with an object in a foreach loop

using (SPSite oSite = new SPSite("http://localhost"))
{
    foreach (SPWeb oWeb in oSite.AllWebs)
    {
        try
        {
            // Do something here
        }
        catch (Exception ex)
        {
            // Handle exception
        }
        finally
        {
            if (oWeb != null)
                oWeb.Dispose();
        }
    }
}

Do Not Dispose of the SPSite and SPWeb Return By SPContext

According to SharePoint best practices, SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext
.Web, and SPContext.Current.Web should not be explicitly disposed by user code.

SharePoint Dispose Checker Tool

Alternatively, you can use SPDisposeCheck to measure your code against known Microsoft dispose best practices.

Friday, November 12, 2010

Deleting Data Using Silverlight and Javascript Client Object Model

Silverlight

private void Delete_Click(object sender, RoutedEventArgs e)
{
    ClientContext ctx = new ClientContext("Your Server Here");
    CamlQuery query = new CamlQuery();
    query.ViewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    List announcements = ctx.Web.Lists.GetByTitle("Announcements");

    ListItemCollection listItems = announcements.GetItems(query);
    ctx.Load(listItems);
    ctx.ExecuteQueryAsync((s, args) =>
    {
        ListItem lastItem = listItems[listItems.Count - 1];
        lastItem.DeleteObject();
        announcements.Update();
        ctx.ExecuteQueryAsync((s1, args1) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                label1.Content = "Last record deleted";
            });
        }, null);
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

Javascript

function Delete_Click() {
    var ctx = new SP.ClientContext.get_current();
    var query = new SP.CamlQuery();
    query.viewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    var announcements = ctx.get_web().get_lists().getByTitle("Announcements");
    var listItems = announcements.getItems(query);

    ctx.load(listItems, "Include(Title)");
    ctx.executeQueryAsync(function (s, args) {
        var lastItem = listItems.get_item(listItems.get_count() - 1);
        lastItem.deleteObject();
        announcements.update();
        ctx.executeQueryAsync(function (s, args) {
            var console = document.getElementById('DemoConsole');
            console.innerHTML = " Last Item Deleted";
        }, null);
    }, null);
}

For more information on Silverlight and JavaScript Client Object Model, see below:

Thursday, November 11, 2010

Updating Data Using Silverlight and Javascript Client Object Model

Silverlight

private void Update_Click(object sender, RoutedEventArgs e)
{
    ClientContext ctx = new ClientContext("Your Server Here");
    CamlQuery query = new CamlQuery();
    query.ViewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    List announcements = ctx.Web.Lists.GetByTitle("Announcements");

    ListItemCollection listItems = announcements.GetItems(query);
    ctx.Load(listItems);
    ctx.ExecuteQueryAsync((s, args) =>
    {
        foreach (var item in listItems)
        {
            item["Title"] = "Updated";
            item.Update();
        }
        ctx.ExecuteQueryAsync((s1, args1) =>
        {
            Dispatcher.BeginInvoke(() =>
            {
                label1.Content = "Records Updated";
            });
        }, null);
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

Javascript

function Update_Click() {
    var ctx = new SP.ClientContext.get_current();
    var query = new SP.CamlQuery();
    query.viewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    var announcements = ctx.get_web().get_lists().getByTitle("Announcements");
    var listItems = announcements.getItems(query);

    ctx.load(listItems, "Include(Title)");
    ctx.executeQueryAsync(function (s, args) {
        var itemEnum = listItems.getEnumerator();
        while (itemEnum.moveNext()) {
            var item = itemEnum.get_current();
            item.set_item("Title", "JavaScript Update");
            item.update();
        }
        ctx.executeQueryAsync(function (s, args) {
            var console = document.getElementById('DemoConsole');
            console.innerHTML = "JavaScript Update Completed";
        }, null);
    }, null);
}

For more information on Silverlight and JavaScript Client Object Model, see below:

Adding Data Using Silverlight and Javascript Client Object Model

Silverlight

private void Add_Click(object sender, RoutedEventArgs e)
{
    ClientContext ctx = new ClientContext("Your Server Here");
    List announcements = ctx.Web.Lists.GetByTitle("Announcements");

    ListItemCreationInformation createInfo = new ListItemCreationInformation();
    ListItem newItem = announcements.AddItem(createInfo);
    newItem["Title"] = "A new item";
    newItem.Update();
    ctx.ExecuteQueryAsync((s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = "Item Added";
        });
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

Javascript

function Add_Click() {
    var ctx = new SP.ClientContext.get_current();
    var announcements = ctx.get_web().get_lists().getByTitle("Announcements");

    var createInfo = new SP.ListItemCreationInformation();
    var newItem = announcements.addItem(createInfo);
    newItem.set_item("Title", "A new javascript item");
    newItem.update();

    ctx.executeQueryAsync(function (s, args) {
        var console = document.getElementById("DemoConsole");
        console.innerHTML = "Add Completed";
    }, null);
}

For more information on Silverlight and JavaScript Client Object Model, see below:

Wednesday, November 10, 2010

Retrieving Data Using Silverlight and JavaScript Client Object Model

Sliverlight

private void CAMLQuery_Click(object sender, RoutedEventArgs e)
{
    ClientContext ctx = new ClientContext("Your site here");
    CamlQuery query = new CamlQuery();
    query.ViewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";

    List announcements = ctx.Web.Lists.GetByTitle("Announcements");
    FieldCollection fields = announcements.Fields;
    ctx.Load(fields);

    ListItemCollection listItems = announcements.GetItems(query);
    ctx.Load(listItems);
    ctx.ExecuteQueryAsync((s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            BuildTable(fields, listItems);
        });
    }, (s, args) =>
    {
        Dispatcher.BeginInvoke(() =>
        {
            label1.Content = args.Message;
        });
    });
}

JavaScript

function CAMLQuery_Click() {
    var ctx = new SP.ClientContext.get_current();
    var query = new SP.CamlQuery();
    query.viewXml = "<View><Query><OrderBy><FieldRef Name=\"Editor\" Ascending=\"False\" /></OrderBy></Query></View>";
    var announcements = ctx.get_web().get_lists().getByTitle("Announcements");
    var listItems = announcements.getItems(query);
    ctx.load(listItems);
    var fields = announcements.get_fields();
    ctx.load(fields);
    ctx.executeQueryAsync(function (s, args) {
        var console = document.getElementById('DemoConsole');
        console.innerHTML = buildTable(fields, listItems);
    }, null);
}

For more information on Silverlight and JavaScript Client Object Model, see below: