Thursday, 24 September 2015

Write the Exception in Page view-source under body tag with HTML generic Controls

In some requirement the exception needs to be displayed in page view-source, so the below code will explain how to make it easily,

Code Sample:

                     try
            {
                //Error Occured
                SPSite _Site = new SPSite("Site URL");
               
            }
            catch (Exception ex)
            {
                //Catching the Exception
                System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
                dynDiv.ID = "dynDivCode";
                dynDiv.InnerHtml = "\n<!--EVL Exception BeginTag-->\n<!--"+ex.Message+"-->\n<!--EVL Exception EndTag-->\n";
                this.Controls.Add(dynDiv);
              
            }

Wednesday, 10 June 2015

Convert selected date format to dd/mm/yyyy from dd.mm.yyyy for SharePoint Date Time control with German LocalId

Problem:

We have a webpart Contains the SharePoint DateTime Control. This webpart can be used in Different Sitecollection with Different Regional settings. Based on Regional settings the Calendar UI should be changed but Date format should be always in dd/mm/yyyy.

Below is the code present in ASCX file of the webpart.

   <SharePoint:DateTimeControl ID="date_GENDateRanges_To" DateOnly="true" runat="server" />


In Code behind .cs file i set the LocalId for the SharePoint DateTimeControl to get the Different calendar based on the Language.

 date_GENDateRanges_To.LocaleId = (int)SPContext.Current.RegionalSettings.LocaleId;

ex : if the LocalId =1033 is for UK so calendar UI is in English and when we select the date it display in the textbox  in format dd/mm/yyyy

if LocalId=1031 is for German so calendar UI is in German and when we select the date it display in the Textox format dd.mm.yyyy

but here is our problem starts the customer want to have the calender UI should be changed in their respective language but Selected Date format in Textbox it should be dd/mm/yyyy.

Solution :

Initially I tried with onchange event on the DateCalender Texbox, as you know SharePoint DateTime Control Consists of A TextBox and Date Picker.

Code Behind :

TextBox txtTo = (TextBox)date_GENDateRanges_To.Controls[0];
 txtTo.Attributes.Add("onchange", "javascript:return ChangeDateFormat('" + txtTo.ClientID + "');");

but onchange event on textbox never fired on selecting the date using Datepicker of SharePoint Date Control. when i change the date using Keypad then the onchange event fires. so  i started searching google and finally i have found there is a Method in DatePicker.js called "OnPickerFinish" which will be called each time you select a date from SharePoint date picker.

I override the "OnPickerFinish" method in my ascx as stated below.

function OnPickerFinish(resultfield) {
        clickDatePicker(null, "", "");

        var mystring = resultfield.value;

  if (mystring.indexOf(".") > -1) {
                var res = mystring.split(".");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                resultfield.value = Newdate;
            }
            else if (mystring.indexOf("-") > -1) {
                var res = mystring.split("-");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                resultfield.value = Newdate;
            }
        }

The above function will take care of two type of Date format as dd.mm.yyyy and dd-mm-yyyy and convert to dd/mm/yyyy.

I thought i achieved what i wanted but suddenly i stuck with another problem. whenever a Postback happend then again the changed Date of Textbox (dd/mm/yyyy) changed to the original LocalId format as dd.mm.yyyy or dd-mm-yyyy.

To overcome this problem again i called "OnPickerFinish" method from code behind as well on each post back as below.

   TextBox txtTo = (TextBox)date_GENDateRanges_To.Controls[0];
 ScriptManager.RegisterStartupScript(UpdatePanel_Search_Docs, GetType(), "Listview2", "javascript:OnPickerFinish('" + txtTo.ClientID + "');", true);

and  i have modified the OnPickerFinish method as well as given below.

function OnPickerFinish(resultfield) {
        clickDatePicker(null, "", "");

        var mystring = resultfield.value;
     
        if (mystring === undefined) {
            mystring = document.getElementById(resultfield).value;
         
            if (mystring.indexOf(".") > -1) {
                var res = mystring.split(".");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                document.getElementById(resultfield).value = Newdate;
            }
            else if (mystring.indexOf("-") > -1) {
                var res = mystring.split("-");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                document.getElementById(resultfield).value = Newdate;
            }
        }
        else {
            if (mystring.indexOf(".") > -1) {
                var res = mystring.split(".");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                resultfield.value = Newdate;
            }
            else if (mystring.indexOf("-") > -1) {
                var res = mystring.split("-");
                var Newdate = res[0] + "/" + res[1] + "/" + res[2];
                resultfield.value = Newdate;
            }
        }


    }


