hits counter
  Create Free Blog | Random Blog »   Report Abuse | Login   

 
jump to navigation

Updating SharePoint User Profile programmatically September 8, 2009

Posted by tippu in : Sharepoint , comments closed
In one of my colleagues project, they had a scenario to update the SharePoint user profile through code. We tried to update the user profile by getting the user profile from the user profile manager and committing the changes, but when we do it, we got the following exception.
 
System.ArgumentNullException: Value cannot be null.
Parameter name: serverContext
at Microsoft.Office.Server.SiteContext..ctor(ServerContext serverContext)
at Microsoft.Office.Server.SiteContext.get_Current()
 
After digging into the issue, we got to know that the server context was not available even when we call the GetContext method. To made it work by faking the current context. I got the concept of faking the SPContext from “Keith Dahlby” blog http://solutionizing.net/2009/02/16/faking-spcontext/
 
if (HttpContext.Current != null)
{
    if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
        HttpContext.Current.Items["HttpHandlerSPWeb"] = spWeb;
    if (HttpContext.Current.Items["Microsoft.Office.ServerContext"] == null)
        HttpContext.Current.Items["Microsoft.Office.ServerContext"] = context;
}
After plugging in the fake SPContext, the Updating of SharePoint User Profile worked. Below is the final code that made the User Profile Update successful.
 
 
SPWebApplication spWebApp = null;
try
{
    //Create a SPSite Object with a valid Site collection address
    using (SPSite spSite = new SPSite("http://www.riswana.com/"))
    {
        //Open the web object
        using (SPWeb spWeb = spSite.OpenWeb())
        {
            //Create the Web Application object from the current site
            spWebApp = spSite.WebApplication;

            //Disable the Form Digest Setting so that the user profile object skips the 
            //Form digest when commiting the User Profile Change.
            spWebApp.FormDigestSettings.Enabled = false;

            //Create the server context
            ServerContext context = ServerContext.GetContext(spSite);

            //Update the HttpHandlerSPWeb with the web object and 
            //the Microsoft.Office.ServerContext with the server context
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
                    HttpContext.Current.Items["HttpHandlerSPWeb"] = spWeb;
                if (HttpContext.Current.Items["Microsoft.Office.ServerContext"] == null)
                    HttpContext.Current.Items["Microsoft.Office.ServerContext"] = context;
            }

            //Create the user profile object from the context object
            UserProfileManager profileManager = new UserProfileManager(context);

            string sAccount = "bayone\\pva1";

            //Get the Users Profile from the profile manager object
            UserProfile userProfile = profileManager.GetUserProfile(sAccount);

            //Update any of the user profile property value
            userProfile[PropertyConstants.CellPhone].Value = "+91 98460 12345";

            //Commit the changes
            userProfile.Commit();

        }
    }
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    if (spWebApp != null)
        spWebApp.FormDigestSettings.Enabled = true;
}
Share SocialTwist Tell-a-Friend 

SharePoint 2010 Sneak Peek July 19, 2009

Posted by tippu in : Sharepoint , comments closed

Hi All, Microsoft is sharing the sneak peek of sharepoint 2010. Some developer features are looking great. In coming months we can see lots of extensive blogging on this.  Check this out http://sharepoint.microsoft.com/2010/Sneak_Peek/Pages/default.aspx

Set Audience targeting on a SharePoint web part programmatically May 20, 2009

Posted by tippu in : Sharepoint , comments closed

In this article I am going to show you how to set the Audience Target while adding a web part.

I am adding a Content Editor Web part to the default page of the site  with the Audience Target set the two SharePoint groups named “SharepointGroup1” and “SharepointGroup2”.

Webpart class have a property called AuthorizationFilter, which is used to set the Audience Target for the web part. One thing we need to be careful is to add the “;;;;” before the group filter string on the AuthorizationFilter property.

Note: While using the SPLimitedWebPartManager, do Dispose of the web object on the web part manager class.

Sample Source Code:

using (SPSite oSite = new SPSite("http://Tippu/sites/AudianceTargetTest"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        using (SPLimitedWebPartManager oWebpartMngr =
            oWeb.GetLimitedWebPartManager("Default.aspx", PersonalizationScope.Shared))
        {
            try
            {
                ContentEditorWebPart wpContent = new ContentEditorWebPart();
                wpContent.ChromeType = PartChromeType.None;

                //The audience target field needs to have this ";;;;" at the
                //beginning of the string
                wpContent.AuthorizationFilter = 
                   ";;;;SharepointGroup1,SharepointGroup2";

                XmlDocument xmlDoc = new XmlDocument();
                XmlElement xmlElement = xmlDoc.CreateElement("SampleText");
                xmlElement.InnerText = 
                  "This web part is only visible to SharepointGroup1 and SharepointGroup2";

                oWebpartMngr.AddWebPart(wpContent, "Left", 1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //When using the Web part manager, do dispose the 
                //SPWeb object inside the web part manager class
                oWebpartMngr.Web.Dispose();
            }
        }
    }
}
Share SocialTwist Tell-a-Friend 

Set Audience Target to SharePoint Navigation May 18, 2009

Posted by tippu in : Sharepoint , comments closed

In this article I will show you how to add the Target Audience on the SharePoint Navigation. The SPNavigationNode class has a property called “Properties”, which allows us to added custom properties to the node. One of the Property is “Audience”, which is used for setting the target audience on the navigation node.

using (SPSite oSite = new SPSite("http://Tippu/sites/AudianceTargetTest"))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        SPNavigationNode oNode = oWeb.Navigation.GlobalNodes[0];

        if (oNode.Properties.Contains("Audience"))
            oNode.Properties["Audience"] = ";;;;SharepointGroup1,SharepointGroup2";
        else
            oNode.Properties.Add("Audience", ";;;;SharepointGroup1,SharepointGroup2");
    }
}

Thread Locking in C# using lock statement April 19, 2009

Posted by tippu in : C#, Threading , comments closed
Hi,   I am back on blogging on another new stuff which programmers use very rarely. Its on the Thread Locking. Many times we need to have a code block which needs to be executed only one at a time. After knowing the use of this statement, i started using it in many place on my application. The lock statement blocks a section of the code as critical section by obtaining the mutual-exclusion lock for a give object, executes the statement and releasing the lock.The sequence of execution of locking is not guarantee to be FIFO (First In First Out) even if it looks FIFO, so don’t have a logic in the code which is dependent on the sequence of execution. The lock statement can get you into trouble if its used incorrectly  by causing inadvertent deadlocks of your code. One more thing that need to be taken care while using the lock statement is the locking object.  Never use lock object as one of your class. This will lock your class and you may end up in deadlock. Always use a private object as a lock and avoid doing anything to this object except for locking and unlocking.

Below is a sample code that explains the use of lock statement for avoiding multiple file lock issue. From today onwards (why from today, from now onwards) when ever have a scenario that needs to have a similar locking do think of using the lock statement.

In my next blog, i will come up with thread synchronization, so be ready to crack on C# .net threading.

 

1: using System;

2: using System.Collections.Generic;

3: using System.ComponentModel;

4: using System.Data;

5: using System.Drawing;

6: using System.Linq;

7: using System.Text;

8: using System.Windows.Forms;

9: using System.IO;

10: using System.Xml;

11: 

12: namespace MultiThreadLockTest

