Search Results

Search found 7 results on 1 pages for 'norgean'.

Page 1/1 | 1 

  • Creating SharePoint sites from xml using Powershell

    - by Norgean
    It is frequently useful to create / delete web applications in a development environment. If you need to create a structure, this can quickly become tedious. Enter Powershell, xml and recursive functions. Create the structure in xml. Something like: <Sites>     <Site Name="Test 1" Url="Test1" />     <Site Name="Test 2" Url="Test2" >         <Site Name="Test 2 1" Url="Test21" >             <Site Name="Test 2 1 1" Url="Test211" />             <Site Name="Test 2 1 2" Url="Test212" />         </Site>     </Site>     <Site Name="Test 3" Url="Test3" >         <Site Name="Test 3 1" Url="Test31" />         <Site Name="Test 3 2" Url="Test32" />         <Site Name="Test 3 3" Url="Test33" >             <Site Name="Test 3 3 1" Url="Test331" />             <Site Name="Test 3 3 2" Url="Test332" />         </Site>         <Site Name="Test 3 4" Url="Test34" />     </Site> </Sites> Read this structure in Powershell, and recursively create the sites. Oh, and have cool progress dialogs, too. $snap = Get-PSSnapin | Where-Object { $_.Name -eq "Microsoft.SharePoint.Powershell" } if ($snap -eq $null) {     Add-PSSnapin "Microsoft.SharePoint.Powershell" } function CreateSites($baseUrl, $sites, [int]$progressid) {     $sitecount = $sites.ChildNodes.Count     $counter = 0     foreach ($site in $sites.Site)     {         Write-Progress -ID $progressid -Activity "Creating sites" -status "Creating $($site.Name)" -percentComplete ($counter / $sitecount*100)         $counter = $counter + 1         Write-Host "Creating $($site.Name) $($baseUrl)/$($site.Url)"         New-SPWeb -Url "$($baseUrl)/$($site.Url)" -AddToQuickLaunch:$false -AddToTopNav:$false -Confirm:$false -Name "$($site.Name)" -Template "STS#0" -UseParentTopNav:$true         if ($site.ChildNodes.Count -gt 0)         {             CreateSites "$($baseUrl)/$($site.Url)" $site ($progressid +1)         }         Write-Progress -ID $progressid -Activity "Creating sites" -status "Creating $($site.Name)" -Completed     } } # read an xml file $xml = [xml](Get-Content "C:\Projects\Powershell\sites.xml") $xml.PreserveWhitespace = $false CreateSites "http://$($env:computername)" $xml.Sites 1 Easy! Sensible real life implementations will also include templateid in the xml, will check for existence of a site before creating it, etc.

    Read the article

  • Running Powershell from within SharePoint

    - by Norgean
    Just because something is a daft idea, doesn't mean it can't be done. We sometimes need to do some housekeeping - like delete old files or list items or… yes, well, whatever you use Powershell for in a SharePoint world. Or it could be that your solution has "issues" for which you have Powershell solutions, but not the budget to transform into proper bug fixes. So you create a "how to" for the ITPro guys. Idea: What if we keep the scripts in a list, and have SharePoint execute the scripts on demand? An announcements list (because of the multiline body field). Warning! Let us be clear. This list needs to be locked down; if somebody creates a malicious script and you run it, I cannot help you. First; we need to figure out how to start Powershell scripts from C#. Hit teh interwebs and the Googlie, and you may find jpmik's post: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C. (Or MS' official answer at http://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx) public string RunPowershell(string powershellText, SPWeb web, string param1, string param2) { // Powershell ~= RunspaceFactory - i.e. Create a powershell context var runspace = RunspaceFactory.CreateRunspace(); var resultString = new StringBuilder(); try { // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work) PSSnapInException snapInError; runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError); runspace.Open(); // set a web variable. runspace.SessionStateProxy.SetVariable("webContext", web); // and some user defined parameters runspace.SessionStateProxy.SetVariable("param1", param1); runspace.SessionStateProxy.SetVariable("param2", param2); var pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(powershellText); // add a "return" variable pipeline.Commands.Add("Out-String"); // execute! var results = pipeline.Invoke(); // convert the script result into a single string foreach (PSObject obj in results) { resultString.AppendLine(obj.ToString()); } } finally { // close the runspace runspace.Close(); } // consider logging the result. Or something. return resultString.ToString(); } Ok. We've written some code. Let us test it. var runner = new PowershellRunner(); runner.RunPowershellScript(@" $web = Get-SPWeb 'http://server/web' # or $webContext $web.Title = $param1 $web.Update() $web.Dispose() ", null, "New title", "not used"); Next step: Connect the code to the list, or more specifically, have the code execute on one (or several) list items. As there are more options than readers, I'll leave this as an exercise for the reader. Some alternatives: Create a ribbon button that calls RunPowershell with the body of the selected itemsAdd a layout pageSpecify list item from query string (possibly coupled with content editor webpart with html that links directly to this page with querystring)WebpartListing with an "execute" columnList with multiselect and an execute button Etc!Now that you have the code for executing powershell scripts, you can easily expand this into a timer job, which executes scripts at regular intervals. But if the previous solution was dangerous, this is even worse - the scripts will usually be run with one of the admin accounts, and can do pretty much anything...One more thing... Note that as this is running "consoleless" calls to Write-Host will fail. Two solutions; remove all output, or check if the script is run in a console-window or not.  if ($host.Name -eq "ConsoleHost") { Write-Host 'If I agreed with you we'd both be wrong' }

    Read the article

  • Html 5 clock, part ii - CSS marker classes and getElementsByClassName

    - by Norgean
    The clock I made in part i displays the time in "long" - "It's a quarter to ten" (but in Norwegian). To save space, some letters are shared, "sevenineight" is four letters shorter than "seven nine eight". We only want to highlight the "correct" parts of this, for example "sevenineight". When I started programming the clock, each letter had its own unique ID, and my script would "get" each element individually, and highlight / hide each element according to some obscure logic. I quickly realized, despite being in a post surgery haze, …this is a stupid way to do it. And, to paraphrase NPH, if you find yourself doing something stupid, stop, and be awesome instead. We want an easy way to get all the items we want to highlight. Perhaps we can use the new getElementsByClassName function? Try to mark each element with a classname or two. So in "sevenineight": 's' is marked as 'h7', and the first 'n' is marked with both 'h7' and 'h9' (h for hour). <div class='h7 h9'>N</div><div class='h9'>I</div> getElementsByClassName('h9') will return the four letters of "nine". Notice that these classes are not backed by any CSS, they only appear directly in html (and are used in javascript). I have not seen classes used this way elsewhere, and have chosen to call them "marker classes" - similar to marker interfaces - until somebody comes up with a better name.

    Read the article

  • SharePoint logging to a list

    - by Norgean
    I recently worked in an environment with several servers. Locating the correct SharePoint log file for error messages, or development trace calls, is cumbersome. And once the solution hit the cloud, it got even worse, as we had no access to the log files at all. Obviously we are not the only ones with this problem, and the current trend seems to be to log to a list. This had become an off-hour project, so rather than do the sensible thing and find a ready-made solution, I decided to do it the hard way. So! Fire up Visual Studio, create yet another empty SharePoint solution, and start to think of some requirements. Easy on/offI want to be able to turn list-logging on and off.Easy loggingFor me, this means being able to use string.Format.Easy filteringLet's have the possibility to add some filtering columns; category and severity, where severity can be "verbose", "warning" or "error". Easy on/off Well, that's easy. Create a new web feature. Add an event receiver, and create the list on activation of the feature. Tear the list down on de-activation. I chose not to create a new content type; I did not feel that it would give me anything extra. I based the list on the generic list - I think a better choice would have been the announcement type. Approximately: public void CreateLog(SPWeb web)         {             var list = web.Lists.TryGetList(LogListName);             if (list == null)             {                 var listGuid = web.Lists.Add(LogListName, "Logging for the masses", SPListTemplateType.GenericList);                 list = web.Lists[listGuid];                 list.Title = LogListTitle;                 list.Update();                 list.Fields.Add(Category, SPFieldType.Text, false);                 var stringColl = new StringCollection();                 stringColl.AddRange(new[]{Error, Information, Verbose});                 list.Fields.Add(Severity, SPFieldType.Choice, true, false, stringColl);                 ModifyDefaultView(list);             }         }Should be self explanatory, but: only create the list if it does not already exist (d'oh). Best practice: create it with a Url-friendly name, and, if necessary, give it a better title. ...because otherwise you'll have to look for a list with a name like "Simple_x0020_Log". I've added a couple of fields; a field for category, and a 'severity'. Both to make it easier to find relevant log messages. Notice that I don't have to call list.Update() after adding the fields - this would cause a nasty error (something along the lines of "List locked by another user"). The function for deleting the log is exactly as onerous as you'd expect:         public void DeleteLog(SPWeb web)         {             var list = web.Lists.TryGetList(LogListTitle);             if (list != null)             {                 list.Delete();             }         } So! "All" that remains is to log. Also known as adding items to a list. Lots of different methods with different signatures end up calling the same function. For example, LogVerbose(web, message) calls LogVerbose(web, null, message) which again calls another method which calls: private static void Log(SPWeb web, string category, string severity, string textformat, params object[] texts)         {             if (web != null)             {                 var list = web.Lists.TryGetList(LogListTitle);                 if (list != null)                 {                     var item = list.AddItem(); // NOTE! NOT list.Items.Add… just don't, mkay?                     var text = string.Format(textformat, texts);                     if (text.Length > 255) // because the title field only holds so many chars. Sigh.                         text = text.Substring(0, 254);                     item[SPBuiltInFieldId.Title] = text;                     item[Degree] = severity;                     item[Category] = category;                     item.Update();                 }             } // omitted: Also log to SharePoint log.         } By adding a params parameter I can call it as if I was doing a Console.WriteLine: LogVerbose(web, "demo", "{0} {1}{2}", "hello", "world", '!'); Ok, that was a silly example, a better one might be: LogError(web, LogCategory, "Exception caught when updating {0}. exception: {1}", listItem.Title, ex); For performance reasons I use list.AddItem rather than list.Items.Add. For completeness' sake, let us include the "ModifyDefaultView" function that I deliberately skipped earlier.         private void ModifyDefaultView(SPList list)         {             // Add fields to default view             var defaultView = list.DefaultView;             var exists = defaultView.ViewFields.Cast<string>().Any(field => String.CompareOrdinal(field, Severity) == 0);               if (!exists)             {                 var field = list.Fields.GetFieldByInternalName(Severity);                 if (field != null)                     defaultView.ViewFields.Add(field);                 field = list.Fields.GetFieldByInternalName(Category);                 if (field != null)                     defaultView.ViewFields.Add(field);                 defaultView.Update();                   var sortDoc = new XmlDocument();                 sortDoc.LoadXml(string.Format("<Query>{0}</Query>", defaultView.Query));                 var orderBy = (XmlElement) sortDoc.SelectSingleNode("//OrderBy");                 if (orderBy != null && sortDoc.DocumentElement != null)                     sortDoc.DocumentElement.RemoveChild(orderBy);                 orderBy = sortDoc.CreateElement("OrderBy");                 sortDoc.DocumentElement.AppendChild(orderBy);                 field = list.Fields[SPBuiltInFieldId.Modified];                 var fieldRef = sortDoc.CreateElement("FieldRef");                 fieldRef.SetAttribute("Name", field.InternalName);                 fieldRef.SetAttribute("Ascending", "FALSE");                 orderBy.AppendChild(fieldRef);                   fieldRef = sortDoc.CreateElement("FieldRef");                 field = list.Fields[SPBuiltInFieldId.ID];                 fieldRef.SetAttribute("Name", field.InternalName);                 fieldRef.SetAttribute("Ascending", "FALSE");                 orderBy.AppendChild(fieldRef);                 defaultView.Query = sortDoc.DocumentElement.InnerXml;                 //defaultView.Query = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE' /><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>";                 defaultView.Update();             }         } First two lines are easy - see if the default view includes the "Severity" column. If it does - quit; our job here is done.Adding "severity" and "Category" to the view is not exactly rocket science. But then? Then we build the sort order query. Through XML. The lines are numerous, but boring. All to achieve the CAML query which is commented out. The major benefit of using the dom to build XML, is that you may get compile time errors for spelling mistakes. I say 'may', because although the compiler will not let you forget to close a tag, it will cheerfully let you spell "Name" as "Naem". Whichever you prefer, at the end of the day the view will sort by modified date and ID, both descending. I added the ID as there may be several items with the same time stamp. So! Simple logging to a list, with sensible a view, and with normal functionality for creating your own filterings. I should probably have added some more views in code, ready filtered for "only errors", "errors and warnings" etc. And it would be nice to block verbose logging completely, but I'm not happy with the alternatives. (yetanotherfeature or an admin page seem like overkill - perhaps just removing it as one of the choices, and not log if it isn't there?) Before you comment - yes, try-catches have been removed for clarity. There is nothing worse than having a logging function that breaks your site!

    Read the article

  • List item stuck in "Pending"

    - by Norgean
    Problem simplified: On approval, you have an event receiver that changes a field according to some weird and wonderful business logic. But the item remains in "Pending" state. Why?   First, you obviously need to turn off the event handling when you change things in the event receiver. If not, the event receiver will be called because the item changed. Infinite recursion is a bad thing. But you guessed that.   But that's not what was wrong. The culprit in my case was that items are set to require a new approval whenever the item is changed. This is good, but not what we want in this particular case. So force it back to approved after the other column has been changed.

    Read the article

  • Powershell progress dialogs

    - by Norgean
    Creating nested progress dialogs in Powershell is easy. Let the code speak for itself: for ($i = 1; $i -le 2; $i++) {     Write-Progress -ID 1 -Activity "Outer loop" -Status "Tick $i" -percentComplete ($i / 2*100)     for ($j = 1; $j -le 3; $j++)     {         Write-Progress -ID 2 -Activity "Mid loop" -Status "Tick $j" -percentComplete ($j / 3*100)         for ($k = 1; $k -le 3; $k++)         {             Write-Progress -ID 3 -Activity "Inner loop" -Status "Tick $k" -percentComplete ($k / 3*100)             Sleep(1)         }     } } I.e. some text that explains what we're doing (Activity and Status), and ID numbers. Easy.

    Read the article

  • Html 5 &ndash; new size units

    - by Norgean
    There are some new size units with CSS 3, which allows you to resize elements relative to the viewport size. They are vw, vh, vmin (that’s vm in IE), and perhaps vmax. (Viewport width, height, smaller of the two, larger of the two.) 8vw is 8% of the viewport width – or 205 pixels on my 2560 screen. I created a tiny demo clock which sizes the elements so that it uses the whole screen. Clock – in Norwegian, but it’s the source that is interesting… Bug: Resize does not work. Tested for IE 9 & 10 and Chrome. Firefox and Safari: does not work.

    Read the article

1