Hope this will help others as well and sincere apologies for my English language. Please mail me or comment if you still face the issue.

Tuesday, 9 June 2015

SharePoint Popup Model dialog is not closing on click of button

Problem :

I have to close the SharePoint Model dialog on click of the cancel Button. It worked fine in SharePoint 2010 but same code when i moved to SharePoint 2010 farm then it did not  work.

HTML Snippet:





on click i have called the CloseModelPopUp() javascript method. This javascript close the SharePoint Dialog in 2010 environment but it did not close in SharePoint 2013.

Solution :

I have searched on google and i got the idea instead of using the above code we have to use some other function. and it was easy in real just a single line of java script.



Above script worked like a charm in SP 2013 and closed the SharePoint Model Dailog.

Below link from where i got the solution.

http://sharepoint.stackexchange.com/questions/118811/sp-ui-modaldialog-close-button

You will get more explanation why the above script does not work in SharePoint 2013 using the above link.


Monday, 25 May 2015

Read and Update the SharePoint Web Part Properties present in page using Server Object Model C#

Problem Description:

We have to read and Update the Custom Webpart properties which we have created on the webpart.cs. Hope you are aware how the Custom Webpart properties created thats why you came to this page to know about how you can read  and update the custom Webpart Properties.

Custom properties
So if you see the above picture i have created a Custom Properties called the "Container ID" Whose value right now is "ABC". We have to read the Container ID in some other Page with the Help of Webpart ID and  Page URl where the Webpart is associated.


Solution:

So at first i have created a Custom Edit menu for the webpart that you can learn from my previous post . I have associated the Page URL and Webpart ID with custom Menu, on click of the custom menu it open an application Page. On Page Load of the Page I read the PageURL and Webpart ID as query string.

///
Page Load to get the Webpart properties
/// 

 protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                GetWebParts();
            }

        }

///
 get the Webpart properties using the WebpartID and PageURL
/// 
  private void GetWebParts()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string strWebPartID = Convert.ToString(Request.QueryString["WebPartID"]);
                    string strPageURL = Convert.ToString(Request.QueryString["PageURL"]);
                    SPFile file = web.GetFile(strPageURL);
                    using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts)
                        {
                            if (wp is QlistView)// QlistView is a Webpart class where you have created the Custom Webpart Properties
                            {
                                if (strWebPartID.Contains(wp.ID))
                                {
                                    QlistView wp1 = wp as QlistView;// QlistView is a Webpart class where you have created the Custom Webpart Properties


                                    txtContainerID.Text = wp1.ContainerID; // txtContainerID is part of the Page UI
                                
                                    wpm.SaveChanges(wp);
                                }
                                /// ...
                            }
                         

                        }
                    }
                }
            }
        }
///
Below method is used to Update the Custom Webpart Properties
///
  protected void btnSaveUpper_Click(object sender, EventArgs e) // btnsaveUpper is a button on the Page UI
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    string strWebPartID = Convert.ToString(Request.QueryString["WebPartID"]); 
                    string strPageURL = Convert.ToString(Request.QueryString["PageURL"]);
                    SPFile file = web.GetFile(strPageURL);
                    using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts)
                        {
                            if (wp is QlistView)// QlistView is a Webpart class where you have created the Custom Webpart Properties
                            {
                                if (strWebPartID.Contains(wp.ID))
                                {
                                    QlistView wp1 = wp as QlistView;// QlistView is a Webpart class where you have created the Custom Webpart Properties

                                    wp1.ContainerID = txtContainerID.Text;
                                
                                   
                                    wpm.SaveChanges(wp);
                                }
                                /// ...
                            }
                          
                        }
                    }
                }
            }
        }

By using the above method you can read and Update the Custom webpart Properties in SharePoint 2010. Let me know if you have any more query on this. Ready to accept your suggestion.

