Wednesday, December 9, 2009

Session state is corrupted

If you got some error like that – the problem is in your TV, not in IIS, not in Sharepoint :-))

Exception message: The session state information is invalid and might be corrupted.

Stack trace:    at System.Web.SessionState.SessionStateItemCollection.Deserialize(BinaryReader reader)
   at System.Web.SessionState.SessionStateUtility.Deserialize(HttpContext context, Stream stream)
   at System.Web.SessionState.SqlSessionStateStore.DoGet(HttpContext context, String id, Boolean getExclusive, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
   at System.Web.SessionState.SqlSessionStateStore.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)
   at System.Web.SessionState.SessionStateModule.GetSessionStateItem()
   at System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData)
   at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

image

This occurs when there is a null value used for a Session Key and later a string based session key is used.

- Code adds a Null session key - this works and there are no errors.

- At a later request, code adds a string session key.

You are doing one of the following:

Object var = SomeFunction();

Session[var] = AnotherObject;

Or

Session[SomeFunction()] = AnotherObject;

You need to the return value and ensure it is not null!

Wednesday, December 2, 2009

Edit Document from MOSS 2007 with Office 2003

I had a case with customer (who uses Office 2003 ~4000 PCs and approximately 150 computers with Office 2007) where if the users try to open office document from MOSS 2007 with Office 2003, the file is always opened as read only. Our custom application needs to open the doc for edit and check it out. So, the result were – it is not supported by Office 2003.

What is supported and what not, is described here

Finally, after customization of CORE.JS we succeeded to run Office 2003 to work as 2007 and these steps are described below :)

In the beginning I need to say, that this blog post were very important, regarding the chosen technical approach

1. I created empty file in the following path: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS\1033\Checkout.JS

2. I got the code of DispDocItemEx function from CORE.JS file (in the same folder) and paste it inside the new one

3. In Checkout.JS I modified the code:

Original:

================

else

    {

    fRet=stsOpen.ViewDocument2(window, szHref, szAppId);

    }

================

Modified:

================

    else

    {

    if (ctx.isForceCheckout==true)

    {

    fCheckoutForEdit=confirm(L_ConfirmCheckout_Text);

        if (fCheckoutForEdit==true)

        {

        CheckoutDocument(ctx.HttpRoot, szHref, null);

            fRet=stsOpen.EditDocument2(window, szHref, szAppId);

            }

       else

       fRet=stsOpen.ViewDocument2(window, szHref, szAppId);

    }

    else

    fRet=stsOpen.ViewDocument2(window, szHref, szAppId);

    }

==================

4. I created a copy of C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\GLOBAL\default.master with name custom.master

5. Added the following code just after the red line

<SharePoint:ScriptLink language="javascript" name="core.js" Defer="true" runat="server" />

<!-- Checkout JS customization BEGIN -->

<SharePoint:ScriptLink language="javascript" name="Checkout.js" Defer="true" runat="server" />

<!-- Checkout JS customization END –>

6. I uploaded custom.master into http://myportal/sites/mysitecollection/_catalogs/masterpage, published and approved the new file.

7. The next step were to configure the site to use customized master page

clip_image002

8. During the tests I found, that if I click on the file link (in document library page /AllItems.aspx) Office 2003 has the same behavior as Office 2007.

clip_image002

clip_image002[7]

The file is checked out, “Shared workspace” pane is opened and on document close the following windows appear

clip_image002[9]

But, here I want to make a note, that if you try to open a document in any other fashion (such hyper link in email or web page), the CheckIn-CheckOut menu items and/or TaskPane functionality may not be available or work as expected. This modification only affects the behavior of the document library page.

Saturday, November 14, 2009

Developing with Office 2010 Services

Visio Services:

Get Microsoft Silverlight

Access Services:

Get Microsoft Silverlight

Excel Services:

Get Microsoft Silverlight

Word services:

Get Microsoft Silverlight