13: {

14: public partial class Form1 : Form

15: {

16: //Always use private object for locking to avoid dead lock

17: private static object tippuLock;

18: delegate void SearchDelegate();

19: 

20: public Form1()

21: {

22: InitializeComponent();

23: tippuLock = new object();

24: }

25: 

26: public void ThreadAccessMethod()

27: {

28: FileStream fsTextFile = null;

29: StreamWriter oStmFileWriter = null;

30: XmlTextWriter datawriter = null;

31: 

32: ////put a lock on the object

33: lock (tippuLock)

34: {

35: try

36: {

37: fsTextFile = new FileStream(“d:\\test.txt”,

38: FileMode.Append, FileAccess.Write);

39: 

40: oStmFileWriter = new StreamWriter(fsTextFile);

41: 

42: oStmFileWriter.WriteLine(DateTime.Now.Ticks);

43: 

44: oStmFileWriter.Flush();

45: }

46: catch (Exception ex)

47: {

48: throw ex;

49: }

50: finally

51: {

52: if (oStmFileWriter != null)

53: {

54: oStmFileWriter.Close();

55: oStmFileWriter.Dispose();

56: }

57: if (datawriter != null)

58: {

59: datawriter.Close();

60: }

61: if (oStmFileWriter != null)

62: {

63: fsTextFile.Close();

64: fsTextFile.Dispose();

65: }

66: }

67: }

68: }

69: 

70: private void button1_Click(object sender, EventArgs e)

71: {

72: for (int i = 0; i <= 10; i++)

73: {

74: SearchDelegate dlgtSerach = new SearchDelegate(this.ThreadAccessMethod);

75: AsyncCallback cb = new AsyncCallback(SearchAsyncCallback);

76: IAsyncResult arSerach = dlgtSerach.BeginInvoke(cb, dlgtSerach);

77: }

78: }

79: 

80: public void SearchAsyncCallback(IAsyncResult ar)

81: {

82: SearchDelegate dlgt = (SearchDelegate)ar.AsyncState;

83: AsyncCallback cbs = new AsyncCallback(SearchAsyncCallback);

84: dlgt.EndInvoke(ar);

85: }

86: }

87: }

Share SocialTwist Tell-a-Friend 

WPF: Placing your WPF Application on the system tray March 9, 2009

Posted by tippu in : WPF , comments closed

Hi Guys,

After getting good response on one of my article on “Tray Notification”, I am now going to show you how to do the same thing on the Windows Presentation Framework (WPF). Adding It is straight forward as we do in the regular Windows Forms Application. To add the Tray notification to WPF, you just need to add the “System.Windows.Forms” assembly reference to your WPF project. Once you add the reference, you can create new instance of the “NotifyIcon” class and  use it in your WPF application. Lets me show you how to do this in step by step.

 

Step 1: Create a blank WPF Application project

image

 

 Step 2: Add reference to “System.Windows.Forms”

image

 

Step 3:  Declare a global variable for NotifyIcon, ContextMenuStrip and ToolStripMenuItem

private System.Windows.Forms.NotifyIcon TippuTrayNotify;
private System.Windows.Forms.ContextMenuStrip ctxTrayMenu;
private System.Windows.Forms.ToolStripMenuItem mnuExit;

NotofyIcon – This is the class which is used to show the application icon on the system tray.

ContentMenuStrip – This is the class which is used to show the context menu when the user right clicks on the system tray icon.

ToolStripMenuItem – This is the class which is used to show the menu item where the user performs the action on the context menu.

Usually in windows forms application, we used to do this by dragging and dropping the icons for the above mentioned classed on the form itself and assign property to it. Here in WPF world, its little different. We need to do some of the stuff manually, so lets continue our WPF tray notification application.

 

Step 4: 

Add the ToolstripMenuItem object to the ContextMenuStrip and then add the ContextMenuStrip to the NotifyIcon object. Assign the events for the menu item as shown in the sample code.

 

Enjoy WFP Programming…

- Tippu (Mubarak Musthafa)

 

Source Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace NotifyIconWPFSampl
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private System.Windows.Forms.NotifyIcon TippuTrayNotify;
        private System.Windows.Forms.ContextMenuStrip ctxTrayMenu;
        private System.Windows.Forms.ToolStripMenuItem mnuExit;
        private bool isAppExiting = false;

        public Window1()
        {
            InitializeComponent();

            //Create an instance of the NotifyIcon Class
            TippuTrayNotify = new System.Windows.Forms.NotifyIcon();

            // This icon file needs to be in the bin folder of the application
            TippuTrayNotify.Icon = new System.Drawing.Icon(“Application.ico”);

            //show the Tray Notify Icon
            TippuTrayNotify.Visible = true;

            //Create a object for the context menu
            ctxTrayMenu = new System.Windows.Forms.ContextMenuStrip();

            //Add the Menu Item to the context menu
            System.Windows.Forms.ToolStripMenuItem mnuExit = new System.Windows.Forms.ToolStripMenuItem();
            mnuExit.Text = “Exit”;
            mnuExit.Click += new EventHandler(mnuExit_Click);
            ctxTrayMenu.Items.Add(mnuExit);

            //Add the Context menu to the Notify Icon Object
            TippuTrayNotify.ContextMenuStrip = ctxTrayMenu;

        }

        void mnuExit_Click(object sender, EventArgs e)
        {
            isAppExiting = true;
            this.Close();
            TippuTrayNotify.Visible = false;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //When the application is closed, check wether the application is
            //exiting from menu or forms close button
            if (!isAppExiting)
            {
                //if the forms close button is triggered, cancel the event and hide the form
                //then show the notification ballon tip
                e.Cancel = true;
                this.Hide();
                TippuTrayNotify.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
                TippuTrayNotify.BalloonTipTitle = “Tippu Tray Notify”;
                TippuTrayNotify.BalloonTipText = “Tippu Tray Notify has been minimized to the system tray. To open the application, double-click the icon in the system tray.”;
                TippuTrayNotify.ShowBalloonTip(400);
            }
        }
    }
}

