SharePoint postback problem after file download

For a customer I was creating a project where they needed to click a button and download a file.
This is basic ASP.net stuff, BUT in SharePoint there are some issues with this.

If you use this code, which is the code to push a file towards the client browser for download:

Response.Clear();
Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xml");
Response.CacheControl = "public";
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.Flush();

This code will work once,BUT next time you click the button it will not work.
Note: I’m using a byte array to publish, reason is that I created in this case an XML at runtime, this will be handled in an other blog

Solution:

We need to add Javascript to the button !!! Glimlach

 protected override void OnLoad(EventArgs e)
{
           public string ScriptRefresh =@"function Refresh()
                                        {
                                           window.setTimeout(
                                               function()
                                               {
                                                  _spFormOnSubmitCalled = false;
                                                }, 10);
                                           } ";  //This string represents the javascript fore this issue, it could be any kind of javascript.

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"Refresh",ScriptRefresh, true);     //Here we add the Javascript to the page ,ScriptRefresh = javascript, you could type it directly here if you want
btnDownLoadXML.OnClientClick =
"Refresh()";  //Here we add the javascript to the button

}

Thats actually all you need to do.
What you are doing behind the scene is tell SharePoint that the page is not submitted yet.

Hope it helps


Published: 12/22/2011 | 0  Comments | 0  Links to this post

How to use Live writer for creating Blog’s on SharePoint

 

When you want to configure your Live Writer to write Blog’s on SharePoint you must not select the option “SharePoint”.



Strange but true Glimlach

SNAGHTML2add71a

 

you must select ‘Other services’, next you just fill in the url of the site and your credentials and you are ready to go. Glimlach


Published: 2/22/2011 | 0  Comments | 0  Links to this post

Extra information on my page

With some customers I have noticed that this is a requirement they often want.
Is is really not complex , nevertheless

These are some option you can place underneath a page:
 
<div class="edit_createdby">
Created By:
<SharePointWebControls:FieldValue id="CreatedBy" FieldName="Created_x0020_By" runat="server">
</SharePointWebControls:FieldValue>
</div>
<div class="edit_createdon">
Created On:
<SharePointWebControls:FieldValue id="CreatedOn" FieldName="Created" runat="server" />
</div>
<div class="edit_editedby">
Last Edited By:
<SharePointWebControls:FieldValue id="EditedBy" FieldName="Modified_x0020_By" runat="server">
</SharePointWebControls:FieldValue>
</div>
<div class="edit_editedon">
Last Edited On:
<SharePointWebControls:FieldValue id="EditedOn" FieldName="Modified" runat="server" />
</div>
this is what you get underneath your page:
 

 
This is the code of the page:
 

<div id="authorinfo">

<span class="author"><span class="label">inhoud: </span><a href="mailto:"><SharePointWebControls:FieldValue ID="FieldValue2" FieldName="PublishingContactName" runat="server"></SharePointWebControls:FieldValue></a></span>

<span class="date"><span class="label">laatste wijziging:</span><SharePointWebControls:FieldValue ID="FieldValue1" FieldName="Modified" runat="server"></SharePointWebControls:FieldValue></span>

<div class="edit_editedby">laatst gewijzigd door: <SharePointWebControls:FieldValue id="EditedBy" FieldName="Modified_x0020_By" runat="server"></SharePointWebControls:FieldValue></div>

</div>

 

Nothing difficult but handy to know

 
 

Published: 2/11/2011 | 0  Comments | 0  Links to this post

Timer Jobs , example

TimerJobs just are a part of SharePoint they are very powerfull.
 
This example is a timerjob to send emails.
This timerjob runs in the code with a minute interval, this was just for testing purposes.
What it doe sin production is, checking a SharePoint calendar, if the calendar contains an item, and the date is the same as today, it will sent out the email.
This is an easy way for your customer to control the timerjob.
You can add more advanced stuff to get, according to some metadata from calendar item, an other mail message and so on.
It is deployed with a feature, but the timerjob is created whtin the feature, so we can remove the timerjob again if we disable the feature:
 