Sharepoint 2010 Developer Resources

SP2010

The first place, which you need to visit before starting Sharepoint 2010 development is here. Clicking on the modules from the right side bar you will have an access to related HOL (see below) and code snippets from Paul Andrew’s blog 

What’s new in Sharepoint development  with VS 2010 (Beta 2)

What’s new in Sharepoint Foundation 2010 

What’s new in Sharepoint Server 2010

Sharepoint 2010 Developer Hands-on-labs (download): Series of 10 HOL, which covers:

  • Web parts development
  • List definitions and Event receivers
  • Using LINQ for Sharepoint
  • Using Client OM and REST
  • Business Connectivity Services (BCS) External Content Type
  • Sharepoint 2010 workflow
  • Developing UI and Silverlight
  • Sandboxed solutions
  • UI Ribbon and dialogs development

Sandboxed solutions - Sandboxed solutions run in a secure and monitored process that has limited resource access

Extending Sharepoint tools in Visual Studio 2010 - You can create extensions for projects, project items, define your own project item types and create deployment extensions.

Feature and Package designer

Visual Studio 2010 and Sharepoint 2010 (drill down and navigate through the content categories)

Peter Jausovec’s blog (http://blogs.msdn.com/vssharepointtoolsblog/)

Monday, November 9, 2009

SUGBG (Meeting 7): No-code solutions with Sharepoint 2007

When: 11 November 2009, 18:30

Where: Microsoft Bulgaria office (Sofia, Blvd.”Nikola Vaptzarov”, 55)

Session 1: Enhance Sharepoint with no-code solutions

Speakers: Esad Ismailov, Miloslav Shulev and Veselina Evstatieva (BNP Paribas)

Download the presentation

Session 2: Enabling SharePoint business users: iTechnology Forms Accelerator and K2

Speaker: Petya Gaitanska (iTechnology)

iTechnology presented their fantastic product iTFA. They demonstrated the Silverlight form designer, the rules editor, integration with K2 workflow and answered all questions from SUGBG members. The very important notice here is: iTFA is free! Download and test from here (needs registration).

For more info (in Bulgarian) visit www.sugbg.org

Thursday, October 15, 2009

SUGBG (Meeting 6): Sharepoint for ASP.NET Developers

When: 21 October 2009, 18:30

Where: Microsoft Bulgaria office (Sofia, Blvd.”Nikola Vaptzarov”, 55)

Session: SharePoint for ASP.NET Developers

Level 200

Speaker: Radi Atanasov, Architect, Abilitics

For mo info (in Bulgarian) visit www.sugbg.org

Download the presentation

IMAGE_130

Wednesday, October 7, 2009

Sharepoint - InfoPath Error - “Some rules were not applied”

Yesterday evening I had a very strange problem with InfoPath form. When I tried deploy it to Sharepoint production farm I received the error that “some rules were not applied”. The same form worked perfect when I tested in InfoPath client against the same Sharepoint deployment. It is very important to say, that I’m using a call to UserProfileService and GetUserProfileByName operation. The production farm consist of three WFE and we found the following exception in the log:

w3wp.exe (0x15D8)                       0x17A8 Forms Server                     Forms Services Data Objects       13zh                Exception            System.Net.WebException: The remote server returned an error: (401) Unauthorized.     at System.Net.HttpWebRequest.GetResponse()     at Microsoft.Office.InfoPath.Server.SolutionLifetime.WebServiceHelper.GetResponseHelper(WebRequest request, DataAdapterTimer dataAdapterTimer, DataAdapterCredentials credentials, Stopwatch timer, ExecWebRequestExceptionState state, String adapterName, Boolean isQuery)     at Microsoft.Office.InfoPath.Server.SolutionLifetime.WebServiceHelper.ExecWebRequestSync(XPathNavigator inputSubDOM, Boolean[] inputUseDataset, XPathNavigator resultsSubDOM, Boolean resultUseDataset, XPathNavigator errorsSubDOM, Uri serviceUrl, Uri soapAction, Int64 timeOutMillisec, Solution solution, Document document, String name, Boolean isQuery, DataAdapterTimer dataAdapterTimer, DataAd...

Server platform: Windows Server 2003 x64, SP2

The solution:

Check http://support.microsoft.com/kb/926642 (Method 2: Disable the authentication loopback check) and add DisableLoopbackCheck key on each WFE.

After reboot it works!

Thursday, September 24, 2009

SUGBG (Meeting 5): Business Intelligence with PerformancePoint Server and MOSS 2007

When: 30 September 2009, 18:30

Where: Microsoft Bulgaria office (Sofia, Blvd.”Nikola Vaptzarov”, 55)

Session: Business Intelligence with PerformancePoint Server and MOSS 2007

Level 200

Speaker: Yordanka Dragieva, Consultant

For mo info (in Bulgarian) visit www.sugbg.org

Download the presentation

IMAGE_129

IMAGE_126

Sunday, September 20, 2009

Attach Files to InfoPath Form, (upload to Sharepoint library and generate links into form’s body)

Soon I have a task to create InfoPath form which has Attachment control, uploads file(s) to Sharepoint library and puts a link to it in the form’s body. I will describe the steps, which a used to solve the business scenario.

I choose to use Visual Studio 2008 instead of InfoPath client and created new InfoPath Form Template project.

image

I designed a form with following layout and data source:

image

image

Field Type Description
Title Text Required, Text Box
Attachment Picture or file attachment (base64)  
group4 Repeating table Two columns, Container for hyperlinks
Url Text Text Box with conditional formatting (see the settings below)

Conditional formatting for Url text box:

image

image

image

Select a hyperlink control from Toolbox, drag and drop it in the first column of the repeating table

image

and set up the properties like this

image

Finally, double click on “Attach File” button, open “Button Properties” dialog and select “Edit Form Code”. FormCode.cs should be open, go to Solution Explorer and add a reference to Microsoft.Sharepoint.dll

Right click on the project Add/New Item…/Code/Class and enter InfoPathAttachmentEncoder.cs for file name. Copy the source code for “Create an Encoder class in Visual Studio” from http://support.microsoft.com/kb/892730 and paste it in the new created file. Make the same for InfoPathAttachmentDecoder.cs

image

Use the following lines of code to upload attached file to Sharepoint document library (“Documents”), plug a hyperlink information into form content and store the form in Form library (“MyForms”)

 

        public void btnAttach_Clicked(object sender, ClickedEventArgs e)
        {
            XPathNavigator attachmentNav = MainDataSource.CreateNavigator();

            // Get the base64 encoded attachment
            string attachedFile = attachmentNav.SelectSingleNode("//my:Attachment", NamespaceManager).Value;
            attachmentNav = attachmentNav.SelectSingleNode("//my:Attachment", NamespaceManager);
            // Delete the encoded file form XML form
            attachmentNav.InnerXml = string.Empty;

            // Get the value of "Title" field
            string reference = MainDataSource.CreateNavigator().SelectSingleNode("//my:Title", NamespaceManager).Value;

            // Convert the base64 encoded string into a byte array
            InfoPathAttachmentDecoder decoder =
              new InfoPathAttachmentDecoder(attachedFile);
            byte[] attachment = decoder.DecodedAttachment;
            string fileName = decoder.Filename;

            // Add the file as an attachment to the SharePoint list item
            using (SPSite site = SPContext.Current.Site)
            {
                if (site != null)
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // Turn on AllowUnsafeUpdates on the site
                        web.AllowUnsafeUpdates = true;

                        // Add the attached document to "Documents" library
                        // and set the value of "Reference" column to
                        // "Title" filed of the InfoPath form

                        SPFolder lib = web.GetFolder("Documents");
                        SPFile file = lib.Files.Add(fileName, attachment, true);
                        file.Item["Reference"] = reference;
                        file.Item["Title"] = fileName;
                        file.Item.Update();
                        file.Update();

                        // Add attachment file url to "Url" field in the form
                        // by adding extra "my:group4" element in the form

                        XmlDocument xdoc = new XmlDocument();
                        xdoc.LoadXml(MainDataSource.CreateNavigator().OuterXml);

                        Uri url = new Uri(new Uri(web.Url), file.Url);

                        XmlNode grp4 = xdoc.SelectSingleNode("//my:group4", NamespaceManager);
                        XmlNode clonedNode = grp4.CloneNode(true);
                        clonedNode.SelectSingleNode("//my:Url", NamespaceManager).InnerText = url.AbsoluteUri;

                        grp4.ParentNode.InsertAfter(clonedNode, grp4);
                        string formXml = xdoc.OuterXml;
                        // Add the form to "MyForms" library
                        SPFolder formlib = web.GetFolder("MyForms");
                        string formName = string.Format("Request {0}.xml", reference);
                        SPFile form = formlib.Files.Add(formName, Encoding.UTF8.GetBytes(formXml), true);
                        form.Item["Title"] = reference;
                        form.Item.Update();
                        form.Update();

                        // Turn off AllowUnsafeUpdates on the site
                        web.AllowUnsafeUpdates = false;

                        // Close the connection to the site
                        web.Close();

                    }
                    // Close the connection to the site collection
                    site.Close();
                }
            }
        }