Share SocialTwist Tell-a-Friend 

Windows Forms: Placing your C# Application on the system tray November 23, 2008

Posted by tippu in : Uncategorized , comments closed

On this week end, my very close friend asked me about having a Windows application running with the icon on the system tray, just like the Google talk application. I told my friend that I will check on this, because I have done this on our good old Visual Basic 6.0 during the start of my carrier. I taught it should be straight forward in C# and it happened to be the same.

Step 1: Create a Windows Forms Application.

image 

 

Step 2: Drag and Drop the NotifyIcon control from Visual Studio Tools box onto the form.

image

 

Step 3: Drag and Drop the ContextMenuStrip control from Visual Studio Tools box onto the form.

image

 

Step 4: Click on the ContextMenuStrip control on the form and add "Restore Application" and "Exit" menu item and add click event for them.

image

 

Step 5: Click the "NotifyIcon1" control on the form and set the "ContextMenuStrip" to the context menu that we added on the form.

image

 

Step 6: After the following code to the forms and build the application. Add  the "SizeChanged" event to the form. When you run the application, the form will run in normal windows mode. When you minimize the application, the application goes to the system tray and shows the notification icon.

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;

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

        /// <summary>
        /// Show the form and set the window state to normal.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void restoreApplicationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            {
                Show();
                WindowState = FormWindowState.Normal;
                this.Focus();
            }
        }

        /// <summary>
        /// Close the application when the exit menu is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// When the form is resized, check the window state and hide the form if minimized.
        /// Set the notify icon visibility to true when window is minimized.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                Hide();
                notifyIcon1.Visible = true;
            }
            else
                notifyIcon1.Visible = false;
        }
    }
}

 

Step 7: Run the application and minimize the form, the notification icon will appear in the task bar.

image

 

Hope this helped you guys on how to add a application icon to the system tray.

Share SocialTwist Tell-a-Friend 

MOSS 2007 – Using Property Bag of SPWeb to store Metadata October 14, 2008

Posted by tippu in : Sharepoint , comments closed

Hi,

I came across the blog site of Roni about using Property Bag of SPWeb. In his blog he missed out on explaining how to remove the Property from the SPWeb after adding it. There might be scenario where we need to remove the Property from the property Bag. This Blog entry is the extension of the blog entry writte by Roni. http://www.sharepointblogs.com/roni/archive/2007/08/27/moss-2007-using-property-bag-of-spweb-to-store-metadata.aspx.

SPWeb.Properties.Remove(string pKey) doesn’t work for removing a property.

To remove a property use the following lines:

webCurrent.Properties[strKey] = null;
webCurrent.Properties.Update();

Navigation.QuickLaunch 1st Time shown as blank and page reload fixes QuichLaunch Issue October 10, 2008

Posted by tippu in : Sharepoint , comments closed

In one of my project, there was a requirement to modify the QuickLaunch for a site which was created dynamically through object model. When we modify the QuickLaunch or add a new SPNavigationNode, the QuickLaunch on the site comes as blank for the fist time. If you refresh the page, then the QuickLaunch shows the updated Navigation. First we taught that this is due to the timing mismatch of the publishing web object updating and the page load. Latter we found that after we created the site and viewed the site at least once, the navigation never get updated.

After digging into the issue, I found that the publishing web’s navigation doesn’t get refreshed, unless we load the all the publishing page once after we update the navigation.