feature.xml
 

<?xml version="1.0" encoding="utf-8"?>

<Feature  Id="3ff27f32-95c7-48a4-8145-1e3905471e41"

          Title="ZI Intranet NewLetter"

          Description="Description for ZI Intranet NewLetter"

          Version="12.0.0.0"

          Hidden="FALSE"

          Scope="Site"

          ImageUrl="ventigrate_flower.gif"

          DefaultResourceFile="core"

          xmlns="http://schemas.microsoft.com/sharepoint/"

          ReceiverAssembly="TimerJob.Intranet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f16d8af2a207857"

          ReceiverClass="TimerJob.Intranet.ZI_Intranet_NewLetter">

</Feature>

 

Next we have the cs file of the feature, the actual code file.
In this class file I also created onother class which is used by the Timer Job itself
.


using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Administration;

using System.Web.UI.WebControls;

using Microsoft.SharePoint.Utilities;

using System.Net.Mail;

using Microsoft.SharePoint.Publishing;

using ZorgInspectie.Intranet.UserControls;

using System.Globalization;

using System.Configuration;

 

namespace TimerJob.Intranet

{

 

    public class ZI_Intranet_NewLetter : SPFeatureReceiver

    {

        //Varaible declaration

        string strTimerTitle = " Intranet News Letter sender";

 

        public override void FeatureActivated(SPFeatureReceiverProperties properties)

        {

            try

            {

                removeTimerJob(properties);

                // install the job

                using (SPSite site = (SPSite)properties.Feature.Parent)

                {

                    ZI_Intranet_NewLetter_TimerJob newsLetterJob = new ZI_Intranet_NewLetter_TimerJob(strTimerTitle, site.WebApplication);

 

                    SPMinuteSchedule schedule = new SPMinuteSchedule();

                    schedule.BeginSecond = 0;

                    schedule.EndSecond = 10;

                    schedule.Interval = 1;

                    newsLetterJob.Schedule = schedule;

                    newsLetterJob.Update();

 

                }

                createLists(properties);

            }

            catch (Exception ex)

            {

                Utility.LogError(ex);

            }

        }

 

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

        {

            try

            {

                removeTimerJob(properties);

                           }

            catch (Exception ex)

            {

                Utility.LogError(ex);

            }

        }

 

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)

        {

            // throw new Exception("The method or operation is not implemented.");

        }

 

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)

        {

            //    throw new Exception("The method or operation is not implemented.");

        }

 

        private void removeTimerJob(SPFeatureReceiverProperties properties)

        {

            SPSite site = properties.Feature.Parent as SPSite;

 

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

            {

                if (job.Name == strTimerTitle)

                {

                    job.Delete();

                    break;

                }

            }

        }

 

            }

 

This class is in the same cs file as the above.
But it is this class of which an object is created in the feature.

 

 

    public class ZI_Intranet_NewLetter_TimerJob : SPJobDefinition

    {

        #region Variables

        private string listName = String.Empty;

        private string webName = String.Empty;

        private string strTimerTitle = "Intranet News Letter sender";

        private List<ZI_NewsLetter_SortItem> lstMailItems = new List<ZI_NewsLetter_SortItem>();

        private string fieldLaatsteNieuws = String.Empty;

        #endregion

 

        public ZI_Intranet_NewLetter_TimerJob()

            : base()

        {

        }

 

        public ZI_Intranet_NewLetter_TimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

            : base(jobName, service, server, targetType) { }

 

        public ZI_Intranet_NewLetter_TimerJob(string jobName, SPWebApplication webApplication)

            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)

        {

            this.Title = strTimerTitle;

        }

        public override void Execute(Guid targetInstanceId)

        {

            base.Execute(targetInstanceId);

            try

            {

                string nieuwsbriefURL = Utility.RetrieveResourceItem("KalenderNieuwsBriefURL", WebApplication);

                SPList listKalendar = WebApplication.Sites[0].OpenWeb().GetListFromUrl(nieuwsbriefURL);

 

                foreach (SPListItem item in listKalendar.Items)

                {

                    DateTime tmpDate = (DateTime)item["Begintijd"];

                    DateTime tmpDateToday = (DateTime)System.DateTime.Today;

                    if (tmpDate.DayOfYear == tmpDateToday.DayOfYear)

                    {

                        fieldLaatsteNieuws = Utility.RetrieveResourceItem("fieldLaatsteNieuws", WebApplication);

                        listName = Utility.RetrieveResourceItem("AnnouncementsListName", WebApplication);

                        retrieveNewsLetterItems(fieldLaatsteNieuws);

                        sendMail();

                        break;

                    }

                    else if (tmpDate.DayOfYear > tmpDateToday.DayOfYear)

                    {

                        break;

 

                    }

                }

            }

            catch (Exception ex)

            {

                throw;

            }

        }

 


