domingo, 24 de maio de 2009

Creating a Custom SharePoint MasterPage using a Feature

Creating a custom MasterPage is a very common requirement especially for those who want to migrate from ASP.NET 2.0 to SharePoint, without altering the look and feel they already had previously.

I have searched a lot about how to accomplish this, and found many articles and blog posts but they are all incomplete, they are missing the complete guide. I will try to be as direct as possible, and include screen shots that I hope they would help.

Anyway, lets start and get our hands dirty...

  1. Navigate to the following folder: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\
    Copy the PageLayouts folder and paste it in the same directory but Change the folder name to another one. To easily follow up with me through this post, lets call it CustomMasterPages.



    Add the masterpage you want in the masterpage folder, the CSS file into the styles folder, and all images you need into the images folder.
  2. Open the CustomMasterPages folder. Now we have to Edit the Feature.xml that has the main Registry info about the new feature you want to create (in our case, the custom MasterPage). So open the feature.xml file using your favorite text editor.
    Delete what the file has, and paste the following:



    77596cae-c12d-4451-9d65-53b66b2fd5aa"
    Title="CS Masterpage"
    Description="My own Custom MasterPage"
    Version="12.0.0.0"
    Scope="Site"
    Hidden="False"
    DefaultResourceFile="core"
    xmlns="http://schemas.microsoft.com/sharepoint/">



    You have to change only the following fields, but I advice you to leave everything as it is for this Demo, just as a good kick off :)
    ID: A GUID to identify the feature. you can go to http://www.newguid.com/ to generate a new GUID (you will find it in the upper banner) and paste it right there.
    Title: the Feature name (Custom MasterPage name).
    Description: Feature's description.
    The Element Manifest is considered as the backbone of the feature; you have to specify its location, which is by default named as ProvisionedFiles.xml located at the same level with the feature.xml. Save the file and close it.

  3. Now open the ProvisionedFiles.xml file and let's see what we have got there.
    You simply link EVERYTHING you have in the CustomMasterPages folder, and create an entry for it in the ProvisionedFiles.xml



    http://schemas.microsoft.com/sharepoint/">

    MasterPage.master" Type="GhostableInLibrary">




    This is my sample master page for use with collaboration or publishing sites." />









    1_Duane.jpg" Name="1_Duane.jpg" Type="GhostableInLibrary"/>


    CS MasterPage.css" Type="GhostableInLibrary" />

    Now we are done with the 2 most important pages.

  4. One important thing you must take care of, is that the masterpage design is not the same as what you used to do in ASP.NET 2.0. Its not an HTML page with some ContentPlaceHolders with random IDs and placed anywhere like before. SharePoint's MasterPages are way different; there are a number of predefined ContentPlaceHolders with specific ids (you can't change them, or they wont be recognized, and the MOSS will hit you with a silly frustrating error page!). These ContentPlaceHolders are recognized by the MOSS according to their IDs. Have a look at the complete list below:



    yet, you dont have to place ALL of these ContentPlaceHolders into your new customized MasterPage. there are some of these which are essential, and others not. The following is a minimal MasterPage that you cant remove anything from it, or it wont work at all. You can always use it as a start for designing your masterpages.. i.e NEVER START THE MASTERPAGE DESIGN FROM SCRATCH! or you will end up banging your head against the wall!

    <%-- Identifies this page as a .master page written in Microsoft Visual C# and registers tag prefixes, namespaces, assemblies, and controls. --%>
    <%@ Master language="C#" %>
    http://www.w3.org/TR/html4/loose.dtd">
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="PublishingNavigation" Namespace="Microsoft.SharePoint.Publishing.Navigation" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register TagPrefix="wssuc" TagName="Welcome" src="~/_controltemplates/Welcome.ascx" %>
    <%@ Register TagPrefix="wssuc" TagName="DesignModeConsole" src="~/_controltemplates/DesignModeConsole.ascx" %>
    <%@ Register TagPrefix="PublishingVariations" TagName="VariationsLabelMenu" src="~/_controltemplates/VariationsLabelMenu.ascx" %>
    <%@ Register Tagprefix="PublishingConsole" TagName="Console" src="~/_controltemplates/PublishingConsole.ascx" %>
    <%@ Register TagPrefix="PublishingSiteAction" TagName="SiteActionMenu" src="~/_controltemplates/PublishingActionMenu.ascx" %>
    <%-- Uses the Microsoft Office namespace and schema. --%>


    <%-- The head section includes a content placeholder for the page title and links to CSS and ECMAScript (JScript, JavaScript) files that run on the server. --%>


    <br /> <asp:contentplaceholder id="PlaceHolderPageTitle" runat="server"> <br />




    <%-- When loading the body of the .master page, SharePoint Server 2007 also loads the SpBodyOnLoadWrapper class. This class handles .js calls for the master page. --%>

    <%-- The SPWebPartManager manages all of the Web part controls, functionality, and events that occur on a Web page. --%>







    <%-- The PlaceHolderMain content placeholder defines where to place the page content for all the content from the page layout. The page layout can overwrite any content placeholder from the master page. Example: The PlaceHolderLeftNavBar can overwrite the left navigation bar. --%>


    <%-- These ContentPlaceHolders ensure all default SharePoint Server pages render with this master page. If the system master page is set to any default master page, the only content placeholders required are those that are overridden by your page layouts. --%>



















    So to start, you can get whatever HTML you have in the old MasterPage and paste it in here, just below the . Then arrange the ContentPlaceHolders wherever you want into your HTML code.
    Another point you must take care of; the images and background's source urls. of course, we added the images previously into the CustomMasterPages\images folder, so we will replace the old source urls you had in the html code into something like:
    background="/Style%20Library/images/bg1.jpg">
    and for sure, that would be the same case in the CSS file.

  5. Now we are ready to install the feature!
    open the command prompt (Start> Run), then type:
    cd C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
    Now type the following
    stsadm -o installfeature -filename CustomMasterPages\feature.xml
    We are installing the feature that we are providing its feature.xml file (the xml file's path from the C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES folder).
  6. Activate the feature for your site.
    open the Internet Browser, and type in the webapplication's URL.. something like http://ahmed-ig:35193 and concatenate /_layouts/settings.aspx to the previous part.
    i.e: http://ahmed-ig:35193/_layouts/settings.aspx

    under the "Site Collection Administration" column, click on "Site collection features"



    locate the Feature you have just made. (you will find its name as you named it in the feature.xml file)



    Now Press on the Activate Button to activate the Feature.

  7. Apply the MasterPage into your site
    Now get back to the url you opened in Step #7
    and under the "Look and Feel" column, click on "Master page".
    Choose the Site Master Page as the customized MasterPage you have created.
    and leave the System Master Page as it is.
    Now you have to upload the CSS file you are using in your customized MasterPage file.


And Hopefully, that's it! Hope it works smoothly without any problems :)

Branding SharePoint Drop Downs

SharePoint has quite a few different drop down menus, within this post I will highlight the three primary drop downs and the CSS that drives it.

#1 Main Navigation Drop down:
image

The Main Navigation drop downs are a new addition to SharePoint from its previous SPS 2003 version. Here are the following classes that make up this navigation:

Class Name

Details

.ms-topNavFlyOutsContainer
{
border:solid 1px #c2dcff;
}

This is the outer container.
Modify this for the outer border.

.ms-topNavFlyOuts{
background-color:#F2F8FF;
font-family:Tahoma;
font-size:8pt;
}

This is the inner container.
Modify this for the drop down background and basic fonts.

.ms-topNavFlyOuts a{
display:block;
*width:120px;
min-width:120px;
color:#3764a0;
padding:4px 8px 4px 8px;
}

This class specifies the drop down items, width, color, and padding.
You might want to put in a width: 100% !important; tag in case you have an instance where you have a small drop down item and an item that its characters exceed 120px.

.ms-topNavFlyOutsHover{
background-color:#ffe6a0;
color:#000000;
}

This class specifies the hover state of each drop down item.
You will also want to put in width: 100%; into this class as well so that you don't get a default color background that you don't want.

image The SharePoint team also put into place a little hidden gem of logic that states that when a list is longer than the height of the page, it will create a scroll type drop down.

If you move your mouse to the top arrow it will scroll up, and if you move your mouse to the bottom as expected it will scroll down.

If you look at the image below the screen capture has 4 main navigation items all with drop down items. The ID's highlighted in green specify the Top Navigation Menu Item # 1, 2, 3, 4. For each navigation menu item if a drop down is available SharePoint will add in two div tags. The first one is the Menu Items Up which has an Image drawn from the /WebResource.axd file. The second DIV tag right below it is the Menu Items Down which also has an Image drawn from the /WebResource.axd file.

image

If you really needed to customize this you could simply add the following classes to your alternate stylesheet. But you would have to make sure you create as many Menun #s per how many top navigation items you have on your site.

Class Name

Details

#zz1_TopNavigationMenun1ItemsUp{
background-color: #FFF;
}