Create Custom Webpart Menu item ( Verbs ) like Edit web part in SharePoint 2013 using C#


Problem Description:

We have the requirement to add new webpart menu like below pic. On click of the Custom menu we have to associate to a Javascript which will open SharePoint popup page.


Solution : 

I searched a lot on google try to figure out how we can add custom menu to the webpart with the Keyword "Create Custom Webpart Menu in SharePoint 2010" . but i could not find any result on first two three pages of google Result. finally i found in some page this webpart menu items are called as Webpart Verbs. Once i get this (Verbs)  Keyword it was easy for me to get the piece of code from google. I am just writing this if someone like me doesn't know about the Webpart Verbs , for them it might be useful.

Code :

Add the below code in your Webpart.cs file, it should create a Custom menu as shown in above figure.

   public override WebPartVerbCollection Verbs
        {
            get
            {
               
                var yourVerb = new WebPartVerb(ID + "yourVerb ", "showModel('"+ID+"')") { Text = "Edit List View webpart" };
               
                var verbs = new[] { yourVerb };
                return new WebPartVerbCollection(base.Verbs, verbs);
            }

        }

We have to Override the WebpartCollection Verbs property and add new custom verb to the collection. In the Above method, i have "showModel" Javascript method which will be called on click of the Menu "Edit List View webpart". You can write either server side code or Java script function against the custom menu.

Hope this article will help to create a custom menu in the webpart.

Ask me if you have any doubt.







Monday, 23 March 2015

Modifying Microsoft Excel sheet using OpenXML in SharePoint 2010 webpart or Asp.net pages

Issue Description

Need to update the Microsoft Excel sheet by adding the color to cell, updating cell value and Replacing the images in SharePoint web partusing DocumentFormat.OpenXml.dll.

Solution
I had to achieved the above requirement using OpenXML ( 3.5 Net Version and above) only since  no other third part client has agreed for, so i started searching to web and found some bits and pieces result from MSDN and Stackoverflow.com. but here i collate all the Information with the sample code so you can use in your project if you have similar kind of requirement.

Click on the link to download the code.

Some explanation to understand the code

- Sample code Folder name is GeneratePDF.zipa - dont go with the name i was using this project initially for GeneratePDF and later used for this Excel update requirement.

- Rename the GeneratePDF.zipa to .zip file so you can extract the file and get the working solution with you.

- In my case, i have an excel template is ready and stored in a SharePoint Document Library.

- Next step i read this Excel template and get the document to Memory stream.

- Load the memory stream to the Spreadsheet object of OpenXMLLibrary

-I have created some methods to work for you easily so you no need to understand all the codes

Methods to Replace the Image in Excel using OpenXML

    ///


        /// Replaced the Image with specific Image from File Location
        ///
        /// <param name="document" - Spreadsheet Document></param>
        /// <param name="wbPart"  Workbook part></param>
        /// <param name="replacement"   Replacement Image Path></param>
        /// <param name="row" which row you want to replace the image></param>
        /// <param name="col"  which Column you want to replace the Image ></param>
