hicham's profilehicham Boutaleb <C'est ...PhotosBlogNetwork Tools Help

hicham Boutaleb <C'est par le bien faire que se crée le bien etre>

SharePoint,Linq,Reporting Services

hicham boutaleb

Occupation
Location
September 25

Building a Company Contact Web Part Using ASP.NET Ajax and JSON

First we have to create a custom SharePoint list that contains a default title, company name, contact person, city, and country fields(set
the column types of all columns to a single line of text) ,as it shows the figure below:

Sans titre

The idea behind the company contact web part is that if you type in the name of the company
and click the AutoFill button, the web part will call a web service that retrieves the rest of the form
information for you from the ContactInfo SharePoint list. The web service will return the data in
JSON format, so the client-side application needs to be able to deal with that.
In the next step, you will create the server side of the company contact application. Add a new
web service to the AskMe2 project; make sure the Place Code in Separate File check box is not
checked, and name the web service ContactService.asmx.

The ContactService web service returns a JSON message containing all contact information.
The ContactService web service will return a JSON message that looks like this:
{“ContactPerson”:”[value]”, “City”:”[value]”, “Country”:”[value]”}

The following listing shows the complete implementation of the ContactService web service. Make sure
to add a reference to the Microsoft.SharePoint assembly.

<%@ WebService Language=”C#” Class=”LoisAndClark.CompanyContact.ContactService”%>
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using Microsoft.SharePoint;
using System.Web.Script.Services;
namespace hichamveo{
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ContactService : System.Web.Services.WebService
{
public ContactService()
{
}
[WebMethod]
public string GetContactInfo(string strCompanyName)
{
string strResponse = “\”ContactPerson\”:\”{0}\”, \”City\”:\”{1}\”, \”Country\”:\”{2}\””;
string strUrl = “site's url”;

try
       {
           using(SPSite objSites=new SPSite(strUrl))
           {
               using(SPWeb objSite=objSites.OpenWeb())
               {
                   SPList objContactList = objSite.Lists["ContactInfo"];
                   foreach(SPListItem objListItem in objContactList.Items)
                   {
                       string strName = objListItem["CompanyName"].ToString();
                       if(strName==strCompanyName)
                       {
                           string strContact=objListItem["ContactPerson"].ToString();
                           string strCity = objListItem["City"].ToString();
                           string strCountry = objListItem["Country"].ToString();

                           strResponse = "{" + string.Format(strResponse, strContact, strCity, strCountry) + "}";
                           break;
                       }
                   }
               }
           }

           return strResponse;
       }
       catch(Exception)
       {
           throw;
       }
   }

Note1 The GetContactInfo() method returns a JSON message.

Note2 Attention to naming namespace, it should not be like "aaaa.bbbb" because when calling the web service, the javascript class proxy takes the form namespace.classeName.methodeName for calling the the web service's method.
So if you name your namespace "aaaa.bbbb ", the call will take the form:
"aaaa.bbbb.classename.methodename" which will generate an error

Now,we will add a single registration of a ScriptManager object to the master page
of a SharePoint site.

The following procedure shows how to use SharePoint Designer to add a single
ScriptManager registration to the default master page of a SharePoint site.

1. Open a browser and navigate to the SharePoint site that you want to add Ajax-enabled web
parts to.
2. Choose File ->Edit with Microsoft Office SharePoint Designer. This opens the SharePoint
site in SharePoint Designer.
3. Expand the _catalogs folder.
4. Expand the masterpage gallery.
5. Double-click default.master. This opens default.master in SharePoint Designer.
6. Switch to Code view.
7. Locate the registration for the web part manager. This looks like the following code fragment:
<WebPartPages:SPWebPartManager id=”m” runat=”Server” />
8. Add the following registration for a ScriptManager object to this page, right after the registration
for the web part manager:
<asp:ScriptManager ID=”theScriptManager” runat=”Server”/>
9. Save the page and close SharePoint Designer.

The complete code for the CompanyContactClient web part :

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace AjaxClient
{
    [Guid("7b7b741e-3f5a-4df9-bf28-5b0ee77234d6")]
    public class AjaxClient : System.Web.UI.WebControls.WebParts.WebPart
    {
        public AjaxClient()
        {
            PreRender += new EventHandler(PerformanceCounterWebPart_PreRender);
        }

        void PerformanceCounterWebPart_PreRender(object sender,EventArgs e)
        {

            if(!Page.ClientScript.IsClientScriptBlockRegistered("JSON"))
            {
                Page.ClientScript.RegisterClientScriptInclude("JSON", "/wpresources/json.js");
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("AJAX"))
            {
                Page.ClientScript.RegisterClientScriptInclude("AJAX", "/wpresources/ajax2.js");
            }
        }
        protected override void CreateChildControls()
        {
            try
            {
                string strPath = "http://web service's url/ContactService.asmx";//web service's url
                ServiceReference objReference = new ServiceReference();
                objReference.Path = strPath;

                Control ctlManager=Page.Master.FindControl("theScriptManager");
                ScriptManager objManager = ctlManager as ScriptManager;
                objManager.Services.Add(objReference);

                ScriptReference objScript=new ScriptReference("/wpresources/ajax2.js");
                objManager.Scripts.Add(objScript);

                string strCompanyName = "Name: <input id=\"CompanyName\" type=\"text\" />";
                Controls.Add(new LiteralControl(strCompanyName));

                string strAutoFill = "<input id=\"AutoFill\" type=\"button\" value=\"AutoFill...\" onclick=\"AutoFillRequest();\" /><br/>";
                Controls.Add(new LiteralControl(strAutoFill));

                string strContactPerson = "Contact: <input id=\"ContactPerson\" type=\"text\" /><br/>";
                Controls.Add(new LiteralControl(strContactPerson));

                string strCity = "City: <input id=\"City\" type=\"text\" /><br/>";
                Controls.Add(new LiteralControl(strCity));

                string strCountry = "Country: <input id=\"Country\" type=\"text\" /><br/>";
                Controls.Add(new LiteralControl(strCountry));
            }

            catch(Exception ErrorWebPart)
            { Controls.Add(new LiteralControl(ErrorWebPart.Message)); }

        }
    }
}

The final part of the company contact ASP.NET Ajax solution is the content of the ajax.js
JavaScript library. It contains a function called AutoFillRequest() that calls the ContactService web
service. A callback function called OnAutoFillResponse() converts the web service response to a
JavaScript object and uses the object to set the values of the contact person, city, and country fields.
The content of the ajax.js JavaScript library looks like :

function AutoFillRequest()
{
    var objCompanyName=document.getElementById("CompanyName");
    hichamveo.ContactService.GetContactInfo(objCompanyName.value,OnAutoFillResponse);
}

function OnAutoFillResponse(strResult)
{
    var objContact=eval('(' + strResult + ')');
    var objContactPerson = document.getElementById("ContactPerson");
    objContactPerson.value =objContact.ContactPerson;
    var objCity = document.getElementById("City");
    objCity.value = objContact.City;
    var objCountry = document.getElementById("Country");
    objCountry.value = objContact.Country;
}

The company contact web part:

Sans titre  

Sans titre

June 30

HOW CAN YOU DEBUG YOUR WEB PARTS

Whenever an error occurs in a web part, Microsoft Office SharePoint Server 2007 shows a generic error message. If
you want to see a detailed error message, you should open the web.config file of the SharePoint web application
that contains the web part, locate the <SafeMode> node, and set the CallStack attribute to true. If you want to
be able to see more than a generic server error message, you should locate the <customErrors> element and set
the mode attribute to Off.
You do not need to set the debug property of the <compilation> element to true to be able to debug a web
part. This setting tells ASP.NET to generate symbol tables (.pdb files) when compiling pages. Since your web part
code is contained in an assembly, you can debug the necessary .pdb files by building a Debug version of the web
part library. When the debug symbols are present, you can debug web parts by attaching to the process (an
instance of w3wp.exe).
However, if you want to be able to debug web parts by letting Visual Studio 2005 auto-attach to the process,
you do need to set the debug attribute of the <compilation> attribute to true. In that case, you also need to raise
the trust level for the SharePoint web application containing your web part to WSS_Medium or greater.
Be careful: setting the debug attribute of the <compilation> attribute to true has an undesirable side effect.
Every time you run the web part library project, a .bak copy of your web application’s web.config file is created.
The blog post “Debugging web parts – a full explanation of the requirements,” written by Maurice Prather,
discusses the previously discussed techniques in detail. The blog post can be found at the following location:
http://www.bluedoglimited.com/SharePointThoughts/ViewPost.aspx?ID=60.
Whenever you are auto-attaching to a process in Visual Studio 2005, the web server is restarted in order to
recycle the w3wp.exe process hosting your web part. This is overkill. Instead, it is much faster if you just restart the
application pool that hosts the SharePoint web application containing your web part and then manually attach to the
process hosting your web part. You can restart the application pool via iisapp.vbs (located in the [drive letter]:\windows\
system32 folder) using the following command:
iisapp.vbs /a “[application pool name]” /r
You can make attaching to this process even easier by installing the Debugger feature for SharePoint, created
by Jonathan Dibble. This feature adds a new menu item to the Site Actions menu of a SharePoint site and is
described in detail in the blog post “Debugger ‘Feature’ for SharePoint ” at http://blogs.msdn.com/
sharepoint/archive/2007/04/10/debugger-feature-for-sharepoint.aspx. The feature can be
downloaded from the SharePoint 2007 Features site at CodePlex (http://www.codeplex.com/features/
Release/ProjectReleases.aspx?ReleaseId=2502). This list of free SharePoint features is maintained by
Scot Hillier.

Mots clés Technorati : ,,,,
June 12

[MOSS 2007]Afficher des messages d'erreur explicites

Au cours de la mise en place de l' authentification par formulaire "Forms Authentication" comme publié sur le blog de Gael Duhamel,j'ai eu un petit soucis sur mon Appli dont je ne connais pas la source exactement,et après une longue discussion avec Gael il m'a proposer une astuce qui m'a permet de bien identifier mon problème,et que je veux partager avec vous afin d'afficher des messages explicites sur vos erreurs au lieu d' avoir une description standard de ce type:

Unknown Error
Troubleshoot issues with Windows SharePoint Services.

 

donc vous n'avez qu'a modifier le Web.config de votre application sharepoint située dans

Lecteur Local:\Inetpub\wwwroot\wss\VirtualDirectories\[repertoire du site] (par exemple 84) ,chercher l'entrée "CallStack" et modifier son statut a "true" pour afficher la pile des erreurs:

<SafeMode MaxControls="200" CallStack="true" DirectFileDependencies="10" TotalFileDependencies="50" AllowPageLevelTrace="false">

En suite vous devez modifier l'entrée "CustomErrors" pour afficher les messages d'erreurs:

<customErrors mode="Off" />

Mots clés Technorati : ,,

[MOSS 2007]Both Windows SharePoint Services Usage logging and Office SharePoint Usage Processing must be enabled to view usage reports.

Pour voir l'etat d'usage de votre site "Site Usage Reports",vous devez activer cette option dans votre environnement sharepoint en procedant par les etapes suivantes:

1-dans la barre a gauche du site d'administration sharepoint,sous "Shared Services Administration" cliquez sur votre SSP.

img7   

2-sur cet ecran et dans la rubrique "Office SharePoint Usage Reporting",cliiquez sur "Usage reporting"

img5  

3-En suite sur la page "Configure Advanced Usage Analysis Processing" cochez les 2 checkboxe comme le montre l'image ci-dessous:

img1  

 

comme ca vous pouvez acceder aux statistiques d'usage de votre :

img8

Adding Permission Levels

To create your own combination of permissions to meet specific site management needs, you can
create your own permission level sets as follows:
1. Navigate to a site having unique permission where you are the administrator.
2. From the site’s home page, click the Site Settings option from the Site Actions menu.

Sans titre

 

3. On the Site Settings page, in the Users and Permissions section, click the Advanced Permissions
link.

Sans titre

 

4. On the Permissions page, click the Settings link to view the Settings menu.
5. Select the Permission Levels option from the Settings menu.

 

Sans titre

 

6. If the current site is not the top-most site, a link will be available under See Also in the left
navigation area called Manage Permission Levels on Parent Web Site. Click this link.
7. On the Permission Levels page, click the Add a Permission Level link.

 

Sans titre

 

8. On the Add a Permission Level page, enter the following:
a. In the Name and Description section, enter the name for the new permission level. You
can also enter an optional description. The description is presented next to the name
when the permission level is listed for selection.
b. In the Permissions section, check the check boxes in front of all permissions that the
permission level should include.

Sans titre

NB:In my new permission level i selected all permissions.

c. Once all of the necessary information has been entered, click the Create button.
The new permission level is created, and you are returned to the Permission Levels page.

Web Part permettant d'uploader un fichier dans son liste des documents partagés

durant mes premiers pas sur sharepoint j'ai realisé un bout de code simple et intuitif qui me permet d'uploader un fichier dans ma liste des Documents Partagés:
 
sing System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Collections;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Net;
using System.Net.Mail;
namespace SharePoint.AspNetExample
{
    [Guid("57edfdc6-361a-4813-a7f2-1e261c5ad48b")]
    public class NormalPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        //le control d'uploade
        FileUpload _objFileUpload = new FileUpload();

        protected override void CreateChildControls()
        {
            Controls.Add(_objFileUpload);
            Button btnUpload = new Button();
            btnUpload.Text = "Save File";
            this.Load += new System.EventHandler(btnUpload_Click);
            LiteralControl space = new LiteralControl("&nbsp;");
            Controls.Add(space);
            Controls.Add(btnUpload);
            LiteralControl backSpace = new LiteralControl("<br>");
            Controls.Add(backSpace);
        }
        private void btnUpload_Click(object sender, EventArgs e)
        {
            this.SiteCollectionUrl = "url de votre site sharepoint";
            using (SPSite objSite = new SPSite(SiteCollectionUrl))
            {
                using (SPWeb objWeb = objSite.OpenWeb())
                  {
                    SPList objList=null;
                    foreach(SPList item in objWeb.Lists)
                    {
                        if (item.Title.Equals("Shared Documents"))//pour recuperer votre liste de documents partagés et faire attention si vous utiliser une version "francais"
                       // de MOSS 2007 le nom sera "Documents partagés" 
                        objList=item;
                    }
                    //SPList objList = objWeb.Lists["Documents partagés"];//ListName];
                    if (_objFileUpload.HasFile)
                    {
                        objList.RootFolder.Files.Add(_objFileUpload.FileName,_objFileUpload.PostedFile.InputStream, true);
                    }
                }
            }         
                     
        }
 
   private string _strSiteCollectionUrl;
        [Personalizable(PersonalizationScope.Shared), WebBrowsable(true), WebDisplayName("Site Collection URL"), WebDescription("Enter the URL of the site collection that contains the list a document is uploaded to")]
        public string SiteCollectionUrl
        {
            get { return _strSiteCollectionUrl; }
            set { _strSiteCollectionUrl = value; }
        }

    }
}
maintenant ne vous faut que configurer votre projet et deployer votre web part dans le GAC.
N.B:sur cet article j'ai pas entamé la methode comment parametrer le projet sharepoint et deploiment.
 
 

Rend un bloc de code transactionnel

vous pouvez rendre tout un bout de code transactionnel avec l'objet "TransactionScope",au lieu de creer un objet transaction et l'affecté a chaque commande.
voyons  comment cet objet peut nous simplifier la vie en utilisation avec des commandes linq:
 

using (System.Transactions.TransactionScope scope =new System.Transactions.TransactionScope())

{

context.SubmitChanges(ConflictMode.ContinueOnConflict);

scope.Complete();

}

cette manip rend tout le code ecrit dans le bloc using transactionnel,et pas besoin d'utiliser try,catch,commit,rollback...,il suffit juste d'appeler la methode Complete() pour commiter si tous passe bien et rollback dans le cas echeant.

autre interet,c'est qu'on peut gerer des transactions pour plusieurs objets connexion.plus d'info