.NET King technical and support webloghttp://www.dotnetking.com/TechnicalArchive.aspx.NET King RSS FeedEnglishMonday, October 06, 2008Sat, 17 Mar 2007 19:43:06 GMT.NET King RSS Service1972Get rid of HTML and XML tags - [Technical] When you work with word xml files and locate a field in the schema what you read usually contains XML decorating tags that most probably you don’t need them in your code. How can we get rid of them?
It is pretty simple. Brush up your .NET knowledge and remember we have a class called Regex which is a short name for Regular Expression object. Using Regex you can simply define a pattern for XML or HTML tags. This pattern will be something like this: "<[^>]*>".
The very same Regex class has Replace function that works just like Replace in String class. Having them all together in C# you will have a code like this:
 

  public string RemoveTags(String originalMessage)

  {

      Regex rgx = new Regex("<[^>]*>");

      return rgx.Replace(originalMessage, "");

  }

This function simply gets an HTML/XML String and returns pure text. Don’t forget to add
using System.Text.RegularExpressions;
to your file header.
Enjoy
Alireza
 

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=347May 30, 2008
How to delete an SQL Server 2005 database (Somehow SharePoint)? - [Technical]It looks like a silly question but I’d like to mention some cool stuff about it. When you drop the database it should delete the database file and the log file accordingly. At least this is what we expect. But what if the database is off-line? Haha, give it a try. Your drop script will delete the data but the data and log files stay there. Now if you want to create another database with the same name you see this:

 

But how this is related to SharePoint?
Remember that when you create MOSS or WSS Site collections it gives you the chance to pick a database name? Now remember when you uninstall SharePoint it doesn’t delete the databases?
Ok, here is what happens. You uninstall MOSS or delete Site Collection. Then you may think that, I may use these data in the future or for any reason database is in use and you cannot delete it so you take it off-line and then you delete and forget it while the files are still there. When you want to create another site collection or a new installation the existing files will not let you create the new database.
But why do you want to take the database off-line?
Taking the database off-line means that we don’t want anybody connect to the database anymore but we are polite enough to let the current users to the database finish their work. It doesn’t kill the existing connections and it takes some time for all the live users to finish their work and disconnect and in the meanwhile no new connection is made to the database. Usually when junior database administrators want to delete a database that there is live connection to that and they come up to related errors they try to take the database off-line, which is a good move, but do you really want to keep the current users when you want to delete what ever the data that they enter? So to drop a database simply go to SQL Server 2005 management studio and Management -> Activity Monitor. If you just double click on the activity monitor you can see a list of all the databases and existing connections to them. Simply right click on the database and kill the connection. Then you will be good to delete the database.
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=345May 02, 2008
Busy days with project - [Technical]
The bad news is that I am very busy with the project deployment with Loblaw so I can hardly find time to blog something considering that I come home sometimes after 10:00 or 11:00pm. The good news is that I am learning lots of cool stuff in this project that I can share with you in the coming days. So stay tuned with my latest updates.
Cheers
Alireza
]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=344May 01, 2008
There are no primary or candidate keys in the referenced table - [Technical]Msg 1776, Level 16, State 0, Line 1
There are no primary or candidate keys in the referenced table 'dbo.Products' that match the referencing column list in the foreign key 'FK_Sales_Products'.
Msg 1750, Level 16, State 0, Line 1

Have you seen this error before? Hah, you just noticed it? Cool! Let's see where the error is coming from.

I created two tables as Products and Sales. There is a foreign key that forces the sales table to use only valid values for ProductAbbreviation in Products table. To create a foreign key constraint I can simply run this script:

ALTER TABLE [dbo].[Sales]  WITH CHECK ADD  CONSTRAINT [FK_Sales_Products] FOREIGN KEY([ProductAbbreviation])

REFERENCES [dbo].[Products] ([Abbreviation])

GO

ALTER TABLE [dbo].[Sales] CHECK CONSTRAINT [FK_Sales_Products]

Here is the point. This foreign key refers to a field called Abbreviation. There is just one simple rule on this game. You cannot make a reference to a field that is not unique. In better word your foreign key can only refer to a field that has a unique constraint like Primary Key or Unique Index. Now read the error again and you can simply understand what is going on.

To have this script work you need to create a unique index on Abbreviation field in Products table or make it a primary key that guarantees uniqueness. So simply go to index management and create a unique index on that field or run this script to create it like old fashioned developers:

CREATE UNIQUE NONCLUSTERED INDEX unq_abbr ON dbo. Products

(Abbreviation)

Then you can create your foreign key happily ever after.
Enjoy
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=343Apr 25, 2008
Active task shouldn't be deleted in SharePoint workflow - [Technical]One of the typical problems in workflow development is task deletion. Usually users that interact with the task, have contribute permission to the task which means they can simply delete the tasks that are created as a part of workflow processing. Deleting a task can mess up the workflow and we may need to handle it as a part of the workflow. But how can we stop the users from deleting tasks? The solution is very simple. Item event handlers in MOSS/WSS 2007 can easily take care of this case. Item event handlers are events that are registered to a list and mapped to a dll that is already deployed to GAC. When an event (insert, delete and update) happens the event handler fires and execute the code that can do something in response or may even cancel the event trigger progression. This is exactly our scenario. We need to build an event handler that when a user tries to delete a task, it checks the task status. If the status is not "Completed" then in cancels the deletion and displays an error message. To implement this simply create a class library project in Visual Studio .NET and make a reference to Windows SharePoint Services Library. Then add the following code. Inline code description is included.

using System;
using
System.Collections.Generic;
using
System.Text;
using
Microsoft.SharePoint;

namespace StopActiveTaskDelete
{
    //Inhertit your class from SPItemEventReceiver
    public class CActiveTasksDelete: SPItemEventReceiver
    {
        // Override the ItemDeleting function. You will find also ItemDeleted
        // function that fires when the item is deleted. For your scenario we
        // need ItemDeleting to stop the delete process before it is complete.
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            //Built in call to the initial definition
            base.ItemDeleting(properties);
            // Get reference to the current item being deleted
            SPListItem myItem = properties.ListItem;
            // Read the status field of the item being deleted
            String taskStatus = myItem["Status"].ToString();
           

            // Is the task status is Complete it is not active task any more
            // Otherwise we cancel the deletion
            if (taskStatus != "Completed")
            {
                // This is the message that we'd like to show to the user
                // if he/she tries to delete an active task
                properties.ErrorMessage = "This task is still in progress and cannot be deleted";
                // This line actually cancels the delete
                properties.Cancel = true;
            }
        }
    }

}

Sign the assembly with a strong name key and deploy it to the global assembly cache. Now all you need to do is to introduce the this assembly to a task list in SharePoint. There are different ways of doing it, but the simplest way is using a simple consol application to do so.

Your script should look like this:

using System;
using
System.Collections.Generic;
using
System.Text;
using
Microsoft.SharePoint; 

namespace RegsiterEventReceiver
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get reference to the the site that containd your task list
            SPSite mySite = new SPSite("http://sharepointSiteURL");
            SPWeb myWeb = mySite.OpenWeb();
            // Get the reference to your task list
            SPList myList = myWeb.Lists["Tasks"];
            myList.EventReceivers.Add(SPEventReceiverType.ItemDeleting,
                "StopActiveTaskDelete, Version=1.0.0.0, Culture=neutral" +
                //Replace this key with your own assembly publick key token
                ", PublicKeyToken=8a1a592e4ca85c4c",
                "StopActiveTaskDelete.CActiveTasksDelete");
            // Don't forget to update the list
            myList.Update();
            // Make sure you add this life to feel good after your
            // Solution is deployed successfully
            Console.WriteLine("Haha, done!");

        }
    }
}

Now go to the SharePoint Site and try to delete an incomplete task. You will get this error page.

And this code will protect active tasks from deletion happily ever after.
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=341Apr 18, 2008
Setting Item Level Security programmatically for SharePoint list items - [Technical] This is not a unique post. You may find this post in many weblogs and websites, but I am putting this code here for my own reference. In this code I break the security inheritance for a list item and provide contribute permission for a group that has been already created in SharePoint site.

 

            SPListItem myItem = properties.ListItem;
//This line detaches the item security from the list
            myItem.BreakRoleInheritance(false);
            myItem.Update();
            SPWeb myWeb = properties.OpenWeb();
// Creates an object of type SPMember to represent a group
            SPMember member = myWeb.SiteGroups["TestGroup"];
// We can simply cast a SPMember object into a SPPrincipal variable
            SPPrincipal principal = (SPPrincipal)member;
