Wednesday, May 27, 2015

EPiServer 7.5 - EPiServer.UI.Admin.SiteMgmt Missing

In EPiServer 7.5, the namespace EPiServer.UI.Admin.SiteMgmt has been removed and site & host management now being implemented with SiteDefinitionRepository and SiteDefinition.Current

Example Code:

In EPiServer < 7.1


Get sites

 var sites = SiteInformationHandler.GetSitesInformation(true);  

Get Host:

 var hosts = SiteInformationHandler.GetSiteInformation(this.SiteID, true);  

In EPiServer > 7.5

Get sites

 var siteDefinitionRepository = ServiceLocator.Current.GetInstance<SiteDefinitionRepository>();  
 var sites = siteDefinitionRepository.List().ToList();  

Get Host:

 var hosts = SiteDefinition.Current;  

Saturday, May 23, 2015

EPiServer - Various ways of getting Current Page



In EPiServer CMS7 < X


 var repository = ServiceLocator.Current.GetInstance<IContentRepository>();  

// We must have a content REF.

 var contentReference = new ContentReference(5);  

// Get  page (or block)

 return repository.Get<TheContentType>(contentReference);  

And if you want to load it as a given type but do not want an exception to be thrown in case type is not correct you could load it as:
 TextPage page = Locate.ContentRepository().Get<IContent>(pageLink) as TheContentType;  

// With a pagetype called Startpage we could get it like this:

 var startPage = repository.Get<StartPage>(PageReference.StartPage);  

https://world.episerver.com/blogs/Johan-Bjornfot/Dates1/2015/2/changes-regarding-language-handling-during-content-loading-in-cms8/

DataFactory in EPiServer 7

In Episerver 5,6  DataFactory was used quite extensively now with ASP.NET MVC unit testing becomes a lot more feasible in practice, and so making your code testable makes more sense.

So, although DataFactory is still available in EPiServer 7 just as it was in EPiServer 6 and earlier versions, the preferred approach nowadays is to make use of the dependency resolver ServiceLocator class to get an instance of IContentRepository.

DataFactory in fact implements the IContentRepository interface, so you will likely be using it implicitly quite a lot regardless.

Good link to read: http://world.episerver.com/Blogs/Johan-Bjornfot/Dates1/2012/8/EPiServer7-Working-with-IContentRepositoryDataFactory/

EPiServer - Check Composer Property Safe



God way of fetching this Epi-Property from Composer without null exception. Because it will always be null before it's created manually.

 public string SetLinkToTab
     {  
       get  
       {  // only tests the 2nd side if the 1st side is true.  
         if (ContentFunctionData.Property["LinkInTab"] != null && 
             ContentFunctionData.Property["LinkInTab"].ToString() == "True")  
         {  
             return "target=\"_blank\"";  
         }  
         return string.Empty;  
       }  

Friday, May 22, 2015

C# - Logical, And, Or, IS, AS Easy Explanation

Bit wise AND: &

& - tests both sides every time.

Bit wise OR: |

| - test both sides every time.

The & and | above are bit wise operators they can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators (see below) will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).
XYX && Y
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse
XYX || Y
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse
X!X
truefalse
falsetrue
Short-Circuiting
When evaluating an expression involving && or || operators, C# uses a practice called short-circuiting. This means that C# will try to do as little work as possible when evaluating a boolean expression. The code "short-circuits" differently depending on the operator being used.
For example, consider this expression:
x || y || z
If x is true, then C# won't even consider the values of y or z, because when using || only one of the values must be true in order for the entire expression to evaluate to true. Look at the truth table for || to see this fact.
Likewise, when using &&:
x && y && z
If x is false, then C# won't look at the values of y or z, because when using && only one of the values must be false in order for the entire expression to evaluate to false. Look at the truth table for && to see this fact.
This is especially important to understand when the conditional expression contains more complex code. Consider this example:
x || SomeMethodThatReturnsABoolean()
If x is true, then the method will not be run. If x is false, then C# will continue evaluating the expression looking for the first operand that evaluates to true, and the method will be run as part of that evaluation.
In general it's best practice to keep conditional expressions as simple as possible. There are a few examples of times when short-circuiting can be very helpful. Consider the following example where I only want to do something if the names array contains at least one item.
if(names != null && names.Length > 0)
{
    // Do something with names
}
Without short-circuiting, accessing the Length property of the names array would throw an exception if names wasnull. But with short-circuiting, names.Length will never get run if names is null so it's safe to put both these expressions together. Just remember that order is important. Boolean expressions are evaluated from left to right, with respect to parenthesis of course.

 The Is Cast operator:

A casting operator.
Is will return true if the left side object can be CAST to the right. Otherwise false...
 if(q is rectangle){ then...}  


 The AS Cast operator:

The "As" operator: retuns null if it fails casting: 
 rectangleObject rekt = someobject as rectangleObject 
// invalid cast, returns null otherwise it will cast.  

EpiServer - Save XForm File To VPP Example

     private string CreateWebRootFile(XFormControl form, HttpPostedFile _postedFile, string formName, string oldFiles)  
     {  
       var _uploadedFileName = _postedFile.FileName;  
       var dir = CreatePathToSaveIn("PATH GOES HERE");  
       if (dir != null)  
       {  
         var fileName = Path.GetFileName(_uploadedFileName);  
         var _file = form.Page.Request.Files[formName + "FileUpload"];  
         if (_file != null)  
         {  
           _file.SaveAs(dir + fileName);  
         }  
         _uploadedFileName = "Somepath here";  
         if (oldFiles != String.Empty)  
         {  
           oldFiles += "|";  
         }  
         oldFiles += _uploadedFileName;  
       }  
       return oldFiles;  
     }  
     private UnifiedDirectory CreatePathToSaveIn(string path)  
     {  
       var dir = HostingEnvironment.VirtualPathProvider.GetDirectory(path) as UnifiedDirectory;  
       if (dir == null)  
       {  
         var tmpPath = "/";  
         foreach (var part in path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))  
         {  
           tmpPath += part + "/";  
           var tmp = HostingEnvironment.VirtualPathProvider.GetDirectory(tmpPath) as UnifiedDirectory;  
           if (tmp != null)  
             dir = tmp;  
           else if (dir != null)  
           {  
             dir.BypassAccessCheck = true;  
             dir = dir.CreateSubdirectory(part);  
           }  
         }  
      }  
       return dir;  

Thursday, May 21, 2015

C# - Filter for Dangerous File types Example

  private bool ContainsDangerousFileType(string fileName)  
     {  
       #region Explanation of Filetypes  
       //.EXE (machine language)  
       //.COM (machine language)  
       //.VB  (Visual Basic script)  
       //.VBS (Visual Basic script)  
       //.VBE (Visual Basic script-encoded)  
       //.CMD (batch file - Windows)  
       //.BAT (batch file - DOS/Windows)  
       //.WS  (Windows script)  
       //.WSF (Windows script)  
       //.SCR (screen saver)  
       //.SHS (OLE object package)  
       //.PIF (shortcut to DOS file plus code)  
       //.HTA (hypertext application)  
       //.JS  (JavaScript script)  
       //.JSE (JScript script)  
       //.LNK (shortcut to an executable)  
       #endregion  
       string extension = Path.GetExtension(fileName); 

       //No extension  == no uploading ;)
       if (extension == null)  
       {  
         return true;  
       }  
       List<String> _forbiddenFileTypes = new List<string>  
       {  
         ".EXE",".COM",".VB",".VBS",".VBE",".CMD",  
         ".BAT",".WS",".WSF",".SCR",".SHS",".PIF",  
         ".HTA",".JS",".JSE",".LNK",  
       };  
        
       Boolean hasForbiddenFile = _forbiddenFileTypes.Any(type => type == extension.Trim().ToUpper());  
      
      return hasForbiddenFile; 
     }      