#zz1_TopNavigationMenun1ItemsDn{
background-color: #FFF;
}

This class is for the top and bottom boxes only for the 1st navigation item with a drop down.

#zz1_TopNavigationMenun2ItemsUp{
background-color: #FFF;
}

#zz1_TopNavigationMenun2ItemsDn{
background-color: #FFF;
}

Same as above but for Menun #2

#2 Site Actions Drop Down:
image

The Site actions drop down is a bit more complex. It uses quite a bit more styles than the main navigation. Here are some things to consider when branding this menu:

  • Define the color of the text, both Heading and description
  • Define what kind of image treatment you want behind the icons.
  • Define the hover state as a user moves the mouse over each item. (Background color, and Border line)

Class Name

Details

.ms-MenuUIPopupBody TABLE
{
color:#003399;
font-size:100%;
margin:0px;
padding:0px;
}

This class specifies the Basic menu color for the Bold Menu Label. However it could be over written see below.

.ms-MenuUISeparator,.ms-MenuUISeparatorRtL,.ms-MenuUISeparatorLarge,.ms-MenuUISeparatorLargeRtl
{
background-color:#c5c5c5;
font-size:1px;
height:1px;
line-height:1px;
}

This class specifies the color of the separator line.

.ms-MenuUI,.ms-MenuUILarge,.ms-MenuUIRtL,.ms-MenuUILargeRtL
{
background-color:#fafafa;
background-repeat:repeat-y;
cursor:pointer;
}

These classes represent the overall background color.

.ms-MenuUILarge
{
background-image:url("/_layouts/images/MGradLarge.gif");
width:250px;
}

This class is specific to all large size drop down menus. Including the Welcome, and My Links drop down.

.ms-MenuUILabel{
padding: 2px 0px 3px 6px;
}

This class specifies the bold menu labels padding. Since the color is not specified here but driven by the Pop up table. You could overide the color by adding it in here.

.ms-menuitemdescription
{
color:#666666;
}

This class specifies the color of the description text for each menu item.

.ms-MenuUIItemTableHover
{
background-color:#ffe6a0;
border:1px solid #d2b47a;
}

This class specifies the hover state when a user moves their mouse over each item.

#3a Document Drop Downimage

#3b Modify Webpart Drop Down
image

Both of the examples above use the same menu classes. You will notice that the space dedicated to the icons is allot smaller. All the classes for the large drop down are shared but for this menu it uses the following class to specify its smaller background image.

Class Name

Details

.ms-MenuUI
{
background-image:url("/_layouts/images/MGrad.gif");
}

This menu specifies the smaller graphic.

One last thing to consider is if you are deploying language packs that change the orientation of text to read right to left. The navigation will also be change.

image

Here are the classes that make up the right to left menus:

Class Name

Details

.ms-MenuUIRtL
{
background-image:url("/_layouts/images/MGradRtl.gif");
}

Background image for small right to left menus

.ms-MenuUILargeRtL
{
background-image:url("/_layouts/images/MGradLargeRtl.gif");
width:250px;
}

Background image for large right to left menus


Customizando uma Master Pages

Personalizando páginas mestras nos serviços SharePoint Windows

Introdução ao ASP.NET master pages

Páginas mestras

10 Templates para SharePoint

10 new theme projects for VSeWSS.

Labs SharePoint Workflow

Creating a SharePoint Workflow


Treinamento Online! E-learning Microsoft

WSS Development
MOSS Development

sábado, 23 de maio de 2009

Inserir imagem no botão Site Action

Pra quem derepente quer colocar uma imagem personalizada no icone Ações do Site "Site Action" mas está encontrando dificuldade vai tutorial que fiz, pesquisei na NET mas não vi nada que falasse passo-a-passo de como fazer, mas ta ai pra vcs.





Primeiro - Vá até o .CSS que faz referência a sua Master Page "no meu caso é o PROPRIO.css"




e veja o código fazendo referência a imagem.

sexta-feira, 22 de maio de 2009

Referência CSS para SharePoint 2007

Vejam as referências CSS para SharePoint, creio que vcs já deram uma olhada, mas vai ai novamente.

veja aqui

Como colocar o logo via CSS

No SharePoint tem diversas formas de colocar o logo na barra superior uma das formas que você pode colocar é via código CSS veja no exemplo a seguir:

A common trick in CSS design is to set a background image in the body tag for a site that contains a lot of the graphic elements of a site. This is often used to create colored columns and bars in CSS only design. See a screenshot. For example:

body {
background: url("myimage.gif");
}

When you do this in SharePoint, the background image will also appear in the Rich Text Editor used in the Content Editor Web Part. See a screenshot.

You can fix this issue pretty easily. Add a DIV tag around your page contents, and set the background for the DIV to the image that you need to use. Then, in your CSS code, specify both BODY and the class/ID for the DIV:

body .MyDiv {
background: url("myimage.gif");
}

Notice the space between body and .MyDiv! This is a contextual selector, only the tag with the class name of MyDiv in the Body tag will be affected.