// A role definition is required to represent a permission level in SharePoint site
            SPRoleDefinition roledefinition =
                myWeb.RoleDefinitions.GetByType(SPRoleType.Contributor );
            SPRoleAssignment myRoleAssignment = new SPRoleAssignment(principal);
            myRoleAssignment.RoleDefinitionBindings.Add(roledefinition);
            myItem.RoleAssignments.Add(myRoleAssignment);
            myItem.Update();

 Enjoy the code.
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=340Apr 15, 2008
SharePoint Conference 2008 Dubai follow up - [Technical]I finally got enough e-mails to start bloging my presentations in the conference. Here is the answer to some of the requests that I received after conference.

Enjoy
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=339Apr 14, 2008
SharePoint Conference 2008 in Dubai - [Technical] After a long and very busy time working on projects and books I am back online with some cool stuff. I will be speaker in SharePoint Conference 2008 Dubai. I have picked up 3 subjects for my presentations that you can find the complete conference agenda here.

  • Using Excel Services to build BI solutions: I personally believe this title is not well articulated. I guess Excel Services is something that everybody should explore it personally so I am not going to completely cover features and capabilities of excel services. I will do my best to deliver the presentation so that the audience can repeat the experience themselves. This lecture will include:
    • Excel services from scratch (how to have it running from a clean installation)
    • Excel services architectural design (Data sources, trusted locations, security structure)
    • Using Excel Services to bring data from SQL Server to MOSS interface with data graphs
    • Using Excel Services to bring Analysis Services Cube data and graphs to MOSS Server
    • Excel Services and BI components (Introducing MOSS out of box and how excel services interacts with MOSS BI lists and BI Dashboard)
    • Q&A
  • Building applications using MOSS 2007 web services: Don't get me wrong, this presentation is not for developers. I am targeting IT-Professionals and I am trying to keep it at 200 level. Here is my presentation outlines:
    • What is XML Web Service?
    • How can we call XML Web Services without code (I am targeting InfoPath)?
    • Introducing built-in XML Web Services in MOSS 2007.
    • Connecting XML Web Services and MOSS 2007 document libraries using InfoPath 2007 glue (Hay InfoPath 2007 glue is NOT a product name - lol).
    • How to deploy these XML Web Service containing InfoPath forms to the MOSS 2007 forms server
    • How can developers build custom Web Services to expose more MOSS features
  • Office Automation using Microsoft Word 2007 and MOSS 2007: This is basically a case study around using Microsoft Word 2007 XML file that is also called WordML. This presentation is basically an open discussion around using WordML files instead of normal word files. I am just trying to explain how easy it is to utilize your basic XML Programming skills to manipulate sections of the WordML files.

I really appreciate if you spare a minute or two and give me your feedback.
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=338Apr 05, 2008
American or Canadian C# Code? - [Technical] The worst thing that I can imagine is that the compiled code works properly on your development/staging environment but fails to work on production. The nightmare starts when you just remember that you don't have debugger on production. Here is what happened to me yesterday. I developed a web service for the Time-Off time calculation. The code was excluding Ontario statuary holidays. This service apparently without any external dependency was working beautifully on my development laptop, but failing with some strange error on the server.

Take a look at this code:
DateTime holiday = DateTime.Parse("28/02/2008");

Sounds ok and works well on my Canadian computer (hey, it is made in China but Windows regional options is set to English(Canada)). But the very same line of code fails to run on an American machine. Simply because the American version of this code should be like this:
DateTime holiday = DateTime.Parse("02/28/2008");

That's just the date format but what can you do in a compiled code for this? Aha, .NET Framework is the answer. If you read the time variable from a Calendar or a DateTimePicker then the control is smart enough to do that, but if you are reading a preformatted string or you are hard-coding the date in your application then this issue come up. Here is the right way of solving this problem:

using System;
using System.Globalization;

namespace DotNetKing
{
    class Program
    {
        static void Main(string[] args)
        {
            CultureInfo culture = new CultureInfo("en-CA");
            DateTime holiday = DateTime.Parse("28/02/2008", culture);
            Console.Write(holiday.ToString());
        }
    }
}

This way you not only hardcode the date but also hardcode the date culture, so your code behaves Canadian even on an American server!
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=337Feb 28, 2008
Forms Server on the MOSS Farms - Silly error - [Technical]Take a look at this error first:

An error occurred accessing a data source.
An entry has been added to the Windows event log of the server.
Log ID:5566

 

Does it look familiar? No? How about this one?

I assume that you love it because without these errors we could never have a job as consultant. I got this error when I deployed an InfoPath 2007 form to MOSS 2007 forms server. There was nothing wrong with the form but it was getting the user information from MOSS profile to have some part of the form pre-populated. First of all when I checked the application log on the front end server I found nothing. Considering the farm installation I could find the error on the server box that was hosting the SharePoint Central Administration service. Here is the error in the application log:

A runtime exception was detected. Details follow.
Message: Access Denied! Only site admin can access Data Source object from user profile DB.

Techinal Details:
System.UnauthorizedAccessException: Access Denied! Only site admin can access Data Source object from user profile DB.
at Microsoft.Office.Server.UserProfiles.SRPSite.AdminCheck(String message)
at Microsoft.Office.Server.UserProfiles.DataSource._LoadDataSourceDef(IDataRecord rec)
at Microsoft.Office.Server.UserProfiles.DataSource._LoadDataSourceDef(String strDSName)
at Microsoft.Office.Server.UserProfiles.DataSource..ctor(SRPSite site, Boolean fAllowEveryoneRead)
at Microsoft.Office.Server.UserProfiles.DataSource..ctor(SRPSite site)
at Microsoft.Office.Server.UserProfiles.UserProfileConfigManager.GetDataSource()
at Microsoft.Office.Server.UserProfiles.BDCConnector.RefreshConfiguration(String sspName)

For more information, see Help and Support Center at

It seems that the forms server is trying to access to Profile Services on MOSS and it is complaining that Only Site Admin can do that. Here was the tricky part. On the top of the page I could see the spadmin login account. This account was site admin for MOSS, SharePoint Central administration and also Shared Services Provider site. So what else is missing?

The answer is here:
Go to SharePoint Central administration --> Application Management --> Authentication Providers. Then select the default zone. Make sure the right Web Application is selected on the top of the page. Clear the checkbox for the anonymous access. And now you can run your form with the forms server happily ever after.

Important point:
When you are using Forms Server with MOSS the site security is not applied to the underlying services. It means even if your MOSS website requires authentication, if Provider is anonymous enabled forms services uses anonymous login for the external access, because it looks at the provider, not the site that is hosting the form. It took me a long time to find it out because I had the impression that Forms Server impersonates the user login information and when I see the user ID on the top of my SharePoint page, this is not anonymous call. I was wrong.

With special thanks to Infusion SharePoint Technical team that gave me wonderful guides to resolve this issue.

 Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=336Feb 27, 2008
How I fell in love with Microsoft .NET - [Technical] On Feb 14, 2002 I was living in Dubai. February 14 is a very special day and every body expects e-mails and gifts from lovers. On that day early in the morning when I opened my mailbox and I was expecting lots of e-mails with pink hearts in it, I found just one e-mail that announced the final release of the .NET Framework 1.0. My god, is Microsoft .NET the only one who remembers me on Valentines day? I was working with Beta release of Visual Studio .NET but from that day I fell in love with .NET. Today is the 6th anniversary of Microsoft .NET first release. So happy birthday .NET and Happy birthday Visual Studio.

Remember that first version of .NET was released on February 13th, 2002.

I Wish all .NET Developers a
wonderful birthday
]]>http://www.dotnetking.com/TechnicalComments.aspx?LogID=333Feb 13, 2008WebPart audience targeting is not appearing - [Technical]  

 I had a funny problem today. On one of the client sites we were trying to enable audience targeting on a development server box and simply I couldn't find the Target Audiences box. Simply it was not there. Guess what the problem was!

Shared Service Provider was not created on the server.

Morale:

  1. Please do the setup steps completely and review the Setup tasks
  2. If the problem is very weird, look for some weird cause
  3. When you find the cause share it with the others

It is interesting that I couldn't find any cause for this problem by searching the internet.