EPiServer - Convert LinkItemCollection to list of Links

    /// <summary>  
     /// Converts a LinkItemCollection to a list of hyper links.  
     /// </summary>  
     /// <param name="linkItemCollection">Link items to be converted.</param>  
     /// <returns>List of hyper links; or an empty one if collection is null or empty.</returns>  
     public static List<HyperLink> ToHyperLinks(LinkItemCollection linkItemCollection)  
     {  
       if (linkItemCollection == null || linkItemCollection.Count <= 0)  
       {  
         return new List<HyperLink>();  
       }  
       List<HyperLink> links = new List<HyperLink>();  
       foreach (LinkItem linkItem in linkItemCollection)  
       {  
         if (linkItem == null || string.IsNullOrEmpty(linkItem.Text) || string.IsNullOrEmpty(linkItem.Href))  
         {  
           continue;  
         }  
         HyperLink link = new HyperLink();  
         link.Text = linkItem.Text;  
         link.NavigateUrl = linkItem.Href;  
         link.ToolTip = linkItem.Title;  
         link.Target = linkItem.Target;  
         links.Add(link);  
       }  
       return links;  
     }  

C# - The ?? och ? operator

Null-coalescing operator - ??

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand. An example of this:

 int value = (int)(CurrentPage["MyDynamicPropety"] ?? 0);  

And another:

 CurrentPage["CardImage"] != null ? CurrentPage["CardImage"].ToString() : String.Empty;  

See: http://msdn.microsoft.com/en-us/library/ms173224.aspx

Conditional operator - ?


TRUE FALSE Condition ? First_expression : second_expression;

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
Following is the syntax for the conditional operator. The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, second_expression is evaluated and becomes the result.
Only one of the two expressions is evaluated. Another example of this:

 h1Ctrl.InnerText = IsValue("Heading")  
                     ? CurrentPage.Property["Heading"].Value.ToString()  
                     : CurrentPage.PageName;  

C#, EpiServer - Various Lazy Loading Examples

  private PageData _gigPage;  
     protected PageData GigPage  
     {  
       get  
       {  
         if( _gigPage == null )  
         {  
           PageReference gigPageRef = CurrentPage.GigPageLink;  
           if( !PageReference.IsNullOrEmpty(gigPageRef) )  
           {  
             PageData gigPage = DataFactory.Instance.GetPage(gigPageRef);  
             _gigPage = gigPage;  
           }  
         }  
         return _gigPage;  
       }  
     }  

Fetch a simple Property with Lazy loading

 protected string PageHeading  
     {  
       get { return _heading ?? (_heading = CurrentPage.Heading); }  
       set { _heading = value; }  
     }  

Fetch a Settingspage Lazy with cache timeout (not recommended since EPiServer handles this better)

 public static class SiteHelper  
   {  
     private static SettingsPage _settingsPage;  
     private static DateTime _fetchTime;  
     public static SettingsPage GetSettingsPage()  
     {  
       const string errorMsg = "Error retrieving settingspage, contact site administrator";  
       try  
       {  
         if (_settingsPage != null && !TimeHasElapsed(5))  
         {  
           return _settingsPage;  
         }  
         StartPage startPage = DataFactory.Instance.GetPage(ContentReference.StartPage) as StartPage;  
         if (startPage != null && startPage.SettingsPage != null)  
         {  
           var page = DataFactory.Instance.GetPage(startPage.SettingsPage);  
           if (page is SettingsPage)  
           {  
             _settingsPage = page as SettingsPage;  
             _fetchTime = DateTime.UtcNow;  
           }  
         }  
         return _settingsPage;  
       }  
       catch (Exception e)  
       {  
         throw new Exception(errorMsg + ": " + e);  
       }  
     }  
     private static bool TimeHasElapsed(int timespan)  
     {  
       if (_fetchTime.AddMinutes(timespan) > DateTime.UtcNow)  
       {  
         return false;  
       }  
       return true;  
     }  
   }   

EpiServer - Get Typed PageData Object In Repeater



In the view we have for example:

 <h3><%# Container.GetDataItem<CallPage>().Heading %></h3>  

Then just Create a Extension method to get the correct type above something like this:


 public static T GetDataItem<T>(this RepeaterItem container)  
 {  
      If Satsen vet jag inte om den fungerar.  
      if (container.GetType().IsAssignableFrom(typeof (T)))  
      {  
       //Some Error handling?  
      }  
       return (T)container.DataItem;  
 }  