After publishing the form and administration approval from CA site I associated the new created Content Type with existing Form library (“MyForms”).

The results:

The initial form’s XML. <my:Attachment> inner text (the encoded file) is very big and Visual Studio hides it from the preview screen

image

The content of <my:Attachment> here is removed

image

The final form’s XML, with attached file URL

image

The empty/new form

image

The final form

image

The uploaded documents

image

The forms library

image

Download complete Visual Studio project

Saturday, September 19, 2009

Oviesse Store in Bulgaria Sucks или какво ми се случи в мола

untitled Ех, какво ми се случи днес… пак поредната простотия в криворазбраната и кривоустроената ни държава! Та решаваме заедно с дъщеря ми Никол (7 г.) да отделим няколко часа за шопинг в съботния ден, като изберем за мен подходящ тоалет за сватбата на много близък приятел. Това в прав текст означава, да изберем костюм, една – две ризи и вратовръзки за радостния повод. Като едни клиенти (консуматори) традиционалисти се упътихме по подразбиране към CSS, където от край време си посещаваме магазина на италианската верига Oviesse. Не след дълго си харесах модел костюм, избрахме и риза. Малко по-дълго се въртяхме покрай вратовръзките, но това си е разбираемо. Добре че на помощ се притекоха Влади, съпругата му и малкия Владко (1 м.), иначе щяхме да откараме поне още час в чудене и маене. И тъкмо бяхме решили, че сме преизпълнили петилетния план предсрочно, когато се започна …