Now the image will appear in your page, but not in the Rich Text Editor. See a screenshot.

Some notes... if you add a class or ID name to the BODY tag and reflect that in your CSS, it will not fix the issue. If you just move the image to a DIV wrapper and specify the image, it will not fix the issue. It is the combination of the image being in a wrapper, and body + the wrapper being specified in the CSS file that fixes the problem.

A common trick in CSS design is to set a background image in the body tag for a site that contains a lot of the graphic elements of a site. This is often used to create colored columns and bars in CSS only design. See a screenshot. For example:

body {
background: url("myimage.gif");
}

When you do this in SharePoint, the background image will also appear in the Rich Text Editor used in the Content Editor Web Part. See a screenshot.

You can fix this issue pretty easily. Add a DIV tag around your page contents, and set the background for the DIV to the image that you need to use. Then, in your CSS code, specify both BODY and the class/ID for the DIV:

body .MyDiv {
background: url("myimage.gif");
}

Notice the space between body and .MyDiv! This is a contextual selector, only the tag with the class name of MyDiv in the Body tag will be affected.

Now the image will appear in your page, but not in the Rich Text Editor. See a screenshot.

Some notes... if you add a class or ID name to the BODY tag and reflect that in your CSS, it will not fix the issue. If you just move the image to a DIV wrapper and specify the image, it will not fix the issue. It is the combination of the image being in a wrapper, and body + the wrapper being specified in the CSS file that fixes the problem.

Como ativar Drop Down no MOSS

MOSS 2007 sites can display drop down menus in the tabbed navigation across the top. Unfortunately there is not an easy check box to activate this functionality, instead things just have to be set up the right way. If you want your MOSS site to show drop down menus, make sure the following is true or walk through the following steps:

  1. From the root of the parent site (Home) choose to create a new site (Site 1). Once that site is created, you will be in that new site. From here choose to create a new page.
  2. Once that is created, choose to create another new site (Sub Site 1). Then create a new page in Sub Site 1.
  3. Your site structure should resemble this, see structure.
  4. For each site in the Navigation settings, both Show Subsites and Show Pages should be checked.
    • Select Site Actions - Site Settings - Modify Navigation.
    • Check Show subsites and Show pages in the first row. See sample.
  5. The end result would be a tab in the horizontal bar for Site 1, with a vertical drop showing Sub Site 1. See sample.

The navigation shows sub sites under the parent and published pages at the parent. Pages for one site are stored flat in a single library. If you want the navigation to show 2nd level sub site pages or 3rd level sub sites under the 2nd level, you need to make a very minor tweak to the master page that the site is using.

  1. Using SharePoint Designer (SPD), open the master page being used by the site. Warning! Making edits to this file will customize the file, a.k.a. unghost it. Don't worry you can always undo this action.
    • In SPD, navigate to _catalogs/masterpage/*.master
    • How do you know which master the site is using? In the site, go to Site Actions - Site Settings - Modify All Settings, then choose Master page under the Look and Feel column. Check which master page is selected in each drop down.
  2. In the master page file, search for SharePoint:AspMenu.
    • You will more than likely have more than one instance of a menu control. Look at the IDs to find the right navigation control for what you want to edit. They are intelligently named, you will be able to sort out which one you need. For default.master, look for ID="TopNavigationMenu".
  3. In the properties for the tag, find MaximumDynamicDisplayLevels="1". Change the number from 1 to 2.
  4. Save the file and publish the master page (do this from SPD, Manage Content and Structure, or the Master Page Gallery).
  5. Refresh your browser. Now when you mouse over Site 1 - Sub Site 1, you should see another level of navigation pop up. See sample.

Cool, ehh? Please don't abuse this dynamic display level. As tempting as it is to provide instant access to something 5 levels deep in your site, drop down menus notoriously aggravate end users. I highly recommend using no more than 2 levels (what we set in this walk through).

quarta-feira, 20 de maio de 2009

Como criar Tema para SharePoint

Choosing a theme
Select a theme as a starting point. In SharePoint select: "Site Actions -> Site Settings -> Site Theme" For the purposes of this article we'll choose "Simple"


Now that we have a starting point lets duplicate it and start creating our own theme.

On the SharePoint server, navigate to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES" and duplicate the "SIMPLE" folder. Rename this folder to whatever you'd like your theme to be called, let's make a new one called "SIMPLER".


In the "SIMPLER" folder, remove all of the images and rename "SIMPLE.INF" file to "SIMPLER.INF"

Open "SIMPLER.INF" file with notepad and change all instances of "Simple" to "Simpler"

Navigate to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\" and edit "SPTHEMES.XML"

Append the following xml, this is the information for the "Site Theme" area in SharePoint:


simpler Simpler Simpler is more simple than simple. images/thsimple.gif
images/thsimple.gif


We'll use the same thumbnails as the "Simple" theme. To change these later the gif files are stored in "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES"

You've created your own theme based on the Simple theme. To start editing the CSS open "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\SIMPLER\theme.css"

Creating multiple CSS files
A great way to organize your CSS is to create multiple style sheets. For example, you could create a style sheet called "navigation.css" where you would place all of your navigation-related styles.

At the bottom of theme.css append the following:

/* more customizations */ @import url("custom.css") screen; @import url("print.css") print;


Using the @import rule we're importing two separate style sheets, one called custom.css for screen media and another called print.css for print.

One important thing to note is that earlier browsers such as ie6 may have issues groking CSS level 2 stuff.

For more information on this technique see the W3C recommendation:
http://www.w3.org/TR/CSS21/cascade.html#at-import http://www.w3.org/TR/CSS21/media.html

Traversing the layout
As you can see in the diagram below Microsoft has used tables for layout in SharePoint 2007. This is an undesirable way of doing things, perhaps if they had used a more minimalistic approach relying more on CSS it wouldn't be so bad, but this is not the case. There are unnecessary attributes, sporadic inline CSS and tables embedded in tables throughout the application.



What this means is that identifying specific element classes is very difficult without the use of some kind of DOM inspector. A DOM inspector is a tool that can be used to inspect and edit the live DOM(Document Object Model) of any web document. Firebug has such a tool built in. Firebug is a Firefox extension that provides a set of development tools that let you edit, debug, and monitor CSS, HTML, and JavaScript. I would recommend grabbing Firebug or some other DOM inspection tool before you continue.

Overriding styles
It may be necessary to override some of core styles to achieve a desired look. Here's an example:

/* make all links red */ a {color:red !important;} td.ms-siteactionsmenu a {color:white !important;}


By using the !important declaration we're overriding all other styles that may be present for the a element. We want the link for the action menu to be a different color though so we also use the !important declaration to override.

For more information on this technique see the W3C recommendation:
http://www.w3.org/TR/REC-CSS2/cascade.html#important-rules

Previewing the theme
Seeing your CSS changes real-time is useful when customizing your theme. I would recommend using a tool that allows you to override styles on the fly. Firebug lets you do this, but I prefer Stylish because you can save your user styles. Stylish is a Firefox extension that allows easy management of style sheets and lets you preview your CSS changes instantly.