Visual Studio - See Return value from Immediate Window

Just type:
$ReturnValue

CSS - Understand some basics in CSS Syntax


Example
We have to classes myClass and anotherClass.
In css: ,   means OR.
and blankspace means: AND but only nested.
No blankspace between the class selectors mean: look for a element that has both classes.
and . means now am expecting a class.

So to select to different classes we can use OR like this:

or, and css example
Please note the difference in CSS : .myClass .anotherClass and myClass.anotherClass

Another reminder:

in the following css statement only the two colors are totally separated when the CSS compilation try to apply them: This is all done with the: ,

.myClass p, .anotherClass div {...}

 #Inherit 

Inherits its parents value, so if a p element has a color red. Then if a a element has tagged to inherit color then this will apply for a element as-well.
Example:

p{
   color:red;
}
p a {
  color: inherit;
}

#Initial

Inherits the value the element should have if no styling for it was declared.
Of course IE crap wont support this.
Firefox might need -moz-initial;


#Border

Some border quick syntax:
border-left: solid #aaa 1px;

#Padding

padding: 20px (this will apply to all sides);

padding: 5px 10px 15px 20px;
Explanation above statement:
5px : represents TOP
10px: represents RIGHT
15px represents BOTTOM
20px and you guest it represents LEFT.

#Custom Fonts

You can download the font of your preference, let’s say cool_font.ttf, and upload it to your remote server where your blog or website is hosted.
@font-face {
font-family: cool_font;
src: url('cool_font.ttf');
}
After that you can use it just like a normal CSS declaration:
p.custom_font{
font-family: cool_font; /* no .ttf */
}
To make your @font-face declaration works with IE as well, you must prepare two font files, one in TTF / OTF format and the other one in EOT format.

@font-face
{
    font-family: my_font;
    src: url('my_font.eot');
    src: local(my_font), url('my_font.ttf') format('opentype');
}

#Center

Center Block elements:
table{width:50%;margin:auto;}

Inline Elements:
for inline elements e.g:

div{text-align:center}


CSS - Make Bullets a part of Li Element instead of UL

To avoid this problem just change style to inside.

Example:
ul {
    list-style-position: inside;
}




CSS/JQuery - Common Useful Selectors


 “Begins with” Selector – [att^="val"]  
 “Ends with" Selector – [att$="val"]  
 “Contains" Selector – [att*="val"]  
 For example if we wanna find all elements with http:// 
then $('a[href^="http://"]') in jQuery will do the job.

nth-child och nth-last-child.
Means i guess n = random integer and th is some crappy language extension.

CSS Example Reminder: 
$('li:nth-last-child(-n+3)')


li:nth-child(an+b){ }
    a =  represents the number that will be looped, N=2 will loop every second selected element.
    b = Is the startingpoint element where we should begin with this pattern.
    n =  ?

}
Take only the first five in the list:
nth-child(-n+5)
Take only the last 3 in the list:
nth-last-child(-n+3)
jQuery:
 $('li:nth-last-child(-n+3)')

# Bryt text snyggt:
.text-overflow{
 
    white-space:nowrap;
    overflow:hidden;
    text-overflow: ellipsis;
}

Visual studio Fixa F7 toggle not working

The fix for now is to either change your profile or map F7(or another key) to the ToggleDesigner command.  Here is how you would do this:


  • Bring up customization dialog with "Tools\Customize "
  • Bring up the keystroke mapper with "Keyboard..."
  • Set focus in "Press Shortcut Keys" text box
  • Press F7 or some other keystroke you want
  • The "Shortcut currently used by" box will show the command currently invoked by the keystroke.
  • Set focus to "Show Commands Containing" and type ToggleDesigner
  • This will select the View.ToggleDesigner command in the list box of commands
  • Next press the "Assign" button to assign the keystroke shortcut to the command.
  • Click "OK" to the keystroke mapper dialog
  • Click "Close" to the customization dialog