Published: 1/13/2011 | 0  Comments | 0  Links to this post

Sending mails to all sharepoint users

Sometimes you need to send email yourself to people whitin your company from whitin SharePoint. This piece of code shows you how !!!
 

 

 

        private void sendMail()

        {

            try

            {

                SPSecurity.RunWithElevatedPrivileges(delegate()

                {

                    bool blnSendMail = false;

                    StringBuilder stringBuilder = new StringBuilder();

 

                    //Loop through groups to retrieve all users

                    foreach (SPGroup tmpGroup in WebApplication.Sites[webName].OpenWeb().Groups)

                    {

                        foreach (SPUser tmpUser in tmpGroup.Users)

                        {

                            if (String.IsNullOrEmpty(tmpUser.Email) && tmpUser.Email.Length > 2)

                            {

                                stringBuilder.Append(tmpUser.Email + ";");

                                blnSendMail = true;

                            }

                        }

                    }

 

                    if (blnSendMail)

                    {

 

                        string outboundHost = WebApplication.OutboundMailServiceInstance.Server.Address;

                        string outboundReplyTo = WebApplication.OutboundMailReplyToAddress;

                        string outboundFrom = WebApplication.OutboundMailSenderAddress;

                        //These settings can then be used to create a System.Net.Mail message...

 

                        System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();

                        smtpclient.Host = outboundHost;

                        smtpclient.UseDefaultCredentials = true;

                        smtpclient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

 

                        MailMessage mail = new MailMessage();

 

 

                        mail.To.Add(new MailAddress(stringBuilder.ToString()));

                        mail.From = new MailAddress("Nieuwsbrief@customer.be");

                        mail.Subject = "Nieuwsbrief";

                        mail.IsBodyHtml = true;

 

                        mail.Body = createMail("Nieuwsbrief");

 

                        smtpclient.Send(mail);

                        lstMailItems.Clear();

                    }

 

                });

 

            }

            catch (Exception ex)

            {

                Utility.LogError(ex);

            }

 

        }


Published: 1/13/2011 | 0  Comments | 0  Links to this post

Events on a list with a feature ???

Must of the time you would asign a SPItemEventReceiver in the XAML file of your feature, but the main problem with that is that you can asign it to a listtemplateID, and not to one specific list.
Which is great if you want al those list to perform this action, you can generat a customlisttemplate and create just on instance of that .... to much overhead ,or you can always do a check to see if that list should perform the action or not and so on.

In this case we asign the SPItemEventReceiver only to 1 specific list which is much easier.
This is de the code for the feature.xml:
 

<?xml version="1.0" encoding="utf-8"?>

<Feature Id="37396b05-c17a-4713-b217-a3c7a6904616"

Title="ZI EventHandler e-Flash"

Description="Description for ZI EventHandler e-Flash"

Version="12.0.0.0"

Hidden="FALSE"

Scope="Web"

DefaultResourceFile="core"