Following snippet of code solves the issue.

using (SPSite oSite = new SPSite(“http://localhost/sites/TippuNavTest”))
{
SPWeb oWeb = null;
try
{
oWeb = oSite.OpenWeb(properties.RelativeWebUrl);
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(oWeb);
pubWeb.InheritCurrentNavigation = false;
List<PublishingPage> pages = new List<PublishingPage>();

foreach (PublishingPage page in pubWeb.GetPublishingPages())
{
if (page.IncludeInCurrentNavigation)
pages.Add(page);
}
pubWeb.Update();
pubWeb.Close();

}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oWeb != null)
oWeb.Dispose();
}
}

How to Set a ListViewWebPart’s Toolbar Type as Summary Web Part October 8, 2008

Posted by tippu in : Sharepoint , comments closed

When we are creating a ListViewWebPart through program, Even if we set the View for the ListViewWebPart, Sharepoint displays the web part with full toolbar property set on it. The only option that we can change this view is to set the View for the ListViewWebPart and add the webpart to the Web Part Manager. After adding the web part on the page, load the webpart again and get the view which is cached by the list view web part and update the Type by reading the xml node and updating the type to the desired toolbar type. Once the Toolbar type is set to “Freeform” (i.e Summary Toolbar), we can add the innerXml to the node having the CAML for showing the “add new item” link to the toolbar. Make sure the position attribute in the xml is “After”. This will make the web part to show the “add new item” link below the List View Web Part.

[code]

public static void SetWebPartToolbarAttribute(SPView spView, String AttributeValue)
{
string txt = spView.SchemaXml;

System.Reflection.PropertyInfo NodeProp = spView.GetType().GetProperty("Node",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

XmlNode node = NodeProp.GetValue(spView, null) as XmlNode;
XmlNode tBarNode = node.SelectSingleNode("Toolbar");

if (tBarNode != null)
{
XmlAttribute typeNode = tBarNode.Attributes["Type"];
tBarNode.RemoveAll();
tBarNode.Attributes.Append(typeNode);
typeNode.Value = AttributeValue;
}

if (String.Compare(AttributeValue, "Freeform", true) == 0)
{
string NewItemString = "";
XmlAttribute pos = tBarNode.OwnerDocument.CreateAttribute("Position");
pos.Value = pos.Value = "After";
tBarNode.Attributes.Append(pos);

switch (spView.ParentList.BaseTemplate)
{
case SPListTemplateType.DiscussionBoard:
NewItemString = "discussion";
break;
case SPListTemplateType.Links:
NewItemString = "link";
break;
case SPListTemplateType.Tasks:
NewItemString = "task";
break;
case SPListTemplateType.GenericList:
NewItemString = "item";
break;
case SPListTemplateType.DocumentLibrary:
NewItemString = "document";
break;
}

tBarNode.InnerXml = @"<IfHasRights><RightsChoices><RightsGroup PermAddListItems=""required"" /></RightsChoices><Then><HTML><![CDATA[ <table width=100% cellpadding=0 cellspacing=0 border=0 > <tr> <td colspan=""2"" class=""ms-partline""><IMG src=""/_layouts/images/blank.gif"" width=1 height=1 alt=""""></td> </tr> <tr> <td class=""ms-addnew"" style=""padding-bottom: 3px""> <img src=""/_layouts/images/rect.gif"" alt="""">&nbsp;<a class=""ms-addnew"" ID=""idAddNewItem"" href=""]]></HTML><URL Cmd=""New"" /><HTML><![CDATA["" ONCLICK=""javascript:NewItem(']]></HTML><URL Cmd=""New"" /><HTML><![CDATA[', true);javascript:return false;"" target=""_self"">]]></HTML><HTML>Add a new " + NewItemString + @"</HTML><HTML><![CDATA[</a> </td> </tr> <tr><td><IMG src=""/_layouts/images/blank.gif"" width=1 height=5 alt=""""></td></tr> </table>]]></HTML></Then></IfHasRights>";
}

spView.Update();
}

[/code]

Share SocialTwist Tell-a-Friend 
High Page Rank website
Powered by Blog.co.in and Zorg Directory
Powered By Indic IME