Cheers
Alireza

  ]]>http://www.dotnetking.com/TechnicalComments.aspx?LogID=331Feb 08, 200864 Bit IFilter for PDF files - [Technical]  Have you ever used iFilters for PDF in MOSS? It's beautiful. You may simply download it from adobe website and install it on the MOSS Server and enjoy the enterprise content search for the PDF content. Such a sweet component becomes a pain once you'd like to upgrade to 64 bit platform, simply because  adobe iFilter it doesn't have 64 bit support.
 Last week I found Foxit PDF iFilter. It is not a free product, but $1184.93 doesn't look like an issue for a huge enterprise with 64 bit implementation of MOSS. I haven't tried it yet myself, so if you have used it before send me your feedback.

Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=329283e1bdf-4e66-497b-a480-647a3a71beedJan 14, 2008
How to setup MOSS development environment - [Technical] After I completed the MOSS development training in Barrie there was a request to a checklist to setup a MOSS development environment. Here are the steps:

  1. Configure a virtual PC machine with at lease 1GB memory allocated
  2. Install windows 2003 Server standard edition on the virtual PC (You may also go for enterprise edition, but because of some unnecessary services on enterprise edition it will perform slower than enterprise edition while it doesn't give you anything extra for MOSS development)
  3. Go to windows Control panel and Add/remove windows component:
    1. Add ASP .NET (as a result of this selection any necessary IIS component will be installed)
    2. Add local SMTP server
    3. Make sure FrontPage server extension is not selected
    4. Remove "Internet Explorer Enhanced Security Configuration". It is not a MUST, but for development environment that we need absolute freedom, it is quite annoying.
  4. Install the latest service pack available for windows 2003. (it is still too early to go for windows component update)
  5. Install Visual Studio .NET 2005 (Professional or VSTS) and make sure you Install C# components (VB .NET is not enough) and make sure you UNCHECK the SQL Server express edition that comes as embedded component in Visual Studio .NET.
  6. Install Visual Studio .NET Service pack 1.0
  7. Install .NET Framework 3.0
  8. Install MOSS 2007 as stand alone installation with all default settings
  9. Install "Visual Studio 2005 extensions for .NET Framework 3.0 (Windows Workflow Foundation)"
  10. Install MOSS 2007 SDK
  11. Install Windows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions
  12. Install Microsoft Office 2007 (InfoPath, Outlook, Word, PowerPoint, Access and Excel are mandatory). You may uncheck Microsoft Publisher, Microsoft Groove and One Note.
  13. Install Microsoft SharePoint designer 2007
  14. Install VSTO
  15. Connect the Virtual PC to Internet and run Windows Update
  16. Read this and install all the components mentioned there.

Have fun
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=3220c12f19b-c3e5-48ba-8621-c2a2491166efDec 01, 2007
Some important tips passing variables to SSIS package programmatically - [Technical]Have you ever tried to call an SSIS (SQL Server Integration Services) package programmatically? It's just a piece of cake. Hah, you haven't tried it yet? Ok, see this MSDN article. Hey guys I am not writing this weblog just to put the links that you can easily find them using any search engine. Here are my points.

I create a simple SSIS package with only one script task and two parameters and I want to call this package using C# code. I have already built this package and you can download it from here. The parameters are:

yourName (Int32) that has the value of "Alireza" already hard coded in the package
yourAge (String) that has the value of 35 and again this value is hard coded in the package

If I run this package it displayed a simple message box that shows "Hi Alireza you will be 36 next year". Now lets call this package programmatically:

Assuming that the package is loaded on "C:\SSISProgrammatically\Package.dtsx" this piece of code can run the package successfully. (don't forget to add the Microsoft.SQLServer.ManagedDTS to your project references)

string pkgLocation;
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
pkgLocation =
@"C:\SSISProgrammatically\Package.dtsx";
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(pkgLocation, null);
pkgResults = pkg.Execute();

By now it is nothing more than the MSDN example. Here are my points:

We want to pass the variables programmatically to SSIS Package. Here is how:

string pkgLocation;
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
pkgLocation =
@"C:\SSISProgrammatically\Package.dtsx";
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(pkgLocation, null);

pkg.Variables["yourName"].Value = "Dennis MacAlistair Ritchie";
pkg.Variables["yourAge"].Value = 66;


pkgResults = pkg.Execute();

OK, It is quite easy but watch out for the  data types. How do you like this example:

 string pkgLocation;
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
pkgLocation =
@"C:\SSISProgrammatically\Package.dtsx";
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(pkgLocation, null);

pkg.Variables["yourName"].Value = "Dennis MacAlistair Ritchie";
pkg.Variables["yourAge"].Value = "Ha ha!";


pkgResults = pkg.Execute();

You will end up to a bizarre execution result. It compiles successfully and runs successfully and gives you no execution result. You can simply guess that "Ha ha!" cannot be converted to integer, but where can you track this error? Server Application log? Good guess, but this is what you find in the log:"Package "Package" failed." How much it can help I really don't know but here is my advice.

NEVER RELY ON THE IMPLICIT DATA CONVERSION. Check all your variables in the SSIS package in advance and make sure all the values that you pass to SSIS variables are exactly the same data types as the variables inside the package.

Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=321f8102fca-2885-48f1-88d6-5189a20ce690Nov 24, 2007
Security concerns in custom actions in MOSS workflows - [Technical]Creating custom actions for SharePoint designer 2007 ended up with setting the item level security for the list item. Here are the important points to remember.
When creating a workflow always you have a trigger for the workflow that is bound to a document library. In better words the workflow is triggered either manually or as a response to a list item create and/or update. This trigger is assigned to the user that has fired the trigger. For example if I change a list item in WSS or MOSS and that change fires a workflow, that workflow is running under my security context. It means that the workflow will be able to do only the things that I can do as a user and cannot reach and object that I cannot reach. If you want my workflow do more than what I am allowed to do you need to run it with elevated privilege. This is how it works:
This function tries to enable anonymous access to the website http://siteURL, but with a simple function call only the users that have administrative permission to the site can do it by running this code.
 

public void SpecialFunction()
{
    //This function will do something inside SHAREPOINT that the user does not
    //have permission to do that

    // Remember to create the SPSite instance inside the function
    // otherwise it will not work as elevated permissions
   
Microsoft.SharePoint.SPSite myStrongSiteObject = new Microsoft.SharePoint.SPSite("http://siteURL");
    Microsoft.SharePoint.SPWeb myWeb = myStrongSiteObject.OpenWeb();
    myWeb.AllowUnsafeUpdates = true;
    // The user cannot enable anonymous access to the website but can run this code to
    // do this job as a part of workflow or webpart that is running this code
   
myWeb.AnonymousState = Microsoft.SharePoint.SPWeb.WebAnonymousState.Enabled;
    myWeb.AllowUnsafeUpdates = false;
}

Now if you call the function using this code:

Microsoft.SharePoint.SPSecurity.CodeToRunElevated SpecialFunctionDelegate =
  new Microsoft.SharePoint.SPSecurity.CodeToRunElevated(this.SpecialFunction);
Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(SpecialFunctionDelegate );


The code will run happily ever after by any user.
With elevated privilege you can do ANYTHING inside SharePoint and you can do almost NOTHING outside SharePoint. Using elevated privilege you may restrict the current user access to a certain object in MOSS, but you cannot re-grant it again. The logic is simple; this workflow cannot reach the object again to do something even with elevated privilege.
Of course you will find lots of sample codes like this on forums, but I just wanted to have a copy for myself for future use.
Enjoy
Alireza

 

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=320ee886e22-004f-4e62-93ab-51be896ff4a2Nov 23, 2007
Discovery of a wonderful SharePoint weblog - [Technical] Now I am getting an expert in SharePoint designer workflow development and now I can refer you to some better resources. Here you may find a detailed example. You will find lots of these examples if you search the internet. But what you can hardly find is a link like this. Make sure you read it before you start you custom action development. I really enjoyed this weblog and I am surprised that such a valuable weblog is not managed by an MVP. I personally love this style of weblog. These are the points that you cannot easily find anywhere.
Enjoy it
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=318d7176203-56a8-408c-a4aa-a8e6242238a0Nov 22, 2007
<b>Visual Studio 2008 is finally out</b> - [Technical]  
 Honestly speaking it didn’t make me happy at all. It was just two weeks that I install Visual Studio 2008 Beta release. So my first impression was “Damn it!! Couldn’t they release it two weeks earlier?” and today I am really happy. I found this article that saved my day. If you have already installed the Beta release of Visual Studio 2008 and want to get rid of it here is how. So now I can happily shout: “Horary; Visual Studio 2008 is released!”
Enjoy
Alireza ]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=317aa8c51dc-c75c-4183-96ec-d5996e782e1cNov 21, 2007
I fell in love with SharePoint designer 2007 - [Technical] We are spoiled generation of developers. .NET Framework and beautifully exposed Microsoft platform and application APIs have spoiled us so much that we rarely think of anything other than .NET, C# and VB .NET. For quite a long time I have been doing all my workflows with Visual Studio .NET and SharePoint Server 2007 SDK. When ever people were talking about SharePoint designer 2007 workflow development I was saying "Ah..., I am a developer and I want freedom to do what ever I want and SharePoint designer doesn't give me that freedom!". Only 22 out-of-box actions can only keep a kid happy.
 Today in a project that we had to do it with SharePoint designer 2007, in the middle of the project I just understood that we need to set the item level security for a form library. Damn it! SharePoint designer does not support it!!!

 Did you know that you can add custom actions to SharePoint designer 2007? In better words you can develop your actions with .NET and MOSS SDK and deploy it to Global Assembly Cache. Then add it to your SharePoint designer to use it. Do you want to know how? See it here and don't worry I don't feel jealous if you also fall in love with SharePoint designer.
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=316df5803f0-c3f9-4de0-8fa8-163b0ab6948eNov 15, 2007
Technet and MSDN Read Show - [Technical]

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=313ff246bee-f19b-4031-9f2d-bbacf12a8b26Oct 29, 2007
Where can I find the relevant material for WCF, WWF, WPF? - [Support]Hi Guys
 I received this question from Jay today and I thought this might be a questions for may of you:

Where can I find the relevant material for WCF, WWF, WPF?

 This is a very general question and I am not the right person to answer it completely. I have put all my focus on Windows Workflow Foundation and that's the only area that I can give you acceptable answers. Usually the first reference for the Microsoft technologies is Microsoft itself (Microsoft Official Curriculum, MSDN and Microsoft eLearning), but this advice doesn't work here. The first question is: what is your development background? I am not talking about .NET development skills. I mean good and deep understanding of Object Oriented concepts, Abstraction, Inheritance, Polymorphism and Design patterns. Good is not enough. You should be excellent. WF is developed based on OOA&P best practices and design patterns and once you are confident in OOA, it is quite simple to proceed. So to start with I personally recommend Object-Oriented Analysis and Design Using UML (OO-226) delivered by a very qualified instructor. As a trainer I have delivered this course for a couple of times (With Microsoft Visio and C# because I don't know Java ) and I believe this is one of the best starting points for most of the developers. Buy the way, you can find all classic design patterns in .NET here. The more you know design patterns the easier you learn WF.
As an MCT I always recommend Microsoft Official Curriculum (MOC) as the first step, but it seems that Microsoft is a little bit slow in releasing MOCs for .NET framework 3.0, so you should rely on MSDN and Microsoft eLearning at least for the time being. After the OOA&D warm up you have the following steps ahead.

  1. Understand the workflow basics: read this articles in detail Windows Workflow Foundation Overview. If some parts are not very clear don't waste time on that part. Go through it quite fast and everything will be bright. If you can understand it 70% you are in a good shape.
  2. Some visual workflow development taste: I don't mean to scare you, so let's experience the joy of Workflow Development with this article Getting Started with Microsoft Windows Workflow Foundation: A Developer Walkthrough that is published on MSDN by Solid Quality Learning (SQL). (I know Solid Quality Learning (SQL) from the time that I was living in Dubai. They gave us a training on SQL Server 2005 in July 2005 before the product release and the training was wonderful. The trainer was Dejan Sarka). I don't consider this article as a training material. It is just a developer test drive to work with workflow extension and see how it is like developing a simple workflow.
  3. Have your hands dirty with code: you may start from here Windows Workflow Foundation Tutorials depending on your taste. If you are a kind of person that can follow the code and instructions and learn the concepts, this is quite good and reliable content (this is MSDN-programmers bible, so you can put your right hand on it and swear in the court. lol). These samples are beautiful and they go deep into code level WF development. The walkthroughs are not visual and you may need a bit of code manipulation to open these examples with the workflow extension visually although all the codes compile successfully. To open the files visually you only need to make sure that workflow class is the first class definition in the code (It is just a matter of cut and paste that we are all expert in it).
  4. Spend a little bit on books: Hah, not everything comes as free download. If you are looking for a clean way of learning workflow foundation your candy material is here Microsoft® Windows® Workflow Foundation Step by Step. This book is sweet, but it doesn't mean that this book alone will make you a professional workflow developer. Good Object Oriented is still a MUST. By the way, this book is not perfect. Check this link before you start with the book.
  5. Learn workflow patterns and techniques: You are not supposed to reinvent the moon. Maybe by now you know how to drive WF; but do you know the driving rules? You can learn workflow patterns here: Programming Windows Workflow Foundation: Practical WF Techniques and Examples using XAML and C#.
  6. Find the right technology: WF is a super luxury sports car. But where can you go with this car. Not everything is .NET, Windows application or ASP .NET. The entire SharePoint workflow is built on WF. Install MOSS 2007 SDK and enjoy workflow development for MOSS with .NET.

Ok guys, I am done with my WF materials. Can anyone of you blog WCF and MPF learning path?
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=312cbef6402-bc8f-4a43-9be3-181a53e5cd64Oct 29, 2007
SQL Server 2000 and 2005! Are they compatible? - [Technical]Error: Statement(s) could not be prepared. sql server

 Today one of my colleagues was working on an archiving mechanism on New York stock center project. The scenario is archiving SQL Server 2005 data on SQL Server 2000 and the archiving job should be initiated on SQL Server 2000. He created a linked server on SQL Server 2000 that maps to SQL Server 2005 database. Then he created a Stored Procedure in SQL Server 2000 to read the data from SQL Server 2005 using cursor. He ended up with this error: Statement(s) could not be prepared. sql server
 I thought that it might be a compatibility issue for cursor technology between 2000 and 2005.
Here is the suggested solution:

 I advised him to create a temporary table on SQL Server 2000 and put the query result from the linked server on it and then he can process it. This solution worked!
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=3117f2ab2bb-a373-49fc-84aa-b5a51f92ca63Oct 29, 2007
Can anybody help me solve this MOSS issue? - [Technical] On Friday I installed MOSS at a client site on production. The database server is installed on a separate box and my MOSS server is installed under a domain account without any problem. Domain name is (as mentioned by their DBA) XYZNET and I defined two farm administrators of the same domain that they are box administrators for MOSS machine. After that I created the SharedServices successfully. When I started to import MOSS profiles it simply failed with the automatic domain detection. I noticed that the detected domain is XYZ (and not XYZNET) and the domain controller name that was automatically detected was also correct (as I checked with the network admin).
I changed my strategy and changed the profile source manually to point to domain XYZNET and again the same domain controller machine name was detected and this time MOSS successfully created more than 2000 MOSS profiles based on the AD content. So far so good; but here is the problem:
Now my MOSS farm administrators can login to the shared services administration in the SharePoint and when I try to do so, SharePoint asks me to login as a different user or request permission for the farm administrator. When I request the permission at the same point, the request is not sent although the outgoing mail server is properly configured and the e-mail is working properly with the other MOSS features like alerts and MOSS user notifications.
Here is a clue: After the installation I got this information from the network administrator that the domain name used to be XYZ in the beginning and then they changed it to XYZNET and now XYZ and XYZNET both resolve to the same domain. They also mentioned that XYZ is resolved to XYZNET properly 9 times out of 10!!! But sometimes it doesn’t!!!
My knowledge of active directory is a little bit more than 0, so I need experts’ comments urgently on this issue.
Regards
Alireza Ahmadi Aliabadi

 

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=3083c8807b9-2b36-4339-8d78-05a0603bdd83Oct 09, 2007
Free E-Learning for .NET 3.0 (don't miss it) - [Technical]

Developing Rich Experiences with Microsoft® .NET Framework 3.0 and Visual Studio® 2005
Hey guys, do you want to enjoy one of the sexiest Microsoft e-learning collections for FREE. This is my experience, they are free today and might not be free for tomorrow and this collection is phenomenal. I have tried the windows workflow foundation clinic and that is fantastic as a material to start and puts you in the track within a day. Get your free 3 year subscription today and enjoy it. By the way, Microsoft virtual lab is available and you don't need an extra effort for the setup.
Enjoy
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=303211b1c9f-a57c-4b29-b45d-006ba690f344Aug 17, 2007
Impressive InfoPath 2007 demos - [Technical] Have you ever noticed what a fancy product InfoPath is? Today I discovered this demo collection on the Microsoft website and I'd like to share the fun with you.

At least I am sure the ATC Guys will love it.
Cheers
Alireza

]]>
http://www.dotnetking.com/TechnicalComments.aspx?LogID=302fd92146c-a796-4345-bebb-e4cb9ae04128Aug 09, 2007