ImageUrl="ventigrate_flower.gif"

xmlns="http://schemas.microsoft.com/sharepoint/"

ReceiverAssembly="SharePoint.Intranet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f16d8af2a207857"

ReceiverClass="SharePoint.Intranet.ZI_Intranet_EFlash_FeatureReceiver">

</Feature>

the next is the code for the cs file which is called in the feature. This cs file contains two classes.
The class for the feature event, because we want this thing to be installed when our feature is activated, and we want this to disappear when our feature is deactivated:
 

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

using ZorgInspectie.Intranet.UserControls;

using Microsoft.SharePoint.Utilities;

using Microsoft.SharePoint.Administration;

using System.Net.Mail;

namespace SharePoint.Intranet

{

class ZI_Intranet_EFlash : SPItemEventReceiver

{

//Varaible declaration

private const string fldSendMail = "Send e-Flash";

public override void ItemAdded(SPItemEventProperties properties)

{

try

{

SPSecurity.RunWithElevatedPrivileges(delegate()

{

if (properties.ListItem != null && properties.ListItem[fldSendMail] != null && properties.ListItem[fldSendMail].ToString().Equals("True"))

{

bool blnSendMail = false;

StringBuilder stringBuilder = new StringBuilder();

SPGroupCollection colGroups = properties.OpenWeb().Groups;

foreach (SPGroup tmpGroup in colGroups)

{

foreach (SPUser tmpUser in tmpGroup.Users)

{

if (String.IsNullOrEmpty(tmpUser.Email) && tmpUser.Email.Length > 2)

{

stringBuilder.Append(tmpUser.Email + ";");

blnSendMail = true;

}

}

}

if (blnSendMail)

{

SPUtility.SendEmail(properties.ListItem.ParentList.ParentWeb, true, true, stringBuilder.ToString(), "e-Flash " + properties.ListItem.Title, "test");

}

else

{

stringBuilder.Append(test@test.com);

string outboundHost = properties.OpenWeb().Site.WebApplication.OutboundMailServiceInstance.Server.Address;

string outboundReplyTo = properties.OpenWeb().Site.WebApplication.OutboundMailReplyToAddress;

string outboundFrom = properties.OpenWeb().Site.WebApplication.OutboundMailSenderAddress;

//These settings can then be used to create a System.Net.Mail message...

System.Net.Mail.SmtpClient smtpclient = new System.Net.Mail.SmtpClient();

smtpclient.Host = outboundHost;

smtpclient.UseDefaultCredentials = true;

smtpclient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

MailMessage mail = new MailMessage();

mail.To.Add(new MailAddress("test@test.com"));

mail.From = new MailAddress("test@test.com");

mail.IsBodyHtml = true;

string listitemURL = properties.OpenWeb().Site.Url + "/Lists/" + properties.ListItem.ParentList + "/DispForm.aspx?ID=" + properties.ListItem.ID;

mail.Body = createMailMessage(properties.ListItem.Title, "test", listitemURL);

smtpclient.Send(mail);

}

}

});

}

catch (Exception ex)

{

Utility.LogError(ex);

}

}

private string createMailMessage(string titel, string content, string itemURLs)

{

try

{

string mail = string.Format(@"<HTML>

<BODY>

<H1><B>{0}</B></H1>

<BR>

<p>{1}</p>

<BR >

<div>

</div >

<a target='new' href='{2}'>{3}</a>

</BODY>

</HTML>", titel, content, itemURLs, "Look at Intranet");

mail = mail.Replace("titel_to_replace", titel);

mail = mail.Replace("body_to_replace", content);

return mail;

}

catch (Exception)

{

return null;

throw;

}

}

public override void ItemAdding(SPItemEventProperties properties)

{

}

public override void ItemUpdated(SPItemEventProperties properties)

{

//base.ItemUpdated(properties);

}

public override void ItemUpdating(SPItemEventProperties properties)

{

//base.ItemUpdating(properties);

}

}

class ZI_Intranet_EFlash_FeatureReceiver : SPFeatureReceiver

{

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

try

{

SPSecurity.RunWithElevatedPrivileges(delegate()

{

SPSite site = SPContext.Current.Site as SPSite;

SPWeb web = site.OpenWeb();

SPList Announcement = web.Lists["Announcement Lists"];

string assemblyName = "SharePoint.Intranet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f16d8af2a207857";

string className = "SharePoint.Intranet.ZI_Intranet_EFlash";

Announcement.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);

});

}

catch (Exception ex)

{

throw;

}

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)

{

try

{

SPSecurity.RunWithElevatedPrivileges(delegate()

{

SPSite site = SPContext.Current.Site as SPSite;

SPWeb web = site.OpenWeb();

SPList Announcement = web.Lists["Announcement Lists"];

Announcement.EventReceivers[0].Delete();

});

}

catch (Exception ex)

{

}

}

public override void FeatureInstalled(SPFeatureReceiverProperties properties)

{

//throw new Exception("The method or operation is not implemented.");

}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)