private static void ReplaceImageFromSpecificLocation(SpreadsheetDocument document, WorkbookPart wbPart, string replacement, string row, string col)
        {
            var workSheet = wbPart.WorksheetParts.FirstOrDefault();

            TwoCellAnchor cellHoldingPicture = workSheet.DrawingsPart.WorksheetDrawing.OfType<TwoCellAnchor>()
                 .Where(c => c.FromMarker.RowId.Text == row && c.FromMarker.ColumnId.Text == col).FirstOrDefault();

            OneCellAnchor cellHoldingPicture1 = workSheet.DrawingsPart.WorksheetDrawing.OfType<OneCellAnchor>()
                .Where(c => c.FromMarker.RowId.Text == row && c.FromMarker.ColumnId.Text == col).FirstOrDefault();

            string rIdofPicture = string.Empty;
            if (cellHoldingPicture != null)
            {
                var picture = cellHoldingPicture.OfType<DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture>().FirstOrDefault();

                string PictureName = picture.NonVisualPictureProperties.LocalName;
                rIdofPicture = picture.BlipFill.Blip.Embed;
            }
            if (cellHoldingPicture1 != null)
            {
                var picture = cellHoldingPicture1.OfType<DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture>().FirstOrDefault();
                rIdofPicture = picture.BlipFill.Blip.Embed;

            }




            ImagePart imageInThisCell = (ImagePart)workSheet.DrawingsPart.GetPartById(rIdofPicture);

            foreach (var part in document.WorkbookPart.GetPartsOfType<WorksheetPart>())
            {

                // get drawingpart of worksheetpart

                var drawingPart = part.DrawingsPart;



                if (drawingPart != null)
                {

                    // load drawing part to XmlDocument for processing

                    XmlDocument doc = new XmlDocument();

                    doc.Load(drawingPart.GetStream());

                    drawingPart.DeletePart(imageInThisCell);

                    // add the ImagePart

                    ImagePart newPart = drawingPart.AddImagePart(ImagePartType.Jpeg, rIdofPicture);

                    // replace image




                    using (FileStream stream = new FileStream(replacement, FileMode.Open))
                    {

                        // feed data to the newPart

                        newPart.FeedData(stream);

                    }


                    doc.Save(drawingPart.GetStream(FileMode.Create));
                }



            }
        }

-- 


Method to Update the Cell Value 

 ///


        /// 
        ///
        /// <param name="spreadSheet" - Spreadsheet Object></param>
        /// <param name="text"  The Text to be replaced></param>
        /// <param name="rowIndex" Row Index where the value need to repalced></param>
        /// <param name="columnName" ColumnName where the value need to be replaced></param>
   public static void UpdateCell(SpreadsheetDocument spreadSheet, string text, uint rowIndex, string columnName)
        {

            WorksheetPart worksheetPart =
                  GetWorksheetPartByName(spreadSheet, "Sample PDF Design");// Sample PDF Design is your sheet Name
            // InsertImage(worksheetPart, 1, 1, 3, 3, new FileStream(ImageFile, FileMode.Open));

            if (worksheetPart != null)
            {
                Cell cell = GetCell(worksheetPart.Worksheet,
                                         columnName, rowIndex);
                Stylesheet styleSheet = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
                cell.CellValue = new CellValue(text);
                worksheetPart.Worksheet.Save();

            }

        }


Method to Update the the Cell Value with Cell Color

   public static void UpdateCellWithBackColor(SpreadsheetDocument spreadSheet, System.Drawing.Color Backcolor, uint rowIndex, string columnName)
        {

            WorksheetPart worksheetPart =
                  GetWorksheetPartByName(spreadSheet, "Sample PDF Design"); // Sample PDF Design is your sheet Name
            // InsertImage(worksheetPart, 1, 1, 3, 3, new FileStream(ImageFile, FileMode.Open));

            if (worksheetPart != null)
            {
                Cell cell = GetCell(worksheetPart.Worksheet,
                                         columnName, rowIndex);
                Stylesheet styleSheet = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
               // cell.CellValue = new CellValue(text);
                UInt32Value headerFillIndex =
                 createFill(
                     styleSheet,
                     Backcolor);
                //cell.DataType =
                //    new EnumValue<CellValues>(CellValues.Number);
                UInt32Value StyleIndex =
                 createCellFormat(
                     styleSheet,
                     null,
                     headerFillIndex,
                      null);

                cell.StyleIndex = StyleIndex;// GetStyleIndex(spreadSheet.WorkbookPart, cell);
                // Save the worksheet.
                worksheetPart.Worksheet.Save();

            }

        }
There are some supporting method might be used in above method, so please Download whole code and find the appropriate method. After changing the Excel sheet again i am saving to a Temp folder in Documents Library of SharePoint.

Let me know if you face any issue with above solution. i will try to help you.

Thanks cheers. :)





Wednesday, 11 March 2015

Merge two or More PDF into a single PDF using PDFSharp Library in SharePoint 2010

Problem:

Need  to merge two or more PDFs into a single PDF in SharePoint 2010


Solution:

I have searched around web for the solution and it seems many third Party dlls like itextsharp,selectPDF, PDFSharp etc are available to achieve this functionality. I go with PDFsharp free Licence.

Download the PDFsharp  dll

Below is the code :

