Sharepoint Insight by Namwar Rizvi

Sharepoint Tips, Tricks and inside knowledge from real world experience by Namwar Rizvi

Archive for the ‘C#’ Category

How to generate a valid SharePoint FileName

Posted by namwar on June 17, 2010


SharePoint imposes several restrictions for the filenames. To get the details of all these restrictions, please check this support article from Microsoft. I have created a utility function to convert a given string to a valid SharePoint filename. This function is valid for SharePoint 2003, 2007 and 2010. Here you go

public string ConvertToValidSharePointFileName(string originalFileName)
        {
            char[] InvalidFilenameCharacters = new[] {'\\', '/', ':', '*', '?', '"', '<', '>', '|', '#', '{', '}', '%', '~','&' };
            string[] InvalidFileNameStrings = new[] { ".files", "_files", 
                "-Dateien", "_fichiers", "_bestanden","_file", 
                "_archivos", "-filer", "_tiedostot", "_pliki", 
                "_soubory","_elemei", "_ficheiros", "_arquivos", 
                "_dosyalar", "_datoteke","_fitxers", "_failid", 
                "_fails", "_bylos", "_fajlovi", "_fitxategiak"};
            
            string validSharePointFileName = originalFileName;

            //Remove Invalid characters
            validSharePointFileName = validSharePointFileName.Remove(InvalidFilenameCharacters);
            
            //Remove consecutive periods(..)
            while (validSharePointFileName.Contains(".."))
            {
                validSharePointFileName = validSharePointFileName.Replace("..", ".");
            }

            //Remove reserved words from end
            foreach (string s in InvalidFileNameStrings)
            {
                if (validSharePointFileName.EndsWith(s))
                {
                    if (validSharePointFileName.Length > s.Length)
                    {
                        validSharePointFileName = validSharePointFileName.Substring(0, validSharePointFileName.Length - s.Length);
                    }
                }
            }

            //Remove period (.) at end
            if (validSharePointFileName.EndsWith("."))
            {
                validSharePointFileName = validSharePointFileName.Remove(validSharePointFileName.Length - 1, 1);
            }

            //Remove period (.) at end
            if (validSharePointFileName.StartsWith("."))
            {
                validSharePointFileName = validSharePointFileName.Remove(0, 1);
            }

            return validSharePointFileName;
        }
Advertisements

Posted in C#, Solutions, SP2010, Tips | Tagged: , , , , | Leave a Comment »

How to add custom CSS in your WebPart

Posted by namwar on June 14, 2009


If you want to add custom CSS file for your webpart, here is the code:

  1. protected override void CreateChildControls()
  2. {
  3. base.CreateChildControls();
  4. CssLink cssLink = new CssLink();
  5. cssLink.DefaultUrl = “/_layouts/Test.css”;
  6. this.Page.Header.Controls.Add(cssLink);
  7. }

Posted in C#, Solutions, Tips | Tagged: , , | Leave a Comment »

Got MCTS Status Today! – Exam 70-542 Done!

Posted by namwar on February 7, 2009


Today, I got the status of MCTS: Microsoft Office SharePoint Server 2007 ― Application Development. This exam focuses on Application Development for Sharepoint Portal Server by utilizing enterprise features. If you are preparing for this exam then I will recommend you the book Professional SharePoint 2007 Development from Wrox publishers.

Main topics covered in this exam are:

  1.  Business Data Catalog (Definition, management etc.)
  2. Data Connection Management, Trusted locations
  3. Audience Management
  4. User Profiles Management
  5. InfoPath Form Server
  6. Records Management
  7. Documents Management
  8. Excel Web Services

You will need to do hands on practice by writing code to make sure you understand object model and context management of API calls.

Good Luck!

Posted in C#, Certification | Tagged: , , | Leave a Comment »

Programmatically upload a file to Document Library

Posted by namwar on January 10, 2009


Following is a utility function which you can use to upload a file programmatically in SharePoint document library. It has two parameters. First is the source file path and second is the target document library path. 

Following is an example call to this function:

UploadFileToDocumentLibrary(@”C:\test.txt”, @”http://home-vs/Shared Documents/textfile.txt”);

and here is the function

    public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)

    {

        //Flag to indicate whether file was uploaded successfuly or not

        bool isUploaded = true;

        try

        {

            // Create a PUT Web request to upload the file.

            WebRequest request = WebRequest.Create(targetDocumentLibraryPath);

 

            //Set credentials of the current security context

            request.Credentials = CredentialCache.DefaultCredentials;

            request.Method = “PUT”;

 

            // Create buffer to transfer file

            byte[] fileBuffer = new byte[1024];

 

            // Write the contents of the local file to the request stream.

            using (Stream stream = request.GetRequestStream())

            {

                //Load the content from local file to stream

                using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))

                {

                    //Get the start point

                    int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);

                    for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))

                    {

                        stream.Write(fileBuffer, 0, i);

                    }

 

                }

            }

 

            // Perform the PUT request

            WebResponse response = request.GetResponse();

 

            //Close response

            response.Close();

        }

        catch (Exception ex)

        {

            //Set the flag to indiacte failure in uploading

            isUploaded = false;

        }

 

        //Return the final upload status

        return isUploaded;

    }

Posted in C# | Tagged: , | 12 Comments »