{

// throw new Exception("The method or operation is not implemented.");

}

}

}

 

Published: 1/10/2011 | 0  Comments | 0  Links to this post

List selector for webpart

This is an easy way for retrieving a list name , if you needed in a webpart property.
 
We need to create an extra class;
 

using System;

using System.Text;

using System.Collections.Generic;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using ZorgInspectie.Intranet.WebParts;

 

Namespace Intranet

{

    class ListSelectEditorPart : EditorPart

    {

        private TextBox txtListUrl;

        private Button _selectList;

        private String WebPartName = String.Empty;

 

        public ListSelectEditorPart(string webPartID, string webpartname)

        {

            this.ID = "ListSelectEditorPart" + webPartID;

            this.Title = "Select a list";

            this.WebPartName = webpartname;

        }

 

        protected override void CreateChildControls()

        {

            base.CreateChildControls();

            txtListUrl = new TextBox();

            //_listUrl.Enabled = false;

            Controls.Add(txtListUrl);

            _selectList = new Button();

            _selectList.OnClientClick = "javascript:launchPicker();";

            _selectList.Text = "...";

            Controls.Add(_selectList);

        }

 

        public override void SyncChanges()

        {

            EnsureChildControls();

 

            if (WebPartName.Equals("HomePageNews"))

            {

                HomePageNews webPart = WebPartToEdit as HomePageNews;

                if (webPart != null)

                {

                    txtListUrl.Text = webPart.ListUrl;

                }

            }

 

            else if (WebPartName.Equals("BulletinBoard"))

            {

                BulletinBoard webPart = WebPartToEdit as BulletinBoard;

                if (webPart != null)

                {

                    txtListUrl.Text = webPart.ListUrl;

                }

            }

        }

        public override bool ApplyChanges()

        {

            EnsureChildControls();

 

 

            if (WebPartName.Equals("HomePageNews"))

            {

                HomePageNews webPart = WebPartToEdit as HomePageNews;

                if (webPart != null)

                {

                    webPart.ListUrl = txtListUrl.Text;

                }

            }

 

            else if (WebPartName.Equals("BulletinBoard"))

            {

                BulletinBoard webPart = WebPartToEdit as BulletinBoard;

                if (webPart != null)

                {

                    webPart.ListUrl = txtListUrl.Text;

                }

            }

            return true;

        }

 

        protected override void OnLoad(EventArgs e)

        {

            base.OnLoad(e);

            string webLocale = SPContext.Current.Web.Locale.LCID.ToString();

            Page.ClientScript.RegisterClientScriptInclude("PickerTreeDialog", string.Format("/_layouts/{0}/PickerTreeDialog.js", webLocale));

 

            RegisterSelectListScript();

        }

 

        private void RegisterSelectListScript()

        {

            StringBuilder launchPicker = new StringBuilder();

            launchPicker.Append("<SCRIPT LANGUAGE='JavaScript' >");

            launchPicker.Append("function launchPicker()\n");

            launchPicker.Append("{\n");

            launchPicker.Append("   var listurlfield = document.getElementById(\"" + txtListUrl.ClientID + "\");\n");

            launchPicker.AppendFormat("   var defaulturl = '{0}';\n", SPContext.Current.Web.ServerRelativeUrl);

            launchPicker.Append("   var url = defaulturl;\n");

            launchPicker.Append("   if(listurlfield != null && listurlfield.value != '')\n");

            launchPicker.Append("   {\n");

            launchPicker.Append("       url = listurlfield.value.substring(0,listurlfield.value.lastIndexOf('/'));");

            launchPicker.Append("   }\n");

            launchPicker.Append("   var callback=function(arr)\n");

            launchPicker.Append("   {\n");

            launchPicker.Append("       if(arr==null || arr==undefined)\n");

            launchPicker.Append("           return;\n");

            launchPicker.Append("       var site=arr[1];\n");

            launchPicker.Append("       var list=arr[2];\n");

            launchPicker.Append("       if(list != '')\n");

            launchPicker.Append("       {\n");

            launchPicker.Append("           listurlfield.value = site + (site == '/' ? '' : '/') + list;\n");

            launchPicker.Append("       }\n");

            launchPicker.Append("       " + Page.ClientScript.GetPostBackEventReference(txtListUrl, string.Empty) + ";\n");

            launchPicker.Append("   }\n");

            launchPicker.Append("LaunchPickerTreeDialog(\'CbqPickerSelectListTitle','CbqPickerSelectListTitle','listsOnly',\"\",url,null,\"\",\"\",\"/_layouts/images/generic.png\", 0, callback );\n");

            launchPicker.Append("}\n");

            launchPicker.Append("</SCRIPT>");

 

            if (!Page.ClientScript.IsClientScriptBlockRegistered("launchPicker"))

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "launchPicker", launchPicker.ToString());

        }

 

    }

}

 