След като избрах костюма, го оставих директно на касата, за да не го разнасям с мен из пробните … и пристига един младеж от персонала и ми заявява:

“Господине, панталонът и сакото, които сте избрали са различни номера, а това не е разрешено и не може да ги вземете!”

Еййй… това направо ме втрещи… съответно най-учтиво му обясних, че предвид моето телосложение това е крайно необходимо и го помолих да направим изключение. Той на свой ред ми каза, че не може да направи това и за това го помолих да повика управителя на магазина.

Появи се една млада госпожица (да не се сърди ако е госпожа) и започна на свой ред да ми обяснява, че не може да стане това, което искам аз. Тя нямала право да взема такова сложно решение… Това беше моментът в който се разбра, че тя била Заместник Упраивител, а баш управителя го нямало. “Добре”, казах си аз, нека да го питаме по телефона, дали няма да се съгласи да направи едно изключение за редовен клиент. След няколко минути увещания тя реши да звънне все пак, на някаква “Ани” и говориха по моя случай. А познайте резултата … не може! Загубих ума и дума от изненада и го обърнах темата по посока на това: “Вие знаете ли в подобни магазини по света какво е обслужването…” и “Добре кой може?”… глас в пустиня и пълно безхабери от страна на персонала.

В този момент си дадох сметка какво представлява въпросният магазин – евтина китайска стока със задоволително качество, подредена в не лош магазин на италиански бранд, с никакво обслужване. Да, там няма никакво обслужване, освен касиерите! То затова и цените са такива… Както и да е… бях решил да похарча 500 лв за сватбарския тоалет и някоя дрешка на щерката, но си останах със страница и половина оплакване в Книгата на оплаквания.

