20 December 2011

Export SharePoint 2010 sites list to Excel File

How to get the SharePoint 2010 sites list to Excel using Powershell?

Go to SharePoint 2010 Management Shell.


You have to open the Web Application, then the Site Collection, after Select the Fields and Export to Excel (csv file)
$Get-SPSite | Get-SPWeb | Select url,title | Export-Csv



All this on one line in PowerShell, just think how much time it saves time instead of building a console application.

Yours
Roi

18 December 2011

Sharepoint 2007 Crawl Never Ends - Always Status Crawling

I had "Not Stopped the Search Index Crawler " case in SharePoint 2007 (in “Crawling” status indefinitely) and doesn't respond to stop requests
I had not stopped the search case "Stop Crawl"
But nothing - stuck "Stopping"

The solution:
 Enter the following stsadm commands : execadmsvcjobs, osearch -action stop, -o osearch -action start -role Index

C:\>stsadm -o  execadmsvcjobs
Executing .
Operation completed successfully.
C:\ >stsadm -o osearch -action stop
The Office SharePoint Server Search service was successfully stopped.
C:\>stsadm -o osearch -action start -role Index
The Office SharePoint Server Search service was successfully started.

Now you need to do - Reset all craweld content



Now re-run the indexing, this should solve the problem.

Hope I helped,
Roi

15 December 2011

SPListItem​Collection to Linq List

This time you code gives us extension to SPListItemCollection object.

SPListItem​Collection to Linq List

If you want to work with the object of SPListItemCollection using linq - The following code can help

public static List<SPListItem> ToList(this SPListItemCollection items)
{
    IEnumerable<SPListItem> itemsContiens = items.OfType<SPListItem>();
    return itemsContiens.ToList<SPListItem>();
}

Yours...
Roi

14 December 2011

The underlying connection was closed: An unexpected error occurred on a receive

When I tried to access an external server on the server side (not the organization) through the code (in my case web-part of sharepoint) I got an error:

The code is simple code:

public XmlDocument GetXmlData()
{
    XmlDocument document = new XmlDocument();
    //Now load the XML Document
    document.Load(this.url);// fall
    return document;
}

The error I got it:

   The underlying connection was closed: An unexpected error occurred on a receive.

   Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

   at System.Net.HttpWebRequest.GetResponse()
   at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
   at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
   at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
   at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
   at System.Threading.CompressedStack.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
   at System.Xml.XmlTextReaderImpl.OpenUrl()
   at System.Xml.XmlTextReaderImpl.Read()
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
   ...

In Visual Studio it looks like this:
The underlying connection was closed: An unexpected error occurred on a receive

I tried to execute the code in another request.
Then in another Thread.
And almost before I gave up, I tried to do impersonation with another user.
Nothing works....

Then I realized the problem - is the problem of information security.
I defined proxy in web.config - and cheers .... It works

Setting in web.config

  <system.net>
    <!--proxyaddress is the url address of the Company with the port-->

     <defaultProxy>
       <proxy usesystemdefault="True" proxyaddress="http://myporxy:port" bypassonlocal="True" />
     </defaultProxy>
   </system.net>

Hope I helped,
Roi

11 December 2011

Update SharePoint fields on Client-Side with spservices

This time I will present a client-side code (JavaScript) - which updates a list of fields without having to insert the data (edit) into the form.

All you need is another class from beloved and familiar - jquery that Called- spservicehttp://spservices.codeplex.com/
It works in 2007 and 2010 because the code in the form ajax turns  to the sharepoint web-service. (Although in 2010 we have the "Client Object Model").
The following code built two objects - an image and textbox


I make an update of the field after clicking on the image, and then I prevent users from updating again.
Please note, I use the method of spservice SPUpdateMultipleListItems.
The method get the following variables:
webURL, listName, CAMLQuery, batchCmd, valuepairs, debug