The next lines are the code of my code file for my webpart;

using System;

using System.Collections.Generic;

using System.Runtime.InteropServices;

using System.Web.UI;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint;

using System.Web.UI.WebControls;

using ZorgInspectie.Intranet.UserControls;

using Microsoft.SharePoint.WebPartPages;

using System.ComponentModel;

 

namespace ZorgInspectie.Intranet.WebParts

{

     [ToolboxItemAttribute(false)]

    public class BulletinBoard : Microsoft.SharePoint.WebPartPages.WebPart, IWebEditable

    {

        private bool _error = false;

        public string _listUrl;

        private const string _ascxPath = @"~/_controltemplates/ZI_Intranet/BulletinBoard.ascx";

 

        [Browsable(false),

        Personalizable(PersonalizationScope.Shared)]

        public string ListUrl

        {

            get { return _listUrl; }

            set { _listUrl = value; }

        }

 

 

 

        /// <summary>

        /// Create all your controls here for rendering.

        /// Try to avoid using the RenderWebPart() method.

        /// </summary>

        ///

        protected override void CreateChildControls()

        {

            if (!_error)

            {

                try

                {

 

                    this.Title = "Bulletin Board";

                    Control control = Page.LoadControl(_ascxPath);

                    Controls.Add(control);

 

                    //bulletinBoardUserControl = (UserControl)Page.LoadControl(@"~/_controltemplates/ZI_Intranet/BulletinBoard.ascx");

                    //this.Controls.Add(bulletinBoardUserControl);

                }

                catch (Exception ex)

                {

                    HandleException(ex);

                }

            }

        }

 

 

        #region IWebEditable Members

 

        EditorPartCollection IWebEditable.CreateEditorParts()

        {

            List<EditorPart> editors = new List<EditorPart>();

 

            // Add the base editor parts

            EditorPartCollection baseParts = base.CreateEditorParts();

            foreach (EditorPart basePart in baseParts)

                editors.Add(basePart);

 

            editors.Add(new ListSelectEditorPart(this.ID, "BulletinBoard"));

            return new EditorPartCollection(editors);

        }

 