Once you are pleased with the changes you've made to your CSS, it's time to preview them. Open a command prompt and enter the following:

C:\>iisreset /restart

This will restart all Internet Information Services (IIS).


Now open SharePoint and select your updated theme.


Adding your company logo
Save your logo to your theme directory "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\SIMPLER"

Now we'll identify where we want to place the logo, let's put it in the traditional place in the upper left. We'll put it under the breadcrumb section in "td.ms-globalTitleArea":

/* insert logo */ td.ms-sitetitle { height:60px; background: 0 5px no-repeat url(logo.png); } h1.ms-sitetitle,td.ms-titleimagearea {display:none;}

We're changing the height of "td.ms-sitetitle" to fit the size of our new logo, and declaring the logo as the background. Then we hide the image and the h1 that are there by default.

Creating Complex Web Parts in Sharepoint 2007 using Web User Control

My task this few days was to research on how to create comple Web Parts in Sharepoint 2007. Ideally, I create my web parts using code-behind code. In other words, I create the controls dynamically. This was gruesome in my part, because from positioning to event-handlers may take a lot of time, debugging, and most specially in designing. Take a look at my sample code I used to design a very simple web part:



protected override void CreateChildControls()
{
base.CreateChildControls();

// TODO: add custom rendering code here.

Button myButton = new Button();
myButton.Text = "Click";
myButton.Width = 50;
myButton.Height = 50;

myButton.Click += new EventHandler(myButton_Click);

this.Controls.Add(myButton);

}

void myButton_Click(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
myLabelPublic = new Label();
myLabelPublic.Text = "For testing only. For testing only. For testing only.";
this.Controls.Add(myLabelPublic);

}

Basically, this code generate a button on it's page load. After the load, if user clicks the button, obviously, a new Label will generate displaying the message. This is not the way I want to develop my Web Parts, because it takes a lot of time.

So after a long time research, I found another way to create not just simple but you can make it complex using Web User Control. I did suspect Web User Control at the first place but I don't know how to figure it out. Anyway, here are the steps:

1.) First, of course, create your Web User Control. You have the option on how you create it, but in my part, I create it using ASP.NET 2.0 IDE. What I usually did is I create a blank page, then I add a new item which is Web User Control. Take note to uncheck the option which separate your code in a separate file.

2.) Second, design your Web User Control (ascx), from its physical design to its logic coding.

3.) Copy your ascx file to this directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES

4.) Then use this sample code as your reference for adding your Web User Control file in your .cs file:



protected override void CreateChildControls()
{
base.CreateChildControls();

// TODO: add custom rendering code here.

this.Controls.Clear();
userControl = (UserControl)this.Page.LoadControl(@"/_controltemplates/Test.ascx");
this.Controls.Add(userControl);
}


protected override void RenderContents(HtmlTextWriter writer)
{
//base.RenderContents(writer);
userControl.RenderControl(writer);
}


5.) Last build then deploy your site. Make sure your output is the URL of your sharepoint site for successful deployment of your Web Part.

Building a SharePoint 2007 Web Part using Web User Controls

Mais um passo-a-passo pra vcs!

We will perform the following actions, broken into document parts:

· Build a Web Part
by hand (as opposed to using templates)

· Build a simple web user control

· Load the web user control in the SharePoint Web Part via code

· Deploy the web user control by placing the development location in the SharePoint site

· Deploy the Web Part by compiling it to the bin directory of the SharePoint site

· Add a safe-control entry in to the Web.config and modify the security settings

· Modify the Web Part Gallery to display the Web Part for testing and debugging

Part 1: Starting the Required Projects

1. Create a directory under the root of the SP web called /usercontrols. It may help to drag and copy the existing /bin directory and clear out the contents. This ensures the proper file based permissions are added to your project.

2. Open Visual Studio 2005
and start a new file system based C# website project. Make sure the location is your new /usercontrol directory. Remove the initial aspx page.

3. Add a new C# based windows library project to the solution. Name it appropriate to the fact that this will be your Web Part project.

4. Open the Web Part project properties and change the compile output location to the /bin directory of your SP web, not the /bin directory of your user control project.

Part 2: Developing the User Control

1. In the usercontrol project add a new user control, naming it appropriate to your needs. In this case we will call it the HelloControl. This, of course, adds the HelloControl.ascx file and the HelloControl.cs files.

2. Open the ascx file, switch to Design mode and add a Textbox control.

3. Use F7 to switch to the C# code view and in the Page_Load event add code that changes the text output of the Textbox control, for example:

Listing 1

protected void Page_Load(object sender, EventArgs e)
{
this.TextBoxHello.Text = @"Hello Control World!!!";
}Part 3: Developing the Web Part

1. Open the Web Part control project and change the name of the cs file appropriate to your needs, for example HelloLibrary, which will change the name of the class declaration inside the code file.

2. Open the class file and change the using statements to reflect the following listing.

Listing 2

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;3. Change the class declaration to ensure the class inherits from the Web Part class.

Listing 3

public class HelloLibrary:WebPart4. Add a Control object that will represent the usercontrol.

5. Override the CreateChildControls to load your control with the Page object LoadControl method that will load the HelloControl control from the file system.

6. The LoadControl method has two overloads. The method we will use expects a string representing the virtual location of the usercontrol on disk. This will point to the virtual location by using the "~" and the path. The "~" represents the location of the code that is running. As such, the path "~/usercontrols/HelloControl.ascx" means, start from where I am running and consider that the root of this path, then locate the file to use.

7. Follow this up by adding this loaded control to the page controls collection.

Listing 4

Control control;
protected override void CreateChildControls()
{
this.control = this.Page.LoadControl(@"~/usercontrols/HelloControl.ascx");
this.Controls.Add(this.control);
}Part 4: Adapting the Web.Config

1. Now, two changes need to be made to the web.config. Locate and open it from the root of your SP website.

2. One change needed is to adjust the security settings. The discussion of SP application security
is beyond the scope of this article, but we will cover the change needed for this application. A search of the internet will cover the fact that there are other ways to adapt security than what we will use, but this will work for our needs.

3. Locate the line in the web.config that reads:

Listing 5

Change it to read:

Listing 6

By doing this we are granting full access to this SP site, which is needed to allow file IO access and to load the usercontrol from a disk.

4. Next, locate the SafeControls block. Make a copy of the last line and replace the information with your project information. If we were using a GAC installed assembly, our SafeControl line would look more like the line you cut and paste. But because we are putting the assembly in the bin directory, we can keep it simpler.

Listing 7

Namespace="HelloSmartPart" TypeName="*" Safe="True" />· The Assembly tag refers to the physical name of the assembly without the .dll extension.

· The NameSpace is the same as the assembly namespace.

· The TypeName denotes the safe methods, in this case * indicates all methods are safe.

Part 5: Deployment and Testing