arrFilesToZip - This is array list to store all the PDF file location which you want to merge.
CombinedFilePath - This  is the Merge PDF file full path URL


                PdfDocument outputDocument = new PdfDocument();

                // Iterate files
                foreach (object tmpfile in arrFilesToZip)
                {
                    string file = (string)tmpfile;
                    // Open the document to import pages from it.

                    PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

                    // Iterate pages

                    int count = inputDocument.PageCount;
                    for (int idx = 0; idx < count; idx++)
                    {
                        // Get the page from the external document...
                        PdfPage page = inputDocument.Pages[idx];

                        // ...and add it to the output document.
                        outputDocument.AddPage(page);

                    }
                }

                // Save the document...

   
                string combinedFilesPdfName = "CombinedFilePath"+".pdf";
                //  if (File.Exists(combinedFilesPdfName))
                //      File.Delete(combinedFilesPdfName);



                outputDocument.Save(combinedFilesPdfName);

Please let me know if you face any issue in merge of the files using this code.

cheers.


Create a ZIP file using ICSharpCode.SharpZipLib in SharePoint 2010 webpart

Problem :    

We have to generate a zip file in SharePoint  webpart from a no of files present in a Physical path

Example : 
Files :   ABC.pdf, DEF.pdf, GHI.pdf

Zip file : xyz.zip 


Solution :

I have found the solution on web to use ICSharpCode.SharpZipLib(Free)  and convert the number of files into a single zip file.
Below is the code i have attached.

Parameter for below function:

arrFilesToZip - ArrayList with all the Full file Path name which you want to zip

FolderName - Full path of the folder where you want to save your zip file

sZipFileName- Zip file name


public string CreateZipfile(ArrayList arrFilesToZip, string folderName, string sZipFileName)
        {
            try
            {


                using (ZipOutputStream s = new ZipOutputStream(File.Create(folderName + "\\" + sZipFileName + ".zip")))
                {
                    s.UseZip64 = UseZip64.Off;
                    //s.IsStreamOwner = false;
                    ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                    foreach (string pathname in arrFilesToZip)
                    {
                        byte[] buffer = File.ReadAllBytes(pathname);

                        ZipEntry entry = new ZipEntry(Path.GetFileName(pathname));
                        entry.DateTime = DateTime.Now;
                        entry.Size = buffer.Length;
                        entry.CompressionMethod = CompressionMethod.Stored;

                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;

                        s.PutNextEntry(entry);
                        s.Write(buffer, 0, buffer.Length);
                    }
                    s.Finish();
                    s.Flush();
                    s.Close();
                }


                return folderName + "\\" + sZipFileName + ".zip";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Please let me know if you have any issue in understanding of code. 

Appreciate of any suggestion.:)


Wednesday, 28 January 2015

Getting $Resources:core,ImportErrorMessage error while importing a .webpart-File to a SharePoint2010

Problem :

I have developed a Visual Web part using VS 2010 and deployed to my Local Development environment directly through Visual studio right click Deploy feature. It works fine.

Now i have to move this webpart to the QA environment where no VS 2010 installed. and the environment is like we have to put the dll file in Bin folder of web application, ASCX control we have to put on Control Template.

Step 1 : so i have put the dll and ASCX control to respective folder.

Step 2 : I added the Safe control entry for that dll in web config.

Step 3 : Now i have exported the .webpart file from my Dev Environment site and import to QA environment site Webpart gallery.

Step 4 : I was able to see the webpart in the custom group of webparts.

Step 5 : when i tried to add the webpart to Page i get the Error " $Resources:core,ImportErrorMessage"

Solution :

I tried with all solution available on Internet like add Safe control entry to web config for DLL. verified the dll Public Key token and same GUID in Safe control. but nothing worked out.

After a long effort, i deployed the solution to my Development environment using VS 2010. it creates a Pkg Folder. 

This folder has a feature folder with .webpart file.

I took this .webpart file and uploaded to QA Environment and then Error Message gone and webpart works perfectly.

so in my view problem was with .webpart file which i have exported from DEV and then try to import to QA. so its always better to take the .webpart file from the pkg Folder and upload to another QA site.

Let me know if anybody has any other solutions.

Updated : Actually today ( 24th MARCH 2015) a found the exact problem when you Upload webpart.xml from your Project Folder to webpart gallery then Webpart still refer Project Assembly file which is not present at server.

So you have to change the Project Assembly reference from the actual DLL refrence which you put either in gac or bin folder while you deploy your webpart.

Thank you Cheers.






Friday, 23 January 2015

Get Date Format from Regional Setting of SharePoint 2010 Site programmatically using C#

Scenario:

The requirement was to get the date format for the multilingual web part from the regional setting of a SharePoint site. It had to be achieved programmatically using C# code.

Solution:

DateTime UtcTime = Convert.ToDateTime(DateTime.Now).ToUniversalTime();
            
DateTime Timestamp = SPContext.Current.Web.RegionalSettings.TimeZone.UTCToLocalTime(UtcTime);

SPRegionalSettings RegionSet = SPContext.Current.Web.RegionalSettings;

string Dateformat = System.Globalization.CultureInfo.GetCultureInfo(Convert.ToInt32(RegionSet.LocaleId)).DateTimeFormat.ShortDatePattern;

Label1.Text = Convert.ToString(Timestamp.ToString(Dateformat));

Snippet:





you can comment if you are facing still with any issues.

Wednesday, 21 January 2015

Get Operating system Information using JavaScript in a SharePoint Page

Issue Description:

Recently Business user has asked me to display the Browser Operating system to the top of a SharePoint Portal home page. So if some SharePoint functionality does not support for Windows XP or other operating system, user should be aware of that.

Restriction: We should not use the Server side code

Diagnosis:

I planned to go with java script solution to get the OS details. I have searched over the internet and found some of the solution. One of the solution I am going to use below.



Solution:

 I have added a content Edit webpart to the Home page of the Portal.

Added the below HTML code to the Content Editor.


HTML Code:

create a div element with id "OSMessage" and give the style="Float:right".


Add below code to java script tag


_spBodyOnLoadFunctionNames.push("GetOS");

function GetOS()
{
var nAgt = navigator.userAgent;


        // system
        var os;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];

        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

var divMessage=document.getElementById('OSMessage');

divMessage.innerHTML="";
divMessage.innerHTML = divMessage.innerHTML + 'Your Computer Operating system is '+os;



}