...
  <input type="text" id="txt<%=this.UniqueID%>" class="myClass1" value="<%=likeValue%>" />
  <img class="myClass2" id="btn<%=this.UniqueID%>" src="/_layouts/images/img.gif" alt="" />
...  
<script type="text/javascript">
    $(document).ready(function () {
        // The id$= is doing a regex match for an id ENDING with btn.
        var btn = $("img[id$='btn<%=this.UniqueID%>']");
        btnLike.click(function () {
            var txt = $("input[id$='txt<%=this.UniqueID%>']");
            var myValue = parseInt(txt.val()) + 1;
            var strVal = myValue.toString();
            $().SPServices.SPUpdateMultipleListItems(
                {
                    webURL: "<%=webUrl%>",
                    listName: "<%=listName%>",
                    CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Counter'><%=itemId%></Value></Eq></Where></Query>",
                    batchCmd: "Update",
                    valuepairs: [["<%=field1%>""..."], ["<%=field2%>", strVal]],
                    debug: true
                });
            txt.val(myValue);
            txt.attr("disabled""disabled");
            btn.attr("disabled""disabled");
        });
    });
</script>

Now you can update an item on every page with the content editor web-part that add the JS code.
I do not think the syntax is complicated,
If you have any questions, I'm here

Yours,
Roi Kolbinger

23 November 2011

Barrier: synchronizes threads in freamwork 4

Question:

How to build a barrier like a a traffic light for threads and synchronize them?

Solution:

That's what brought us to the barrier of framework 4!



I built code that gets three threads and trying to sync.
There are three types of situations:
1. Green - do not get their delayed and continue normal (driving).
2. Yellow - paused for a second and then goes through the green.
3. Red - delayed for 2 seconds and then goes through the yellow color.


The following code shows a good example of a barrier. Sync object is a barrier. It causes delay by type situation. Join activates the trigger of the action (TrafficLightsAction).

using System;
using
 System.Collections.Generic;
using
 System.Linq;
using
 System.Text;
using
 System.Threading;
using
 System.Threading.Tasks;
namespace
 BarrierTrafficLights
{
     class Program

     {
         static Barrier sync;
         static void Main(string[] args)
         {
             sync = new Barrier(participantCount: 3);
             var Car1 = new Thread( () =>
             {
                 TrafficLightsAction("Car 1 (green light source)"colorTrafficLights.green, true);
             });
             Car1.Start();
             var Car2 = new Thread(() =>
             {
                 TrafficLightsAction("Car 2 (yellow light source)"colorTrafficLights.yellow, true);
             });
             Car2.Start();
             var Car3 = new Thread(() =>
             {
                 TrafficLightsAction("Car3 (red light source)"colorTrafficLights.red, true);
             });
             Car3.Start();


             Car1.Join();
             Car2.Join();
             Car3.Join();

             sync.Dispose();
             Console.ReadKey();
         }
         static void TrafficLightsAction(string name, colorTrafficLights color, bool firstTime)
         {
             if (firstTime)
                 Console.WriteLine("{0} has reached the intersection with traffic lights", name, color);
             switch (color)
             {
                 case colorTrafficLights.green:
                     Console.WriteLine("{0} drove a green light", name);
                     break;
                 case colorTrafficLights.yellow:
                     Console.WriteLine("{0} is at a yellow light ", name);
                     Thread.Sleep(1);
                     TrafficLightsAction(name, colorTrafficLights.green, false);
                     break;
                 case colorTrafficLights.red:
                     Console.WriteLine("{0} is at a red light ", name);
                     Thread.Sleep(2);
                     TrafficLightsAction(name, colorTrafficLights.yellow, false);
                     break;
             }
             sync.SignalAndWait();
         }
     }
     enum colorTrafficLights

     {
         green, yellow, red
     }
}

Hope you understood,
Roi

04 November 2011

Server is too busy

This time I came across a seemingly simple problem
I received the following message at the portal

Server is too busy