1. Open your website. At this point your new Web Part is not yet an option to be selected and must be enabled for use.

2. Open the Site Settings.

3. Under Galleries, click the Web Parts link.

4. Web Parts are controlled by XML files. But in this case, we did not craft an XML file for this Web Part. The act of enabling this Web Part for use will assist with this need.

5. Click New, which causes SharePoint to read the Web.config file. It reads the config and uses reflection to build the information needed to allow you to use the Web Part.

6. You should now see the webpart. Click the Populate Web Part option.

7. Now back in the main Web Part Gallery page, take a minute to review the Web Part properties by clicking on the Edit link button. Click on the View Xml link. You may find this bare-bones config file useful in other development tasks.

8. Now go to the main page. Click on Site Settings, and edit page. In the middle, click on Add A Web Part and locate the Hello webpart.

9. Your Web Part should now be displayed. The labor of your efforts should now be realized in the fact that you have crafted a user control that is loaded into a Web Part. If you were using the Web Part only method (without a usercontrol), all of your code would need to be built by hand. This means that the creation of all controls, event wire-ups and such would need to be written into the Web Part by way of the html render code. With this method you use the Web Part as the container for one or more usercontrols that do all of the heavy lifting. And one more great aspect to this method is that you do not even need to compile the usercontrol. You simply edit the usercontrol code-behind and IIS and .NET take care of the rest.

Baixa aqui o código

Criando e Cutomizando um Web Services para SharePoint

This article will guide you through the process of creating a custom web service for SharePoint. This web service will work with new versions of SharePoint, Office SharePoint Server 2007 and Windows SharePoint Service 3.0. We will create a simple service that will upload documents to SharePoint. We will call it UploadService. Remember, there are steps in the Microsoft articles that are confusing especially for the beginners, I have taken care of that as well. I have tried to include as much information as possible including screenshots and code snippets to make the job easier for the developer. I have used Microsoft articles as a base for this article. There are some mistakes in the Microsoft articles that have been corrected in this article.

Basic Steps for Creating a Web Service

Create an ASP.NET web service in Microsoft Visual Studio 2005. There are two ways to do this. You can develop a web service on the server machine that hosts SharePoint or you can develop it on a remote machine that does not host SharePoint and later deploy the service on the machine that hosts SharePoint. We will discuss the second method in this article.

Add .ASMX file to your project if it's not already there. This file will contain the programming logic for the web service. Note, you can add programming logic to the markup page as well as the code behind. The choice is yours.
Generate a static discovery file (disco) and a Web Services Description Language (WSDL) file.
Modify the disco and wsdl files for SharePoint.

Deploy the web service files to the SharePoint server.

Create a client application to consume the web service.

You can download the sample application (web service) here. Download size is 361 KB.

The zip file contains the web service and its related files. It also contains an installer to help you install the service easily on your server. Unzip the file to your hard disk. It will create a "WSUploadService" folder. You can unzip the file anywhere on your hard disk. There is no restriction on unzipping it to a particular folder. Run "UploadServiceCopier.exe" to install the service. Installer will ask you to select a SharePoint site where this service should be installed. Select your site from the drop down and keep the folder name as "bin" (second field: textbox) and click "Next".

To uninstall, run the "UploadServiceCopier.exe" again. It will give you the following message:

"Service is already installed. Do you want to uninstall it?"

Select "Yes" and then select "Remove WSUploadService" and click "Finish" to uninstall the service. Uninstall will remove all copied files from your hard disk.

Please run "UploadServiceCopier.exe" to install/uninstall the service. Do not run "setup.exe" directly as it will not install the service correctly.

Creating a Custom Web Service

1. The first step is to create an ASP.NET web service project in Visual Studio 2005. If you don't find a web service project template in visual studio, that means that you are still running an old version of Visual Studio 2005, the one without the service pack. You will have to download and install the Visual Studio 2005 Service Pack 1 Beta from Microsoft here. It's a 371.9 MB download and let me tell you in advance that the installation is very slow and takes a lot of time. On the File menu, click New Project.

2. In the Project Types box, select Visual C#.

3. In the Templates box, select ASP.NET Web Service Application.

4. In the Name box, type UploadService. In the Location box, type the following path: C:\WebService. You can also click the browse button to browse the folders and select the destination folder. This is the path where the project will be stored. In the Solution Name box, type UploadService and check Create directory for solution checkbox.

5. Click OK.

6. In the Solution Explorer, right-click Service1.asmx and rename the file Files.asmx and then right click Files.asmx and click View Code.

7. Add a reference to the assembly for Microsoft Office SharePoint Server 2007 (Microsoft.SharePoint.dll). This assembly is located in the following directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI. Please note that if you are developing on a machine that does not have SharePoint installed then you can copy the required files from the SharePoint machine to your development machine.

8. Make sure following using directives are included at the top:
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;


9. Change your class name from Service1 to Files.
public class Files : System.Web.Services.WebService


10. Comment out the web method definition. The commented out web method code will look like as follows:
//[WebMethod]
//public string HelloWorld()
//{
//return "Hello World";
//}


11. Add following code (web method) in the class:
[WebMethod]

public string UploadDocument(string fileName, byte[] fileContents, string pathFolder)
{
if (fileContents == null)
{
return "Null Attachment";
}

try
{
int iStartIndex = pathFolder.LastIndexOf("/");
string sitePath = pathFolder.Remove(iStartIndex);
string folderName = pathFolder.Substring(iStartIndex + 1);

SPSite site = new SPSite(sitePath);
SPWeb web = site.OpenWeb();

SPFolder folder = web.GetFolder(folderName);

string fileURL = fileName;

folder.Files.Add(fileURL, fileContents);

if (folder.Files[fileURL].CheckedOutBy.Name != "")
{
folder.Files[fileURL].CheckIn("File Checked In");
}

return "File added successfully!";

}
catch (System.Exception ex)
{
return "Error: " + ex.Source + " - " + ex.Message;
}
}


12. Open Files.asmx markup page. In Solution Explorer, right-click Files.asmx and select View Markup. You will notice that the markup page has following line:
<%@ WebService Language="C#" CodeBehind="Service1.asmx.cs" Class="UploadService.Service1" %>


Change it to the following line:
<%@ WebService Language="C#" Class="UploadService.Files" %>


13. Create a strong name for the class library. In Solution Explorer, right-click the web service project, and in the Properties dialog box, click Signing, select Sign the assembly, and select in the box for choosing a strong name key file.

14. In the Create Strong Name Key dialog box, provide a file name for the key, deselect Protect my key file with a password, and click OK.

This was the easy way. You can also strong name your assembly using the command line utility called as sn.exe. Use following steps if you want to strong name your assembly manually:
1. Strong naming utility (sn.exe) can be found in the following folder: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

Copy the sn.exe utility to the folder where your assembly is located and run the following command to strong name your assembly:

sn.exe -k key.snk

Resulting key will be written to the key.snk file.