After adding this piece of code to the content Editor, you will get the output as similar to the below screen shot.




Here in this example I have Operation system as Windows 7. So outputs will is “Your system Operating System is Windows 7”.

Need Your Help: I want to know whether the service Packs information of Operating system also we can get  using the script that I am not able to achieve. Please help me if anybody has the solution.

Always appreciate your comments.  And yes I got most of the code from Stackoverflow.com.




Friday, 9 January 2015

“The type is not registered as safe” when trying to add a webpart to a page in SharePoint 2010

Issue Description:

I had a SharePoint web part solution that is created by my Onsite Colleague. I have deployed the same solution in my Local SharePoint Environment and the Web Part added to the solution gallery. When I add the WebPart to the Page it worked perfectly as it was working on my client colleague machine. So no problem at all. Problem started when he has send the solution second time after doing some modification. Again I followed the same Process to deploy the web part solution. Web part was available in web Part Gallery but whenever I try the webpart to the Page it gives Error: “The type is not registered as safe”
For Information I was using VS 2010 to deploy the Farm Solution to the SharePoint 2010 single Machine Environment.

Diagnosis:

 I have heard this error before and I know the solution to that might be Safe Control Entry is not added properly to web config of SharePoint Web application but it was not that case. Safe Control Entry was properly added. Next I check the assembly Public Key Token which was present in GAC and match with Assembly Key Token present in the Register safe control entry in Web Config of the Web Application. Still I found both the Public Key Token also same. After this I started to take help from Google but most of the Blogs were almost saying the same which I tried initially to solve the Issue.
I Have spent more than 6 Hours to figure out what and where is going wrong, so I am not able to add the Web Part.

Solution:

Finally I have found the Issue with the Name space of the web part. It was changed from the previous correct Namespace. Once I have change back the same old Namespace it was working fine. So be careful and check the proper Namespace of the Webpart and same Namespace should be registered into the Safe Control of Web Config File. Please Ask me if you still face the issue