CPU processor of Windows SharePoint Server yield was 100% !!!

CPU 100%

Thanks to RRaveen - How to resolve the “Server Too Busy” error in asp.net, I understand what the problem.
Previously explained how to solve a problem of "large data transfer in web service"
I showed how to change executionTimeout on the web.config

To correct the error - You need to change the variable "executionTimeout" to 3600 (this an hour because it a number of seconds - 60 * 60 = 3600)

Go to the web.config and set the tag httpRuntime the following code on the "system.web" tag.

<system.web>
  <httpRuntime executionTimeout="3600" maxRequestLength="51200">
...
This should solve the problem. If not,
Should reduce the number (the default is 110 seconds).

thanks,
Roi

29 October 2011

value does not fall within the expected range

Did you have the following situation? Access to the sharepoint list. Operations in any action, then try to contact list again, but this time, and receive the following message

value does not fall within the expected range.


What to do?

You need to refrash the web and the list!

Use this code:

/// <summary>
/// Refresh a List
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public static SPList RefreshList(SPList list)
{
     return RefreshWeb(list.ParentWeb).Lists[list.ID];
}

/// <summary>
/// Return the web
/// </summary>
/// <param name="web"></param>
/// <returns></returns>
public static SPWeb RefreshWeb(SPWeb web)
{
     web = new SPSite(web.Site.ID).OpenWeb(web.ID);
     web.AllowUnsafeUpdates = true;
     web.Lists.IncludeRootFolder = true;
     return web;
}

Here is an example of using the code - I had a problem in this case without using Refresh List.

using (SPSite site = new SPSite(siteUrl))
{
  using (SPWeb web = site.OpenWeb(webId))
  {
    // Get a list.

    SPList list = web.Lists[listId];
    SPView view = list.Views[viewId];
    SPQuery query = new SPQuery(view);
    String FieldsXml =  "<FieldRef Name=… />";
    query.ViewFields = FieldsXml;
    SPListItemCollection items = list.GetItems(query);
    foreach (SPListItem item in items)
    {    
       
list = Lists.RefreshList(list);
        SPListItem item1 = list.GetItemById(item.ID);
        foreach (SPListItemVersion itemVer in item1.Versions)
        { 

           
        }

    }
  
 }// dispose web 
}// dispose site


Yours,
Roi

19 October 2011