2. Go to your project's properties (right-click project name in the Solution Explorer and select Properties from the menu) and select Signing from the menu that appears on the left. This will open a form.

3. Check Sign the assembly checkbox and choose the key file from the drop down (Click the Browse... button in the drop down to locate the key.snk file that you generated in the previous step).

4. Re-compile your assembly.


15. Compile the web service project.

16. As we are developing this web service on a machine that does not host SharePoint, therefore, we need to create a virtual directory in IIS. Click Start, point to Administrative Tools (You may have to go to the Control Panel first to select Administrative Tools), and then click Internet Information Services (IIS) Manager.

Note: In case you are developing the service on a SharePoint server, then skip steps 17-20 and use following instructions and then start with step 22:
1. Copy the Files.asmx to the following folder: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS

2. Run disco.exe at the command prompt from the LAYOUTS directory to generate .disco and .wsdl files.

Run a command in the following format to generate the files in LAYOUTS:

disco http://localhost/_layouts/Files.asmx


17. Expand the branch for the server computer to which you want to add a virtual directory. Under the server computer branch, expand the Web Sites folder, and right-click the Default Web Site and select New and then Virtual Directory.... If you don't want to use Default Web Site, you can create a new web site.

18. Click Next and enter an alias in the text box, for example, for this service you can enter UploadService.

19. Click Next and then click Browse... button to browse to the project folder (containing the .asmx file) and click Next.

20. Click Next again and then click Finish.

Generating and Modifying Static Discovery and WSDL Files

21. Use Disco.exe to generate .disco and .wsdl files. This command line utility is located in the following directory:

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

Open command prompt and type the following line and press Enter:

Disco http://localhost/uploadservice/Files.asmx

Make sure you have entered the correct path in the command above otherwise you will get an error. If you created a virtual directory on a port other than the port 80, then you must mention the port number in the path (For example, http://localhost:8080/uploadservice/Files.asmx). This will generate the .disco and .wsdl files.

22. To register namespaces of the Windows SharePoint Services object model, open both the .disco and .wsdl files and replace the opening XML processing instruction -- -- with instructions such as the following:


<%@ Page Language="C#" Inherits="System.Web.UI.Page"%>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0,
Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>


23. In the .disco file, modify the contract reference and SOAP address tags to be like the following example, which replaces literal paths with code generated paths through use of the Microsoft.SharePoint.Utilities.SPEncode class, and which replaces the method name that is specified in the binding attribute:


<contractRef ref=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request) + "?wsdl"),Response.Output=""); %&gt;
docRef=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns:q1="http://tempuri.org" binding="q1:FilesSoap" xmlns=
"http://schemas.xmlsoap.org/disco/soap/"
/>
<soap address=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt;
xmlns:q2="http://tempuri.org" binding="q2:FilesSoap12" xmlns=
"http://schemas.xmlsoap.org/disco/soap/"
/>


24. In the .wsdl file, make the following, similar substitution for the SOAP address that is specified:


<soap:address location=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt; />


Make the following substitution for the SOAP12 address:


<soap12:address location=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(SPWeb.OriginalBaseUrl(Request)),Response.Output); %&gt; />


25. Rename both files in the respective formats Filedisco.aspx and Fileswsdl.aspx so that your service is discoverable through SharePoint.

Deploying web service on the SharePoint server

Copy the Web service files to the _vti_bin virtual directory

26. Copy the web service files to the _vti_bin directory of the SharePoint server. Web service files that are to be copied are as following:

Files.asmx
Filesdisco.aspx
Fileswsdl.aspx

The _vti_bin virtual directory maps physically to the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI directory, which contains the default Web service files used in Windows SharePoint Services.

To include the Web service in the list of web services on the server

27. In Notepad, open the spsdisco.aspx file. spsdisco.aspx is located in the following directory (on the SharePoint server):

Local_Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

28. Add the following lines to the end of the file within the discovery element and save the file:


<contractRef ref=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(spWeb.Url + "/_vti_bin/Files.asmx?wsdl"), Response.Output); %&gt;
docRef=&lt;% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode
(spWeb.Url + "/_vti_bin/Files.asmx"), Response.Output)
; %&gt; xmlns="http://schemas.xmlsoap.org/disco/scl/" />
<soap address=&lt;%
SPHttpUtility
.AddQuote
(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/Files.asmx"), Response.Output)
; %&gt; xmlns:q1="http://schemas.microsoft.com/sharepoint/soap/directory/"
binding="q1:FilesSoap"
xmlns="http://schemas.xmlsoap.org/disco/soap/" />


Copying the assembly to the correct Bin folder

29. I have seen blogs and forums where people have recommended to copy the assembly to the following folder:

Local_Drive:\program files\common files\microsoft shared\web server extensions\12\isapi\

Some people say it should be copied to the following folder:

Local_Drive:\Inetpub\wwwroot\bin

bin folder is not there by default and has to be created but safest place to copy the assembly is the bin folder of the virtual directory of the web application where you intend to use the web service. Following path contains the virtual directories of web applications that you have created on your SharePoint server.

Local_Drive:\Inetpub\wwwroot\wss\VirtualDirectories

For example, if you want to use the web service in web application at port 81, then you should copy the assembly to the following folder:

Local_Drive:\Inetpub\wwwroot\wss\VirtualDirectories\81\bin

Similarly, if you want to use the web service in web application at port 17316, then you should copy the assembly to the following folder:

Local_Drive:\Inetpub\wwwroot\wss\VirtualDirectories\17316\bin

I am not saying that you can not copy the assembly to the _vti_bin folder or wwwroot folder, of course you can but I have often seen people struggling with the service deployment. People often ask me where they should copy the assembly and what is the best place to put the assembly in. I tested my web service by putting the assembly file in all the recommended places and I found that bin folder of the virtual directory of the web application is the safest place where your web service is guaranteed to work.

Copy the assembly to the bin folder of the virtual directory of the web application of your choice. You will have to create the bin folder yourself. It is not there by default.

Adding web service to the GAC

30. You must add your assembly in the GAC on your SharePoint server. This is necessary otherwise you will get permissions error on the server. There are three ways to avoid this permissions error. One way is to add the assembly in the GAC. Second way is to change the trust level to medium in the web.config file and the third is to create a custom trust policy of your own. There is an article on Microsoft site that has all the details of Code Access Security (CAS) and it also shows how to create a custom policy file. Here is the article if you are interested in exploring this topic.

Unfortunately, this is an old version and works only with SharePoint 2003. I am not sure if Microsoft has already released an updated version of this article or not. I intend to write an updated version of this article (at least the custom policy file part) for Office SharePoint Server 2007 and Windows SharePoint Services 3.0.

To add your assembly to the Global Assembly Cache (GAC), you can either drag and drop the assembly into the %windows%\assembly directory using 2 instances of Windows Explorer, or use the command line utility gacutil.exe that is installed with the .NET Framework SDK 2.0. This utility is located in the following folder:

C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin

To use gacutil.exe to copy the class library DLL into the GAC

To open the Visual Studio command prompt, click Start, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio Tools, and click Visual Studio 2005 Command Prompt.
At the command prompt type a command in the following form, and press ENTER:
gacutil.exe -i "".

You can also use ".NET Framework 2.0 Configuration" tool to add the assembly to the GAC.

1. Go to control panel, click Administrative Tools and select Microsoft .NET Framework 2.0 Configuration.

2. Click Manage the Assembly Cache and then select Add an Assembly to the Assembly Cache. Locate the assembly and click Open.

Creating a Windows Application to Consume the Web Service

After copying the Web services files to the _vti_bin directory, the next step is to create a Windows Application to consume the Web service.

31. Create a new C# Windows Application in Visual Studio 2005.

32. In Solution Explorer, right-click References, and then click Add Web Reference.

33. In the address bar of the Add Web Reference browser, type the URL for the site to which to apply the service, as follows, and then press ENTER:

http://localhost/_vti_bin/Files.asmx?wsdl

If you installed the service on another port, for example, port 17316, then the url would be:

http://localhost:17316/_vti_bin/Files.asmx?wsdl

You can also browse all web services available on the server. Files.asmx will be listed in the web services available on the server. There will be multiple entries, each entry representing the service available for a different web application. Therefore, if you want to upload documents to a site on port 80, then you should select Files.asmx for port 80.

34. Include following using directives at the top:

using System.Net;
using System.IO;

35. Add following code to your application:

try
{
localhost.Files oUploader = new localhost.Files();

oUploader.PreAuthenticate = true;
oUploader.Credentials = CredentialCache.DefaultCredentials;

string strPath = @"C:\test.doc";
string strFile = strPath.Substring(strPath.LastIndexOf("\\") + 1);

string strDestination = "http://sp:17316/Docs";

FileStream fStream = new FileStream(strPath, System.IO.FileMode.Open);
byte[] binFile = new byte[(int)fStream.Length];
fStream.Read(binFile, 0, (int)fStream.Length);
fStream.Close();

string str = oUploader.UploadDocument(strFile, binFile, strDestination);
MessageBox.Show(str);

}
catch (Exception ex)
{
MessageBox.Show(ex.Source + " - " + ex.Message + " -
" + ex.InnerException + " - " + ex.StackTrace);
}


localhost is the name of the web reference that you added in previous step. strPath contains the filename that is to be uploaded. This is just a sample to show you how the service works, that's why i have hard coded the filename but in a real life situation you may want to add a text box and a browse button to select files from your hard disk. strDestination contains the destination path. This should be the path representing the document library where file is to be uploaded.

36. Finally, before testing the service, make sure the current user has privileges to upload documents in the destination document library. The user should have "Contributor" rights in the document library otherwise, you will get "401: Unauthorized" error. Run the application to test the service.

Frequently Asked Questions

Q: I get "Could not create type" error message. What could be the reason?

Make sure your .asmx file has correct class name definition. Open your .asmx file and if class name is myFiles, change it to myService.myFiles!

<%@ WebService Language="C#" Class="myService.myFiles" %>(Correct)

<%@ WebService Language="C#" Class="myFiles" %>(Incorrect)

It's better that you use correct format in the first place but you can change the .asmx file after deployment as well. Go to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI folder and open your .asmx file in notepad (or any editor of your choice) and make the changes as mentioned above.

Q: I get "Server did not recognize the value of HTTP Header SOAPAction: ..." error?

This error occurs if you do not use correct web service namespace. Following three lines should be included in your code, just before the class defintion:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

This error can occur even if you omit the trailing slash of http://tempuri.org/, http://tempuri.org will result in an error.

Q: I get "File not found." error?

This happens when SharePoint fails to find the assembly file. Make sure you have added the assembly in the correct bin folder. Also, make sure you have added the assembly in the GAC.

Q: I get "Unauthorized" error?

Make sure the user who is trying to use the web service has "Contributor" rights in the destination site or library. Also, make sure following lines are added to your client application:

oUploader.PreAuthenticate = true;
oUploader.Credentials = CredentialCache.DefaultCredentials;

Q: I get "SQL Server might not be started" error. I have double checked, my SQL Server is running. Why am i getting the error?

There could be several reasons for this. If you modified the web.config file, reverse the changes you made to the config file and then try again. The error has nothing to do with the SQL Server.

Q: I do not see my web service when i click "Web services on the local machine" in Add Web Reference?

Did you make changes in the spsdisco.aspx file? To include your web service in the list of web services on the SharePoint server, you must add reference to your web service in the spsdisco.aspx file (within the discovery element).

Q: Is it necessary to include the code in the code-behind?

No! You can write code in the myFiles.asmx (markup page) and delete the myFiles.asmx.cs file. Here is the myFiles.asmx code listing:

<%@ WebService Language="C#" Class="myService.myFiles" %>

using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;

namespace myService
{
///
/// Summary description for Service1
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class myFiles : System.Web.Services.WebService
{

//[WebMethod]
//public string HelloWorld()
//{
// return "Hello World";
//}
[WebMethod]
public string UploadDocument(string fileName, byte
[] fileContents, string pathFolder)
{
if (fileContents == null)
{
return "Null Attachment";
}
try
{
int iStartIndex = pathFolder.LastIndexOf("/");
string sitePath = pathFolder.Remove(iStartIndex);
string folderName = pathFolder.Substring(iStartIndex + 1);

SPSite site = new SPSite(sitePath);
SPWeb web = site.OpenWeb();

SPFolder folder = web.GetFolder(folderName);

string fileURL = fileName;

folder.Files.Add(fileURL, fileContents);

if (folder.Files[fileURL].CheckedOutBy.Name != "")
{
folder.Files[fileURL].CheckIn("File Checked In");
}
return "File added successfully!";

}
catch (System.Exception ex)
{
return "Error: " + ex.Source + " - " + ex.Message;
}
}

}
}

Como instalar Reporting Services

Como instalar ou desinstalar o suplemento do Reporting Services
Como Ativar o recurso Servidor de Relatório na administração central do SharePoint
Como configurar a integração do Servidor de Relatório na Administração Central do SharePoint

terça-feira, 19 de maio de 2009

Retirar o ícone "Novo"

Muito bacana este post pois muitas vezes você vai adicionar um novo item e derepente não quer que apareça *novo, segue ai tutorial.

executa este comando

stsadm.exe -o setproperty -pn days-to-show-new-icon -pv 0 -url http://www.servidor/site




Até Mais,

Icone do Pdf

Utilizadores do SharePoint questionam porque é que quando se adicionam documentos Microsoft surgem de imediato os ícones associados aos mesmos, contudo, e quando adicionam outros arquivos, como por exemplo ficheiros pdf, tal não sucede? Bem, a razão é muito simples, não se encontram ícones associados no Servidor Web.

Copie este ícone pdf16 (botão direito, guardar como) com o nome pdf16.gif na pasta C:\Programas\Ficheiros Comuns\Microsoft Shared\web server extensions\60\TEMPLATE\IMAGES no Servidor Web SharePoint.

Edite o pasta C:\Programas\Ficheiros Comuns\Microsoft Shared\web server extensions\60\TEMPLATE\XML\DOCICON.XML e adicione a linha na área .

Na versão 3 do Windows SharePoint Services deverá alterar o valor 60 para 12.

Personalizar com CSS

O SharePoint utiliza Cascading Style Sheets (CSS) para controlar o aspecto geral de Sites de equipe e de Portal. Nunca me dei ao trabalho de perder tempo infinito à procura do melhor CSS, alterando isto e aquilo e verificando o resultado final, mas agora com esta nova aplicação, vou sem sombra de dúvidas perder alguns minutos e alterar os meus Sites de Equipa e Portais. A aplicação SPSkin pode ser vista aqui.

Backup e Restore via STSADM

A ferramenta STSADM é uma ferramenta de linha de comando que permite gerir todos os aspectos de um ambiente WSS sem ter de se aproximar da sua Administração Central.
Para poder, por exemplo, efecuar cópias de segurança e restauros de sites, poderá utilizar o STSADM com apenas dois parâmetros a serem requeridos: a url do site ou colecção de sites (-url) e o caminho para o ficheiro (-filename), poderá utilizar opcionalmente o switch (-overwrite).
A ferramenta SMIGRATE também instalada out-of-the-box com o WSS, permite criar cópias de segurança e restauro de sites, recorrendo, desta feita ao protocolo RPC do FrontPage. Criada inicialmente para garantir a migração de sites do STS (versão 1) para o WSS (versão 2), como o protocolo RPC se manteve compatível, passou a estar disponível para migrar sites na plataforma WSS.
Poderá encontrar a ferramenta em c:\Programas\Ficheiros Comuns\Micsosoft Shared\Web Server Extensions\60\Bin do servidor Web.
Poderá descarregar na Internet a partir daqui.
Está disponível na Technet a referência técnica da ferramenta de gestão por excelência dos sites WSS [STSADM].
Aqui ficam alguns exemplos:
Stsadm:
Backup -
stsadm.exe -o backup -url http://Server/site -filename file.dat
Restore -
stsadm.exe -o restore -url http://Server/site -filename file.dat -overwrite
O switch -overwrite é opcional.
Smigrate:
Backup -
smigrate.exe -w http://Server/site -f modelo_t1.fwp -e -u Nome_do_utilizador -pw palavra_passe
Ao utlizar o switch -e não vai fazer backup aos subsites.
Restore -
smigrate.exe -r -w http://Server/site -f modelo_t1.fwp -u Nome_do_utilizador -pw palavra_passe
Fonte:http://www.aceav.pt/blogs/mjssantos/Lists/Artigos/Post.aspx?ID=35

Visualizar PDF no site SharePoint

Este conceito é muito bacana e pra quem quer facilitar para olhar seu arquivo pdf no prórpio site pdf segue ai tutorial muito bom que encontrei.

O conceito é similar ao Page Viewer(PVWP) Esta WebPart cria um IFRAME object e seta atributo para a pagina.



Através de um DropDown você seleciona o nome do documento.



Crie uma biblioteca de documentos para inserir seus documentos em pdf
Aqui está sendo apontada para a biblioteca de documentos




Segue o código para criar está WebPart
Esta WebPart foi desenvolvida no Visual Studio 2008

[Personalizable(PersonalizationScope.Shared),
WebBrowsable(true),
WebDisplayName("Document Library"),
WebDescription("Enter in the Url to the document library")]
public string LibraryUrl
{
get { return _docLib; }
set { _docLib = value; }
}

Aqui o codigo método CreateChildControl para esta webpart

protected override void CreateChildControls()
{
base.CreateChildControls();

iframeObjectID = "iframe_" + guid;

string siteUrl;
string webUrl = string.Empty;
string fileContents = string.Empty;

//Define our DropDown List
dl = new DropDownList();
dl.Attributes.Add("onchange", "LoadFile_" + guid + "();");
dl.Items.Add("Select a document");

SortedDictionary <string,string> files;

try
{
//Is our document library path set?
if (this._docLib != null)
{
//decode any %20 spaces in URL
siteUrl = this._docLib.Replace("%20", " ");

//Open site collection
using (SPSite site = new SPSite(siteUrl))
{
//this block of code allows us to extract the relative Url of a subweb
if (site.Url.Length + 1 <= siteUrl.Length) { webUrl = siteUrl.Remove(0, site.Url.Length + 1); } //open web
using (SPWeb web = site.OpenWeb(webUrl))
{
//get handle to our document library
SPDocumentLibrary library = (SPDocumentLibrary)web.GetList(_docLib);

//create a generic sorted dictionary to store the files
files = new SortedDictionary<string, string>();

//loop through each file in root folder and add to sorted list
foreach (SPFile file in library.RootFolder.Files)
{
files.Add(file.Name, web.Url + "/" + file.Url);
}

//add each sorted file name to our drop down list
foreach (KeyValuePair<string, string> key in files)
{
ListItem item = new ListItem(key.Key, key.Value);
dl.Items.Add(item);
}
}
}
//Add drop down list and break tag to web part
this.Controls.Add(dl);
this.Controls.Add(new LiteralControl("
"
));

//Define a literal control to hold generated HTML (This will become our iframe)
iframe = new LiteralControl();
//Uniquely stamp this IFRAME
string frameGuid = new Guid().ToString();
iframe.Text = "";
this.Controls.Add(iframe);
}
else
{
//Set literal text to configure this web part
LiteralControl html = new LiteralControl("Click + this.ID + "')\">open tool pane to set path to Document Library");
this.Controls.Add(html);
}
}
catch (Exception ex)
{
//Display any error that comes up
this.Controls.Clear();
this.Controls.Add (new LiteralControl ("An error occurred: " + ex.Message.ToString()));
}


}

Agora o JScript para DropDown

crie antes
maiores detalhes veja aqui

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

if (!Page.ClientScript.IsClientScriptBlockRegistered ("script_" + guid))
{
//dynamically generate our JavaScript
string script = @"function LoadFile_" + guid + @" () {
var iframeobj = document.getElementById ('"
+ iframeObjectID + @"');
var selectobj = document.getElementById ('"
+ dl.ClientID + @"');
if (selectobj.value.toLowerCase().indexOf ('http') != -1)
{
iframeobj.src = selectobj.value;
iframeobj.style.visibility = 'visible';
}
else
{
iframeobj.src = '';
iframeobj.style.visibility = 'hidden';
}
}
"
;
//register our client side script that is an embedded resource
Page.ClientScript.RegisterClientScriptBlock (typeof (Page),"script_" + guid, script,true);
}
}


Agora é só fazer o deploy da solução

stsadm –o addsolution –filename <full path to WSP file>
stsadm –o deploysolution –filename –url <path to Web application>
stsadm –o activatefeature –name FileViewer –url <path to site collection where you want to use this>


Até Mais,