        object IWebEditable.WebBrowsableObject

        {

            get { return this; }

        }

 

        #endregion

 

    }

}

 

 

It's very easy and very handy.

 

 

 

grtz 

 

 


 
 

Published: 12/14/2010 | 1  Comment | 0  Links to this post

Using the SharePoint taxonomy fields

Taxonomy is a new thing in SharePoint 2010, it nice to reuse in your own ussercontrols.
Check out the code !
 
Add these reference in your ascx file
 

<%@ Register TagPrefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Now you can easly user the Taxonomy picker:

<td>
<Taxonomy:TaxonomyWebTaggingControl ID="taxDepartment" runat="server" Width="100">
</Taxonomy:TaxonomyWebTaggingControl>
</td>

You can now easly play arround with code and the fields acutally.

Here you will find some code I used to add certan Taxonomy groups to the fields:

Add the following reference to your project or class

using Microsoft.SharePoint.Taxonomy;

 

Code:

private void findTaxonomieValues()

{

try

{

if (SPContext.Current.Site != null)

{

TaxonomySession taxonomySession = new TaxonomySession(SPContext.Current.Site, false);

TermStore termStore = taxonomySession.TermStores[0];

taxDepartment.SSPList = termStore.Id.ToString();

taxDomein.SSPList = termStore.Id.ToString();

taxTrefwoorden.SSPList = termStore.Id.ToString();

foreach (Group taxGroup in termStore.Groups)

{

if (taxGroup.Name.Equals("Departementen en diensten"))

{

taxDepartment.GroupId = taxGroup.Id;

taxDepartment.TermSetList = taxGroup.TermSets[0].Id.ToString();

}

if (taxGroup.Name.Equals("Kennisdomeinen"))

{

taxDomein.GroupId = taxGroup.Id;

taxDomein.TermSetList = taxGroup.TermSets[0].Id.ToString();

}

if (taxGroup.Name.Equals("Trefwoorden"))

{

taxTrefwoorden.GroupId = taxGroup.Id;

taxTrefwoorden.TermSetList = taxGroup.TermSets[0].Id.ToString();

}

}

}

}

catch (Exception ex)

{

PortalLog.LogString(string.Format("CUSTOM ERROR LOG" + Environment.NewLine + "{0}", ex.Message));

SPUtility.TransferToErrorPage(ex.Message);

}

}

 

This is the result actually:

http://www.moss2007.be/blogs/sebastian/Lists/Photos/taxonomyfields.PNG


Published: 10/15/2010 | 0  Comments | 0  Links to this post

Creating Lists based on List Template

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{
try
{
  using (SPWeb spWeb = SPContext.Current.Web)

{

SPListTemplateCollection spListTemplateCollection = SPContext.Current.Site.GetCustomListTemplates(SPContext.Current.Web);

foreach (SPListTemplate spListTemplate in spListTemplateCollection)

{

if (!CheckListOnWeb(spListTemplate.Name, spWeb))

{

spWeb.Lists.Add(spListTemplate.Name, "", spListTemplate);

spWeb.Lists[spListTemplate.Name].OnQuickLaunch = true;

}

}

spWeb.Update();

}

}

catch (Exception ex)

{

PortalLog.LogString("Feature List Creator ERROR =" + ex.Message);

}

}


Published: 10/13/2010 | 0  Comments | 0  Links to this post

Check if a list exist on an SPWeb

private static bool CheckListOnWeb(string title, string url, SPWeb web)

{

try

{

return web.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, title));

}

catch (Exception ex)

{

Microsoft.Office.Server.Diagnostics.PortalLog.DebugLogString(Microsoft.Office.Server.Diagnostics.PortalLogLevel.Critical, ex.Message);

return false;

}

}


Published: 10/7/2010 | 0  Comments | 0  Links to this post
 Next >>