Update SharePoint Master Page with Code (C#)

This time I brought a code which allows you to update SharePoint master page on console project (with C#.Net and not with SPD).

We look for a site that starts with "http://moss2007/Test-Base/", check that the masterpage had the old version, and we will update the new masterpage.

For this subject, we'll have to save the masterpage on a physical file (C:). In addition, we have to approve the masterpage.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Administration;

namespace Roi.SharePoint.UpdateMasterPage
{
  class Program
  {
    private const string oldMasterPage = "workgroup.master";
    private const string newMasterPage = "NewMaster.master";
    static void Main(string[] args)
    {
      SPWebApplication wepApp = SPWebApplication.Lookup(new Uri("http://moss2007/"));
      foreach (SPSite site in wepApp.Sites)
      {
        using (SPWeb web = site.RootWeb)
        {
          // Get the current "SPWeb" object
          if (web.Url.StartsWith("http://moss2007/Test-Base/"))
          {
            try
            {
              if (web.MasterUrl.ToLower().Contains(oldMasterPage))
              {
                //read file and upload content as bytre array
                FileStream fileReader = new FileStream(@"C:\" + oldMasterPage, FileMode.Open, FileAccess.Read);
                byte[] fileContent = ReadFully(fileReader, fileReader.Length);
                SPFile file = site.GetCatalog(SPListTemplateType.MasterPageCatalog).RootFolder.Files.Add(newMasterPage, fileContent);
                file.CheckIn("File Check In", SPCheckinType.MajorCheckIn);
                file.Approve("File Approve");
                if (PublishingWeb.IsPublishingWeb(web))
                {
                  // open publish site
                  PublishingWeb pub = PublishingWeb.GetPublishingWeb(web);
                  // change the Master Page
                  pub.MasterUrl.SetValue(pub.MasterUrl.Value.ToLower().Replace(oldMasterPage, newMasterPage), true);
                  pub.CustomMasterUrl.SetValue(pub.MasterUrl.Value, true);
                  pub.MasterUrl.SetInherit(false, true);
                  pub.CustomMasterUrl.SetInherit(false, true);
                  // save changes
                  pub.Update();
                }
                else
                {
                  // change the Master Page
                  web.MasterUrl = web.MasterUrl.ToLower().Replace(oldMasterPage, newMasterPage);
                  web.CustomMasterUrl = web.MasterUrl;
                  // save changes
                  web.Update();
                }
              }
              else // if not workgroup.master
              {
              }
              web.Update();
              System.Console.WriteLine("The web was update.");
            }
            catch (Exception ex)

            {
              System.Console.WriteLine("Error:");
              System.Console.WriteLine(ex.Message);
            }
          }
        }
      }
      // Return to calling environment : Success
      Environment.Exit(0);
    }
    /// <summary>
    /// Reads data from a stream until the end is reached. The
    /// data is returned as a byte array. An IOException is
    /// thrown if any of the underlying IO calls fail.
    /// </summary>
    /// <param name="stream">The stream to read data from</param>
    /// <param name="initialLength">The initial buffer length</param>
    public static byte[] ReadFully(Stream stream, long initialLength)
    {
      try
      {
        // If we've been passed an unhelpful initial length, just
        // use 32K.
        if (initialLength < 1)
        {
          initialLength = 32768;
        }
        byte[] buffer = new byte[initialLength];
        int read = 0;
        int chunk;
        while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
        {
          read += chunk;
          // If we've reached the end of our buffer, check to see if there's
          // any more information
          if (read == buffer.Length)
          {
            int nextByte = stream.ReadByte();
            // End of stream? If so, we're done
            if (nextByte == -1)
            {
              return buffer;
            }
            // Nope. Resize the buffer, put in the byte we've just
            // read, and continue
            byte[] newBuffer = new byte[buffer.Length * 2];
            Array.Copy(buffer, newBuffer, buffer.Length);
            newBuffer[read] = (byte)nextByte;
            buffer = newBuffer;
            read++;
          }
        }
        // Buffer is now too big. Shrink it.
        byte[] ret = new byte[read];
        Array.Copy(buffer, ret, read);
        return ret;
      }
      catch (IOException ex)
      {
        System.Console.WriteLine("Error:");
        System.Console.WriteLine(ex.Message);
        return null;
      }
    }
  }
}

Cheers,
Roi Kolbinger

12 October 2011

Daily alerts do not work at SharePoint

Did you encounter a problem alerts list?

Something strange happened to me (hurray sharepoint ...).
Alerts were working fine - just a list daily alerts stopped working. I really do not know why this list.

After searching on google - I realized that take care stsadm commands such problems.

All you have to do is make those commands in the order (and of course replace the http://YOURSITE to your site).

stsadm -o updatealerttemplates -url http://YOURSITE -f "c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\alerttemplates.xml" -LCID 1037

stsadm.exe -o setproperty -url http://YOURSITE -pn alerts-enabled -pv true

stsadm.exe -o setproperty -url http://YOURSITE -pn job-immediate-alerts -pv "every 5 minutes"

I would like to thank Noam - helped me find the solution and fix the problem.

Your,
Roi

21 September 2011

How to Convert Image to Byte Array or Bitmap

This time I present code that can help you work with images (System.Drawing).
I showed how to convert Image to Byte Array and how to convert Image to Bitmap.

here is the code:

/// <summary>
/// Image Converter from Image to byte array
/// </summary>
/// <param name="img">Image</param>
/// <returns>byte</returns>
public static byte[] ImageToByte(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (byte[])converter.ConvertTo(img, typeof(byte[]));
}

/// <summary>
/// Image Converter from Image to Bitmap
/// </summary>
/// <param name="img"></param>
/// <returns></returns>
public static Bitmap ImageToBitmap(Image img)
{
    ImageConverter converter = new ImageConverter();
    return (Bitmap)converter.ConvertTo(img, typeof(Bitmap));
}

Yours,
Roi

16 September 2011

Whether the current user belongs to a SharePoint group policy

This time I will present the work Code which provides the current user has identification.

    #region Permission
    /// <summary>
    /// return true is the CurrentUser has Permission in CurrentWeb
    /// groupNames is the groups that split by ';'.
    /// </summary>
    /// <param name="groupNames"></param>
    /// <returns></returns>
    public static bool IsUserHasPermission(string groupNames)
    {
      SPUser user = SPContext.Current.Web.CurrentUser;
      SPWeb web = SPContext.Current.Web;
      return IsUserHasPermission(groupNames,web,user);
    }
    /// <summary>
    /// return true is the User has Permission in Web
    /// groupNames is the groups that split by ';'.
    /// </summary>
    /// <param name="groupNames"></param>
    /// <returns></returns>
    public static bool IsUserHasPermission(string groupNames, SPWeb web,SPUser user)
    {
      try
      {
        string[] arrGroups = groupNames.Split(';');
        bool isUserHasPermission = false;
        if (!String.IsNullOrEmpty(groupNames))
        {
          if (user.Groups.OfType<SPGroup>().Where<SPGroup>(x => arrGroups.Contains(x.Name)).Count() > 0)
          {
            isUserHasPermission = true;
          }
          List<SPGroup> grps = new List<SPGroup>();
          // checking if current user exist in group
          foreach (SPGroup grp in web.Groups)
          {
            if (arrGroups.Contains(grp.Name))
              grps.Add(grp);
          }
          if (grps.Where<SPGroup>(x => x.ContainsCurrentUser).Count() > 0)
          {
            isUserHasPermission = true;
          }

        }
        return isUserHasPermission;
      }
      catch (Exception ex)
      {
        SetErrorMessage(ex);
        throw ex;
      }
    }
    #endregion

All you need to send method - This group names. You can also submit the web and user.

Example for groupNames :
string groupNames = "Group1;Group2;Group3";

yours,
Roi

11 September 2011

Error occurred in deployment step 'Recycle IIS Application Pool': The local SharePoint server is not available. Check that the server is running and connected to the SharePoint farm

Did you receive the following error when you tried to compile a project of SharePoint 2010?

Error occurred in deployment step 'Recycle IIS Application Pool': The local SharePoint server is not available. Check that the server is running and connected to the SharePoint farm.



So - the solution is simple
You should be Full Permission on the SharePoint Farm - including a data base (DB owner).
After it is completed - open the visual studio as administrator.

Cheers,
Roi Kolbinger

01 September 2011

Date and Time in JavaScript

And this time I will present a snippet of code in javascript that shows the date and time.


You can put it wherever you like - in nearly every segment SharePoint Designer or in the Content Editor WebPart.

The JS code shows Date and Time

<!-- Clock --><script language="JavaScript">
var
clockID = 0;
function
UpdateClock() {
  
if(clockID) {
     
clearTimeout(clockID);
     
clockID  = 0;
  
}
  
var tDate = new Date();
  
var roiClock = window.document.getElementById("roiClock");
  
roiClock.innerHTML = ""
   
+ tDate.toLocaleDateString()
   
+ "&nbsp;&nbsp;&nbsp;&nbsp;"
    
+ tDate.getHoursTwoDigits() + ":"
    
+ tDate.getMinutesTwoDigits()
  
clockID = setTimeout("UpdateClock()", 6000);
}

function
StartClock()
{

  
clockID = setTimeout("UpdateClock()", 500);
}

function
KillClock()
{

  
if(clockID) {
     
clearTimeout(clockID);
     
clockID  = 0;
  
}
}
StartClock();

// return Minutes with two digits (chars)

Date.prototype.getMinutesTwoDigits = function()
{
    
var retval = this.getMinutes();
    
if (retval < 10)
    
{
 
         return ("0" + retval.toString());
     
}
     else     {
        
return retval.toString();    
    
}
}

// return Hours with two digits (chars)

Date.prototype.getHoursTwoDigits = function()
{
     
var retval = this.getHours();
     
if (retval < 10)
     
{
         return ("0" + retval.toString());
     
}
     
else    
     
{
        
return retval.toString();
     
}
}

</
script>
<
div id="roiClock" style="color:#888;font-size:13pt;font-weight:bold;width:300px;" />
<!--- End Clock -->

Some code taken from this - http://www.htmlfreecodes.com/
Roi

26 August 2011

Override the render function of the SharePoint content editor WebPart

Had you come across on Bug of the SharePoint Content Editor WebPart
So there is interesting problem
If using external links and internal links – you will get the bug
An example to the bug:
Try This - Internal links, external links and internal links again

What we get is the first two links work correctly, but the third link will link us to link the internal server name we have created the site. This is big bug for CEWP.
Hope you understood the bug.

How do we solve it? You can not inherit the WebPart - then shall we do?
Built Control Adapter performs render the code.
Create a small project in Visual Studio that contains the following code

using System;
using
 System.Collections.Generic;
using
 System.IO;
using
 System.Text;
using
 System.Web.UI;
using
 Microsoft.SharePoint;
using
 Microsoft.SharePoint.Administration;
namespace
 Roi.Moss.ControlAdapter.ContentEditorWebPart
{
  public class ContentEditorWebPartAdapter : System.Web.UI.Adapters.ControlAdapter
  {
    ///
 &amp;lt;summary&amp;gt;
    ///
 Override the render function off the CEWP
    ///
 &amp;lt;/summary&amp;gt;
    ///
 &amp;lt;param name="writer"&amp;gt;HtmlTextWriter write&amp;lt;/param&amp;gt;
    protected
 override void Render(HtmlTextWriter writer)
    {
      //Create a new stringbuilder

      StringBuilder
 sb = new StringBuilder();
      //create a HtmlTextWriter

      HtmlTextWriter
 htw = new HtmlTextWriter(new StringWriter(sb));
      //Preform the base Render Method

      base
.Render(htw);
      //Get the output string

      string
 output = sb.ToString();
      //Create a list with the alternate access urls

      List
&amp;lt;Uri&amp;gt; alternateUrls = GetCurrentAlternateAccessMappingsUrls();
      //Read out the list with alternate access urls

      foreach
 (Uri alternateUrl in alternateUrls)
      {
        //Replace the url's with /

        output = output.Replace(alternateUrl.ToString(), "/");
      }
      //write the output to the page

      writer.Write(output);
    }
  }
}

The function GetCurrentAlternateAccessMappingsUrls has been showed last month.
Now pass the code to the GAC. On the folder of IIS which at App_Browsers folder.
For example C: \ Inetpub \ wwwroot \ wss \ VirtualDirectories \ 80 \ App_Browsers
Now you need to add the following code in a file compat.browser
<browsers>
  ...
  <
browser refID="Default">
    <
controlAdapters>      <adapter controlType="Microsoft.SharePoint.WebPartPages.ContentEditorWebPart"                 adapterType="Roi.Moss.ControlAdapter.ContentEditorWebPart.ContentEditorWebPartAdapter, Roi.Moss.ControlAdapter.ContentEditorWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3f86d098a47bbaa6" /&amp;gt;
    </
controlAdapters>
  </
browser>

  ...
</
browsers>

Hope I helped
Roi