Това което ще направя със сигурност е, че ще очаквам отговор на оплакването си от книгата (по телефон или E-mail) и ако не го получа ще ескалирам проблема до http://www.oviesse.com и Комисията за защита на потребителя.

Като излязохме от този *** магазин отидохме в съседния Marks & Spenser. Там консултантите (Еми и Любо) ми обърнаха изключително внимание, при тях се оказа, че няма такова ограничение за номерата на сакото и панталона, но за съжаление, не намерих точно това, което търсех.

Но пък в Andrews’ Fashion Studio ударих бингото – перфектно обслужване, първокласна стока, добри цени и какъвто си искаш размер! В крайна сметка с Никол изпълнихме първоначалния план и съм готов за сватбата!

Та така, скоро няма да ги стигнем! Но добре че има и по някое изключение в морето на общото безхаберие, което ни е заляло…

Friday, September 11, 2009

Sharepoint Lists vs. Database Tables

Many times I had mediations about what type of data structures to use in Sharepoint related projects – Sharepoint Lists or Database Tables. And the answer is - “Depends”! There are a lot of pros and cons about one or another approach and when I saw the “Using SharePoint Lists vs. Database Tables” article in Sharepoint Guidance (August, 2009) I decided to extend the content with my considerations. The first seven benefits are taken from the article above.

Benefit Database Sharepoint List / Library

Handles complex data relationships

Yes No

Handles large numbers of items

Yes No

Handles transactions

Yes No

Is easy to use

No Yes

Accommodates workflows

No Yes

Includes a standard interface

No Yes

Can easily add binary data

No Yes
Handle versions and show/extract history No Yes
Modify/customize UI with standard tools (SPD 2007) Yes Yes
Easier playing with files No Yes
Can easy reuse columns definitions (incl. inheritance) – Content Types No Yes
Easy integration with Office client applications – Excel export and Document information panel, using standard UI No Yes
Web Services access No Yes

Friday, August 21, 2009

Sharepoint Error Message: “Your client does not support opening list with windows explorer”

I received the following message, when I tried to open document library in Windows explorer view: “Your client does not support opening list with windows explorer”

clip_image002

OS: Windows Server 2008 SP2 (x86)

Browser: IE 7

MOSS version: 12.0.0.6510

 

The solution:

By default, “Web Client” service is not installed with Windows Server 2008, you need to install “Desktop Experience” from Server Manager > Features

clip_image002[10]

clip_image002[12]

Special thanks to Nishant Shah

Thursday, August 13, 2009

Troubles with CustomList Feature (OOB)

This evening I spent 40 minutes fighting with one my little mistake :-) I was playing with site and lists definitions from retract-solVSeWSS 1.3, and I created a custom list definition with name “CustomList”. When I deployed this def. for the first time, VS said there is a conflict with existing feature, named CustomList and I quickly decided to retract the existing one :-) But, exactly at this moment I tried to access my site collection and received the following error:

 

 

Dependency feature with id 00bfea71-de22-43b2-a848-c05709900100 for feature 'TeamCollab' (id: 00bfea71-4ea5-48d4-a4ad-7ea5c011abe5) is not installed.   at Microsoft.SharePoint.SPFeatureCollection.CheckFeatureDependency(SPFeatureDefinition featdefDependant, SPFeatureDependency featdep, Boolean fActivateHidden, Boolean fForce)

WTF?

image

And after 30 minutes investigation, I found the following:

TeamCollab feature depends on many other features, how is written in the Error message and one of them is CustomList

image

When I retracted CustomList, the server retracted it’s OOB feature and I found that feature.xml file from hive 12 \TEMPLATE\FEATURES\CustomList is missing. The fastest solution for me was to get the particular file from another Sharepoint farm and to copy it to the right place. Finally I ran

stsadm –o installfeature –name CustomList

… and all was OK

:-)

Sunday, August 9, 2009

Червенската крепост и Ивановския скален манастир

Със семейството ми решихме да отделим един ден и да направим туристическа обиколка на забележителностите около Русе. За целта избрахме Червенската крепост и Иванобските скални църкви.   IMAGE_070

Честно казано, накрая си признах, че това което видях надхвърли очакванията ми. Червн и Иваново са разположени в каньон, и това разкрива не типична за България гледка. Когато пристигнахме в Червен, се оказа, че има направен туристически паркинг, един мъж късаше билетчета и имаше възможност да си закупим някакви “агит материали”. Купихме си билети от по 5 лв, които включват и посешение на скалните църкви. Поехме по стълбите нагоре, гидът ни каза, че стъпалата са 230+, но щом Никол (6 г.) ги изкачи безпроблемно…. :) След 10 минути изкачване стигнахме и до самата крепост. Предполагам че е възстановена и реконструирана в наши времена, но определно очаквах да видя някаква купчина камънаци! Това което заварихме си беше съвсем истинска крепостна стена с бойни кули.

 

 

 

IMAGE_072Реално погледнато избрахме Червенската крепост за посещение този уикенд, защото през седмицата бяхме видели в една от емисиите новини по телевизията, че там са проведени възстановки на занаятчийски производства, бойни машини или нещо от сорта.

Иначе, с. Червен се намира само на няколко километра от магистралата София – Русе, минавал съм по нея стотици пъти и никога не съм се отбивал. От върха с крепостта се открива невероятна гледка към каньона и реката. Обещах си, че при следващото ми идване в района ще се разходя именно в този каньон!

 

 

 

 

IMAGE_075 IMAGE_080

Вътрешността на крепостта е по-малко запазена в сравнение с крепостните стени, добре поне че има табели и се разбира кое какво е. Интерес предизвикват две неща – Църквата и бойната кула.

 IMAGE_083 IMAGE_084 IMAGE_086

IMAGE_088 IMAGE_089IMAGE_081

След това се запътихме към Ивановските скални църкви. Неприятната изненада е, че табелите по пътя просто свършват и задължително в самото с. Иваново трябва да се пита! В крайна сметка уцелих правилния път и той се оказа доста добре направен, но за съжаление неподдържан. Очевидно някой е вложил пари в него, хората са направили тротоар край пътя, не че някой би вървял по него, но да бяха поне подрязали храстите, които стърчат отвсякъде. Учудването ми беше голямо, когато намерих паркинга почти запълнен. Имаше доста румънски туристи и семейства българи. Качихме се по съпалата до единствената отворена за посетители скална църква. Там имаше гид, който ни разказа историята и отговаряше на въпросите на посетителите. Всички питаха за липсата на табели и за състоянието на пътя… тъжно но вярно!

IMAGE_091 IMAGE_094 IMAGE_095 

IMAGE_096IMAGE_099

 

IMAGE_101И така след страхотната обиколка в региона огладняхме и решихме да посетим атракциона “Дунавско село”. Страхотна атмосфера, храна и обстановка!

Ако имате път в тази посока, задължително посетете 3-те обекта! :)