+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / Permissions per Image Library

Permissions per Image Library

11 posts, 0 answered
  1. Daniel
    Daniel avatar
    10 posts
    Registered:
    08 Apr 2008
    02 Jul 2008
    Link to this post
    Hi there,
    I notice that it is not possible to set permissions on a per Image Library basis.  What we are trying to do is create multiple image libraries with each one only editable by users in a specific role.

    One option would be to override the provider for the image library (Telerik.Libraries.Data.DefaultProvider) and when used in the CMS admin side, only return those image libraries which match the role the user is in (by naming convention between the role and image library).

    Another option would be to hide items in the LibraryList-Libs.ascx template, for example:

            <radTS:PageView ID="boxesView" runat="server">
                <asp:Repeater ID="allLibraries" runat="server">
                    <HeaderTemplate>
                        <ul id="modulesItemsList" class="modulesItemsList">
                    </HeaderTemplate>
                    <ItemTemplate>
                        <li style="display:<%= MyStaticClass.IsImageLibraryEditableByUsersRole(Eval("Name")  %>;">

    Also, when do you expect this bility to be provided in Sitefinity.

    Thanks,
    Daniel
  2. Daniel
    Daniel avatar
    10 posts
    Registered:
    08 Apr 2008
    03 Jul 2008
    Link to this post
    Hi,
    Just been looking through the Telerik.Libraries.Data.DefaultProvider and I see that the GetLibraries methods are not overridable, so perhpas it might not be possible to filter out the ImageLibraries by making a new provider?

    The second option I listed does work but has the downside that if there are a lot of image libraries, then the paging can mean that some pages show no results in the list and you need to move to the Next Page in order to see some results.

    Thoughts?
    Cheers,
    Daniel
  3. Daniel
    Daniel avatar
    10 posts
    Registered:
    08 Apr 2008
    03 Jul 2008
    Link to this post
    Hi,

    I've created a new Library Provider based on the existing one, with the idea that I'll filter out Libraries in the GetLibraries methods, however, I'm seeing the following error when using this new provider. 

    The query Libraries has not been registered. Use DataConnection.Initialize or DataConnection.RegisterAssembly to register an assembly.


    The query Libraries has not been registered. Use DataConnection.Initialize or DataConnection.RegisterAssembly to register an assembly.   
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.   
     
    Exception Details: Nolics.ORMapper.Base.NolnetException: The query Libraries has not been registered. Use DataConnection.Initialize or DataConnection.RegisterAssembly to register an assembly.  
     
    Source Error:   
     
     
    Line 477:               return libraries;  
    Line 478:           }  
    Line 479:           libraries.Load(from + max, from);  
    Line 480:           return libraries;  
    Line 481:       }  
       
     
    Source File: C:\Projects\MyApp.ExternalWebsite\Main\Source\MyApp.Web.Process\LibraryProvider.cs    Line: 479   
     
    Stack Trace:   
     
     
    [NolnetException: The query Libraries has not been registered. Use DataConnection.Initialize or DataConnection.RegisterAssembly to register an assembly.]  
       Nolics.ORMapper.Base.OdbClassManager.GetQueryInfo(String queryName, Boolean fMustFind) +156  
       Nolics.ORMapper.DataProviders.SQLDataProvider.ExecQuery(DataSet queries) +165  
       Nolics.ORMapper.Base.QueryBase`1.LoadQuery(Int32 maxElements, Int32 fromElement) +275  
       Nolics.ORMapper.Base.QueryBase`1.Load(Int32 maxElements, Int32 from) +8  
       MyApp.Web.Process.LibraryProvider.GetAllLibraries(Int32 from, Int32 max, Int32& count, String sortExp) in C:\Projects\MyApp.ExternalWebsite\Main\Source\MyApp.Web.Process\LibraryProvider.cs:479  
       Telerik.Libraries.LibraryManager.GetAllLibraries(Int32 from, Int32 max, String sortExp) +23  
     
    [TargetInvocationException: Exception has been thrown by the target of an invocation.]  
       System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0  
       System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +72  
       System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +371  
       System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29  
       System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +480  
       System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1960  
       System.Web.UI.WebControls.Repeater.GetData() +50  
       System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +232  
       System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +53  
       System.Web.UI.WebControls.Repeater.DataBind() +72  
       Telerik.Libraries.WebControls.Admin.LibraryList.CreateLibrariesView() +2243  
       Telerik.Libraries.WebControls.Admin.LibraryList.CreateChildControls() +44  
       System.Web.UI.Control.EnsureChildControls() +87  
       System.Web.UI.Control.PreRenderRecursiveInternal() +50  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Control.PreRenderRecursiveInternal() +170  
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2041  
     
       
     

    I've also updated the web.config file to include the new provider:

    <providers> 
        <clear/> 
        ...  
        <add name="Libraries" urlRewriteFormat="~/{Provider}/{LibraryName}/[Name].sflb" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="True" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="MyApp.Web.Process.LibraryProvider, MyApp.Web.Process" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx"/>  
        ...  
    </providers> 
     

    Do you think this is going to work or would you recommend another solution?

    Thanks,
    Daniel
  4. Vassil Daskalov
    Vassil Daskalov avatar
    261 posts
    Registered:
    18 May 2013
    08 Jul 2008
    Link to this post
    Hello Daniel,

    I am sorry for the late response.

    Your approach for achieving permissions per library basis seems logical and pretty inventive. The reason why you get this error is due to the fact that you have not registered your assembly for the Nolics engine. I am not sure how you are implementing the provider but Nolics requires that you register your assemblies in order to prevent naming conflicts. That is why when you initialize your provider, you should call the DataConnection.Initialize(false, assembly); method by providing as a parameter the current executing assembly.

    Hope this helps.

    Regards,
    Vassil Daskalov
    the Telerik team

    Instantly find answers to your questions at the new Telerik Support Center
  5. Jason M
    Jason M avatar
    108 posts
    Registered:
    15 Jan 2007
    09 Jul 2008
    Link to this post
    Any success with this Daniel?  We're trying to do something similar with our protected documents.  We have 40+ members only sites (each is a role) and we'd like to ensure only users with the appropriate role can access the sites library.

    J
  6. Daniel Flippance
    Daniel Flippance avatar
    2 posts
    Registered:
    08 Jul 2008
    14 Jul 2008
    Link to this post
    Hi guys,

    I've successfully created a new LibraryProvider based on the existing one.  The code follows and is basically a reflected copy of Telerik.Libraries.Data.DefaultProvider, with two changes:

    1.  Add the code marked //Custom Code in the Initialize() method
    2.  Set the version number of your DLL to be the same as the LibrariesSchemaVersion, in ur case, this is 3.2.1616.2

    Basically, what happening is that the Nolics DataConnection reflects over all Types in the specified assemblies looking for entities and Queries.  In the case of the Telerik provider, the entities and queries are in the same DLL as the Provider, but in our case, they are in 2 different assemblies, so we need to call DataConnection.Initialize(...) twice.

    For our specific security needs, in order to hard code in the security that we need, we altered the code below to include lines like the following:

        //Don't do this:
        //return libraries


        //Do this instead
        return CustomPermissions.Filter(libraries)

    That code would then perform the custom filtering - in our case, removing Libraries with a certain naming convention matching one of the users Roles.

    Cheers and here's the code for the new Provider
    Daniel Flippance

    1 using System;  
    2 using System.Collections;  
    3 using System.Collections.Generic;  
    4 using System.Collections.Specialized;  
    5 using System.ComponentModel;  
    6 using System.Data;  
    7 using System.Drawing;  
    8 using System.Drawing.Imaging;  
    9 using System.IO;  
    10 using System.Linq;  
    11 using System.Reflection;  
    12 using System.Security;  
    13 using System.Security.Permissions;  
    14 using System.Text;  
    15 using System.Web.Hosting;  
    16  
    17 using Telerik;  
    18 using Telerik.Cms.Engine;  
    19 using Telerik.Cms.Engine.Configuration;  
    20 using Telerik.DataAccess;  
    21 using Telerik.Libraries;  
    22 using Telerik.Libraries.Data;  
    23 using Telerik.Libraries.Data.Resources;  
    24 using Nolics.ORMapper.Base;  
    25 using Nolics.ORMapper.DataProviders;  
    26  
    27 namespace MyApp.DataAccess  
    28 {  
    29     internal class Messages  
    30     {  
    31         public const string NotAllowedExtension="The item extension in not allowed for this library.";  
    32         public const string LibraryWithSameName="Library with the '{0}' name already exists.";  
    33         public const string LibraryMaxFilesCountReached="The '{0}' library can not have more than {1} files.";  
    34         public const string ItemBelongsToOtherProvider="This item belongs to a different provider.";  
    35         public const string NotBrowserImage="The image is not viewable via browser. Image gallery should only contain browser viewable images.";  
    36         public const string LibraryMaxSizeReached="The '{0}' library can not be bigger than {1} bytes.";  
    37         public const string ItemWithSameName="There is already item with '{0}' name in the '{1}' library.";  
    38         public const string MaxFilesSizeReached="The '{0}' library can not contain files bigger than {1} bytes.";  
    39         public const string NotSupportedType="The type {0} is not supported by this provider.";  
    40         public const string DefaultProviderDescription="Libraries Data Provider for Nolics";  
    41     }  
    42  
    43     public class LibraryProvider : Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Libraries.ILibraryProvider  
    44     {  
    45         public LibraryProvider()  
    46         {  
    47         }
    48
    49         #region Public methods  
    50         public override void Initialize(string name, NameValueCollection config)  
    51         {  
    52             lock (this)  
    53             {  
    54                 Assembly executingAssembly = Assembly.GetExecutingAssembly();  
    55                 DataConnection.Initialize(false, executingAssembly);  
    56  
    57                 //CUSTOM CODE  
    58                 //NOTE:  You must also set the Assembly Version to be the same as the database schema version - Get the number from the Telerik.Libraries.Data assembly  
    59                 Assembly sitefinityLibraryDataAssembly = Assembly.GetAssembly(typeof(Telerik.Libraries.Data.Library));  
    60                 DataConnection.Initialize(false, sitefinityLibraryDataAssembly);  
    61                 //END CUSTOM CODE  
    62       
    63                 base.Initialize(name, config);  
    64                 bool flag = false;  
    65                 try 
    66                 {  
    67                     string variable = this.GetVariable("LibrariesSchemaVersion"true);  
    68                     if (string.IsNullOrEmpty(variable) || (int.Parse(variable) != executingAssembly.GetName().Version.Build))  
    69                     {  
    70                         flag = true;  
    71                     }  
    72                 }  
    73                 catch 
    74                 {  
    75                     flag = true;  
    76                 }  
    77                 if (flag)  
    78                 {  
    79                     SecurityPermission perm = new SecurityPermission(PermissionState.Unrestricted);  
    80                     if (!SecurityManager.IsGranted(perm))  
    81                     {  
    82                         throw new ProviderDatabaseUpgradeException(this);  
    83                     }  
    84                     base.odbProvider.Upgrade();  
    85                     this.SetVariable("LibrariesSchemaVersion", executingAssembly.GetName().Version.Build.ToString(), true);  
    86                 }  
    87             }  
    88         }  
    89  
    90         public override void Export(DataSet dataSet)  
    91         {  
    92             DataTable table = new DataTable(this.GetExportedTableName("Libraries"));  
    93             dataSet.Tables.Add(table);  
    94             table.Columns.Add("ID"typeof(Guid));  
    95             table.Columns.Add("Name"typeof(string));  
    96             table.Columns.Add("MaxFiles"typeof(int));  
    97             table.Columns.Add("MaxSize"typeof(long));  
    98             table.Columns.Add("TypeName"typeof(string));  
    99             table.Columns.Add("LastModifiedDateEnabled"typeof(bool));  
    100             table.Columns.Add("ContentExpirationEnabled"typeof(bool));  
    101             table.Columns.Add("ExpirationValue"typeof(string));  
    102             table.Columns.Add("ExpirationOption"typeof(int));  
    103             foreach (Library library in this.GetAllLibraries())  
    104             {  
    105                 DataRow row = table.NewRow();  
    106                 row["ID"] = library.ID;  
    107                 row["Name"] = library.Name;  
    108                 row["MaxFiles"] = library.MaxFiles;  
    109                 row["MaxSize"] = library.MaxSize;  
    110                 row["TypeName"] = library.TypeName;  
    111                 if (library.LastModifiedDateEnabled.HasValue)  
    112                 {  
    113                     row["LastModifiedDateEnabled"] = library.LastModifiedDateEnabled.Value;  
    114                 }  
    115                 if (library.ContentExpirationEnabled.HasValue)  
    116                 {  
    117                     row["ContentExpirationEnabled"] = library.ContentExpirationEnabled.Value;  
    118                 }  
    119                 row["ExpirationValue"] = library.ExpirationValue;  
    120                 row["ExpirationOption"] = (int)library.ExpirationOption;  
    121                 table.Rows.Add(row);  
    122             }  
    123             base.Export(dataSet);  
    124         }  
    125  
    126         public override ICustomTypeDescriptor GetDescriptor(ICustomTypeDescriptor parent, IContent instance)  
    127         {  
    128             return new LibraryItemTypeDescriptor(parent, instance);  
    129         }  
    130  
    131         public override IDictionary<string, IMetaInfo> GetMetaKeys(IContent content)  
    132         {  
    133             Dictionary<string, IMetaInfo> dictionary = new Dictionary<string, IMetaInfo>();  
    134             ContentManager manager = new ContentManager(content.ProviderName);  
    135             LibraryManager manager2 = new LibraryManager(content.ProviderName);  
    136             ILibrary library = manager2.GetLibrary(content.ParentID);  
    137             string[] metaKeys = manager2.GetMetaKeys(library.TypeName);  
    138             foreach (string str in manager.MetaKeys.Keys)  
    139             {  
    140                 bool flag = false;  
    141                 foreach (string str2 in metaKeys)  
    142                 {  
    143                     if (str2 == str)  
    144                     {  
    145                         flag = true;  
    146                     }  
    147                 }  
    148                 if (flag)  
    149                 {  
    150                     dictionary.Add(str, manager.MetaKeys[str]);  
    151                 }  
    152             }  
    153             return dictionary;  
    154         }  
    155  
    156         public override string GetUrlMetaPart(string key, IContent item)  
    157         {  
    158             if (!HostingEnvironment.IsHosted)  
    159             {  
    160                 return base.GetUrlMetaPart(key, item);  
    161             }  
    162             object metaData = item.GetMetaData(key);  
    163             if (metaData == null)  
    164             {  
    165                 return string.Empty;  
    166             }  
    167             if (metaData is DateTime)  
    168             {  
    169                 DateTime time = (DateTime)metaData;  
    170                 return time.ToString(this.UrlDateTimeFormat);  
    171             }  
    172             return metaData.ToString().Trim();  
    173         }  
    174  
    175         public override string GetUrlPart(string key, IContent item)  
    176         {  
    177             string str;  
    178             if (((str = key) != null) && (str == "{LibraryName}"))  
    179             {  
    180                 return this.GetLibrary(item.ParentID).Name;  
    181             }  
    182             return base.GetUrlPart(key, item);  
    183         }  
    184  
    185         public override void Import(DataSet dataSet)  
    186         {  
    187             DataTable table = dataSet.Tables[this.GetExportedTableName("Libraries")];  
    188             if (table != null)  
    189             {  
    190                 foreach (DataRow row in table.Rows)  
    191                 {  
    192                     Library library = (Library)this.CreateLibrary();  
    193                     library.ID = (Guid)row["ID"];  
    194                     library.Name = (row["Name"] == DBNull.Value) ? string.Empty : ((string)row["Name"]);  
    195                     library.MaxFiles = (int)row["MaxFiles"];  
    196                     library.MaxSize = (long)row["MaxSize"];  
    197                     library.TypeName = (row["TypeName"] == DBNull.Value) ? string.Empty : ((string)row["TypeName"]);  
    198                     if (row["LastModifiedDateEnabled"] != DBNull.Value)  
    199                     {  
    200                         library.LastModifiedDateEnabled = new bool?((bool)row["LastModifiedDateEnabled"]);  
    201                     }  
    202                     if (row["ContentExpirationEnabled"] != DBNull.Value)  
    203                     {  
    204                         library.ContentExpirationEnabled = new bool?((bool)row["ContentExpirationEnabled"]);  
    205                     }  
    206                     library.ExpirationValue = (row["ExpirationValue"] == DBNull.Value) ? string.Empty : ((string)row["ExpirationValue"]);  
    207                     library.ExpirationOption = (ExpirationOptions)row["ExpirationOption"];  
    208                     this.SaveLibrary(library);  
    209                 }  
    210                 base.Import(dataSet);  
    211             }  
    212         }  
    213  
    214         public override BrowserCache RetrieveContentCache(IContent content)  
    215         {  
    216             if (content.ParentID != Guid.Empty)  
    217             {  
    218                 ILibrary library = this.GetLibrary(content.ParentID);  
    219                 return new BrowserCache(library.LastModifiedDateEnabled, library.Expiration);  
    220             }  
    221             return base.RetrieveContentCache(content);  
    222         }
    223         #endregion  
    224  
    225         #region Override Protected Methods  
    226         protected virtual int GetLibrariesCountOptimized()  
    227         {  
    228             int num;  
    229             SQLDataProvider odbProvider = base.odbProvider as SQLDataProvider;  
    230             Connection con = odbProvider.GetConnection();  
    231             try 
    232             {  
    233                 IDbCommand command = con.CreateCommand();  
    234                 StringBuilder builder = new StringBuilder();  
    235                 string str = "SELECT COUNT(*) FROM sf_Libraries T1";  
    236                 builder.Append(" WHERE T1.Application = '");  
    237                 builder.Append(this.Application);  
    238                 builder.Append("'");  
    239                 command.CommandText = str + builder.ToString();  
    240                 object obj2 = command.ExecuteScalar();  
    241                 command.Dispose();  
    242                 if (obj2 != null)  
    243                 {  
    244                     return Convert.ToInt32(obj2);  
    245                 }  
    246                 num = 0;  
    247             }  
    248             finally 
    249             {  
    250                 odbProvider.ReleaseConnection(con);  
    251             }  
    252             return num;  
    253         }  
    254  
    255         protected virtual int GetLibrariesCountSlow()  
    256         {  
    257             return this.GetAllLibraries().Count;  
    258         }  
    259  
    260         protected override void OnExecuted(ExecutedEventArgs args, bool fireEvents)  
    261         {  
    262             base.OnExecuted(args, fireEvents);  
    263         }  
    264  
    265         protected override void OnExecuting(ExecutingEventArgs args, bool fireEvents)  
    266         {  
    267             if (((args.CommandName != "DeleteContent") && (args.CommandArguments is IContent)) && (((IContent)args.CommandArguments).ParentID != Guid.Empty))  
    268             {  
    269                 IContent commandArguments = args.CommandArguments as IContent;  
    270                 ILibrary library = this.GetLibrary(commandArguments.ParentID);  
    271                 if (library != null)  
    272                 {  
    273                     long length = 0L;  
    274                     long num2 = 0L;  
    275                     object metaData = null;  
    276                     metaData = commandArguments.GetMetaData("Size");  
    277                     if ((metaData != null) && (metaData is long))  
    278                     {  
    279                         num2 = (long)metaData;  
    280                         if ((commandArguments.Content is byte[]) && (num2 != (commandArguments.Content as byte[]).Length))  
    281                         {  
    282                             commandArguments.SetMetaData("Size", (commandArguments.Content as byte[]).Length);  
    283                             length = (commandArguments.Content as byte[]).Length;  
    284                         }  
    285                         if ((library.MaxFileSize > 0L) && (num2 > library.MaxFileSize))  
    286                         {  
    287                             throw new ArgumentException(string.Format(Messages.MaxFilesSizeReached, library.Name, library.MaxFileSize));  
    288                         }  
    289                         if ((library.MaxSize > 0L) && ((num2 + library.Size) > library.MaxSize))  
    290                         {  
    291                             throw new ArgumentException(string.Format(Messages.LibraryMaxSizeReached, library.Name, library.MaxSize));  
    292                         }  
    293                     }  
    294                     if ((library.TypeName == "Image") && (commandArguments.Content is byte[]))  
    295                     {  
    296                         try 
    297                         {  
    298                             if ((length > 0L) && (length != num2))  
    299                             {  
    300                                 Image image = Image.FromStream(new MemoryStream(commandArguments.Content as byte[]));  
    301                                 if ((!(image.RawFormat.Guid == ImageFormat.Gif.Guid) && !(image.RawFormat.Guid == ImageFormat.Jpeg.Guid)) && !(image.RawFormat.Guid == ImageFormat.Png.Guid))  
    302                                 {  
    303                                     throw new ArgumentException(Messages.NotBrowserImage);  
    304                                 }  
    305                                 object obj3 = commandArguments.GetMetaData("Width");  
    306                                 if ((obj3 != null) && (Convert.ToInt64(obj3) != image.Width))  
    307                                 {  
    308                                     commandArguments.SetMetaData("Width", image.Width);  
    309                                 }  
    310                                 obj3 = commandArguments.GetMetaData("Height");  
    311                                 if ((obj3 != null) && (Convert.ToInt64(obj3) != image.Height))  
    312                                 {  
    313                                     commandArguments.SetMetaData("Height", image.Height);  
    314                                 }  
    315                             }  
    316                         }  
    317                         catch 
    318                         {  
    319                         }  
    320                     }  
    321                     IList items = library.GetItems();  
    322                     if ((!items.Contains(commandArguments) && (library.MaxFiles > 0)) && ((library.ItemsCount + 1) > library.MaxFiles))  
    323                     {  
    324                         throw new ArgumentException(string.Format(Messages.LibraryMaxFilesCountReached, library.Name, library.MaxFiles));  
    325                     }  
    326                     metaData = commandArguments.GetMetaData("Name");  
    327                     string str = string.Empty;  
    328                     if ((metaData != null) && (metaData is string))  
    329                     {  
    330                         str = metaData as string;  
    331                     }  
    332                     if (((IOdbClass)commandArguments).CurrentState != OdbObjectStates.New)  
    333                     {  
    334                         items.Remove(commandArguments);  
    335                     }  
    336                     foreach (IContent content2 in items)  
    337                     {  
    338                         object obj4 = content2.GetMetaData("Name");  
    339                         string str2 = string.Empty;  
    340                         if ((obj4 != null) && (obj4 is string))  
    341                         {  
    342                             str2 = obj4 as string;  
    343                         }  
    344                         if (!string.IsNullOrEmpty(str2) && (str2 == str))  
    345                         {  
    346                             throw new ArgumentException(string.Format(Messages.ItemWithSameName, str, library.Name));  
    347                         }  
    348                     }  
    349                     LibraryInfo info = new LibraryInfo(library);  
    350                     object obj5 = commandArguments.GetMetaData("Extension");  
    351                     if (obj5 != null)  
    352                     {  
    353                         string str3 = Convert.ToString(obj5);  
    354                         if (str3 != str3.ToLower())  
    355                         {  
    356                             commandArguments.SetMetaData("Extension", str3.ToLower());  
    357                             str3 = str3.ToLower();  
    358                         }  
    359                         if (!info.Extensions.Contains(".*") && !info.Extensions.Contains("*"))  
    360                         {  
    361                             bool flag = false;  
    362                             foreach (string str4 in LibraryHelper.ConvertExtensionsToArray(info.Extensions))  
    363                             {  
    364                                 if (str4.Equals(str3, StringComparison.OrdinalIgnoreCase))  
    365                                 {  
    366                                     flag = true;  
    367                                 }  
    368                             }  
    369                             if (!flag)  
    370                             {  
    371                                 throw new ArgumentException(string.Format(Messages.NotAllowedExtension, new object[0]));  
    372                             }  
    373                         }  
    374                     }  
    375                 }  
    376             }  
    377             base.OnExecuting(args, fireEvents);  
    378         }  
    379  
    380         protected virtual IMetaSearchInfo[] DocumentsFilter  
    381         {  
    382             get 
    383             {  
    384                 List<IMetaSearchInfo> list = new List<IMetaSearchInfo>(4);  
    385                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".jpg", SearchCondition.NotEqual, JoinType.And));  
    386                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".jpeg", SearchCondition.NotEqual, JoinType.And));  
    387                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".gif", SearchCondition.NotEqual, JoinType.And));  
    388                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".png", SearchCondition.NotEqual, JoinType.And));  
    389                 return list.ToArray();  
    390             }  
    391         }  
    392    
    393         protected virtual IMetaSearchInfo[] ImagesFilter  
    394         {  
    395             get 
    396             {  
    397                 List<IMetaSearchInfo> list = new List<IMetaSearchInfo>(4);  
    398                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".jpg", SearchCondition.Equal, JoinType.Or));  
    399                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".jpeg", SearchCondition.Equal, JoinType.Or));  
    400                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".gif", SearchCondition.Equal, JoinType.Or));  
    401                 list.Add(new MetaSearchInfo(MetaValueTypes.ShortText, "Extension"".png", SearchCondition.Equal, JoinType.Or));  
    402                 return list.ToArray();  
    403             }  
    404         }
    405
    406         #endregion  
    407  
    408         #region ILibraryProvider Members  
    409  
    410         public Telerik.Libraries.ILibrary CreateLibrary()  
    411         {  
    412             Library library = new Library();  
    413             library.Application = this.Application;  
    414             return library;  
    415         }  
    416  
    417         public void DeleteLibrary(Guid ID)  
    418         {  
    419             this.DeleteLibrary(this.GetLibrary(ID));  
    420         }  
    421  
    422         public void DeleteLibrary(Telerik.Libraries.ILibrary library)  
    423         {  
    424             if (library == null)  
    425             {  
    426                 throw new ArgumentException("library");  
    427             }  
    428             lock (this)  
    429             {  
    430                 IOdbClass mem = library as IOdbClass;  
    431                 if (mem == null)  
    432                 {  
    433                     throw new NotSupportedException(string.Format(Messages.NotSupportedType, library.GetType().Name));  
    434                 }  
    435                 if (mem.Provider != base.odbProvider)  
    436                 {  
    437                     throw new InvalidOperationException(Messages.ItemBelongsToOtherProvider);  
    438                 }  
    439                 Transaction currentTransaction = mem.CurrentTransaction;  
    440                 if (currentTransaction == null)  
    441                 {  
    442                     currentTransaction = new Transaction();  
    443                 }  
    444                 base.OnExecuting(new ExecutingEventArgs("DeleteLibrary", library));  
    445                 currentTransaction.Delete(mem);  
    446                 currentTransaction.Commit();  
    447                 base.OnExecuted(new ExecutedEventArgs("DeleteLibrary", library));  
    448             }  
    449         }  
    450  
    451         public int DocumentsCount(Guid parentID)  
    452         {  
    453             Guid[] parentIDs = new Guid[] { parentID };  
    454             return this.ContentCount(null, parentIDs, this.DocumentsFilter);  
    455         }   
    456  
    457         public System.Collections.IList GetAllLibraries(string typeName, bool isEqual)  
    458         {  
    459             Libraries libraries = new Libraries();  
    460             libraries.Provider = base.odbProvider;  
    461             QueryCondition condition = isEqual ? QueryCondition.EQ : QueryCondition.NE;  
    462             libraries.AndCondition("TypeName", condition, typeName);  
    463             libraries.AndCondition("Application", QueryCondition.EQ, this.Application);  
    464             libraries.LoadAll();  
    465             return libraries;  
    466         }  
    467  
    468         public System.Collections.IList GetAllLibraries(int from, int max, ref int count, string sortExp)  
    469         {  
    470             Libraries libraries = new Libraries();  
    471             libraries.Provider = base.odbProvider;  
    472             if (!string.IsNullOrEmpty(sortExp))  
    473             {  
    474                 libraries.OrderBy = sortExp;  
    475             }  
    476             else 
    477             {  
    478                 libraries.OrderBy = "DateCreated DESC";  
    479             }  
    480             libraries.AndCondition("Application", QueryCondition.EQ, this.Application);  
    481             if ((max == 0) && (from == 0))  
    482             {  
    483                 libraries.LoadAll();  
    484                 return libraries;  
    485             }  
    486             libraries.Load(from + max, from);  
    487             return libraries;  
    488         }  
    489  
    490         public System.Collections.IList GetAllLibraries(string sortExpr)  
    491         {  
    492             int count = 0;  
    493             return this.GetAllLibraries(0, 0, ref count, sortExpr);  
    494         }  
    495  
    496         public System.Collections.IList GetAllLibraries()  
    497         {  
    498             return this.GetAllLibraries(string.Empty);  
    499         }  
    500  
    501         public System.Collections.IList GetDocuments(int from, int max, string sortExp, Guid[] parentIDs)  
    502         {  
    503             return this.GetContent(from, max, sortExp, string.Empty, null, parentIDs, this.DocumentsFilter);  
    504         }  
    505  
    506         public System.Collections.IList GetImages(int from, int max, string sortExp, Guid[] parentIDs)  
    507         {  
    508             return this.GetContent(from, max, sortExp, string.Empty, null, parentIDs, this.ImagesFilter);  
    509         }  
    510  
    511         public int GetLibrariesCount()  
    512         {  
    513             if (base.odbProvider is SQLDataProvider)  
    514             {  
    515                 return this.GetLibrariesCountOptimized();  
    516             }  
    517             return this.GetLibrariesCountSlow();  
    518         }  
    519  
    520         public Telerik.Libraries.ILibrary GetLibrary(string name)  
    521         {  
    522             Libraries libraries = new Libraries();  
    523             libraries.Provider = base.odbProvider;  
    524             libraries.AndCondition("Application", QueryCondition.EQ, this.Application);  
    525             libraries.AndCondition("Name", QueryCondition.EQ, name);  
    526             libraries.LoadAll();  
    527             if (libraries.Count > 0)  
    528             {  
    529                 return libraries[0];  
    530             }  
    531             return null;  
    532         }  
    533  
    534         public Telerik.Libraries.ILibrary GetLibrary(Guid libraryID)  
    535         {  
    536             if (libraryID == Guid.Empty)  
    537             {  
    538                 return null;  
    539             }  
    540             Library primaryKey = new Library();  
    541             primaryKey.ID = libraryID;  
    542             primaryKey.Application = this.Application;  
    543             primaryKey = (Library)OdbClass.LoadByPrimaryKey(primaryKey, base.odbProvider, ObDataCache.Current);  
    544             if (primaryKey != null)  
    545             {  
    546                 IOdbClass mem = primaryKey;  
    547                 if (mem.CurrentTransaction == null)  
    548                 {  
    549                     new Transaction().Join(mem);  
    550                 }  
    551             }  
    552             return primaryKey;  
    553         }  
    554  
    555         public int ImagesCount(Guid parentID)  
    556         {  
    557             Guid[] parentIDs = new Guid[] { parentID };  
    558             return this.ContentCount(null, parentIDs, this.ImagesFilter);  
    559         }  
    560  
    561         public void SaveLibrary(Telerik.Libraries.ILibrary library)  
    562         {  
    563             if (library == null)  
    564             {  
    565                 throw new ArgumentNullException("library");  
    566             }  
    567             library.Name = library.Name.Trim();  
    568             IOdbClass mem = library as IOdbClass;  
    569             if (mem == null)  
    570             {  
    571                 throw new NotSupportedException(string.Format(Messages.NotSupportedType, library.GetType().Name));  
    572             }  
    573             if ((mem.CurrentState != OdbObjectStates.Uninitialized) && (mem.Provider != base.odbProvider))  
    574             {  
    575                 throw new InvalidOperationException(Messages.ItemBelongsToOtherProvider);  
    576             }  
    577             Transaction currentTransaction = mem.CurrentTransaction;  
    578             if (currentTransaction == null)  
    579             {  
    580                 currentTransaction = new Transaction();  
    581                 base.OnExecuting(new ExecutingEventArgs("SaveLibrary", library));  
    582                 if (mem.CurrentState == OdbObjectStates.Uninitialized)  
    583                 {  
    584                     currentTransaction.Create(mem, base.odbProvider);  
    585                 }  
    586                 else 
    587                 {  
    588                     currentTransaction.Join(mem);  
    589                 }  
    590             }  
    591             currentTransaction.Commit();  
    592             base.OnExecuted(new ExecutedEventArgs("SaveLibrary", library));  
    593         }
    594
    595         #endregion  
    596     }  
    597 }  
    598  

  7. Pierre
    Pierre avatar
    433 posts
    Registered:
    16 Feb 2006
    15 Jul 2008
    Link to this post
    Hi Daniel,

    Great!, soo could you help to implement the solution. How to use to manage permisions for Users or filtering after implement the Provider.

    Many thanks to share with us. Regards Romi
  8. Terry
    Terry avatar
    4 posts
    Registered:
    01 Jun 2008
    22 Dec 2010
    Link to this post
    Hi guys,

    I was in the same situation with Daniel, and i have run Sitefinity 3.7. In order to filter library per user's permission, i have to completely rewrite the LibraryProvider, and i had almost the same class with Daniel, except some new properties, methods in newer version of Sitefinity. Basically, i have introduced a new class (and put in App_Code folder of my web application). 
    namespace Foo.Web
    {
    public class LibraryProvider : Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Libraries.ILibraryProvider
    { ... } 
    }

    I also went to Web.Config to change the DefaultProvider as Daniel suggestion, to replace the type="Telerik.Libraries.Data.DefaultProvider, Telerik.Libraries.Data" by my own one type="Foo.Web.LibraryProvider, Foo.Web". 

    However, in my test page (the very first page when run the website), i have a call to BlogManager blog = new BlogManager(); and it throws me an exception Missing Libraries provider; 

    I have tried to add/remove the 2 hints from Daniel post, however, it doesn't work. I also tried to add assembly version to my class as below
    [assembly: AssemblyVersion("3.7.2136.2")]
    public class LibraryProvider : Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Libraries.ILibraryProvider
    {...}

    That's all i have done, but the result still the same. Seems like it never ran to my Initialize method in my custom LibraryProvider (i always have a breakpoint in it). 

    My task is pretty simple, i just need a way to customize the Library provider. Any help is greatly appreciate. Please let me know if you want to try my real implementation for LibraryProvider (i basically reflect everything from the DefaultProvider). 

    Thanks,

    Terry



  9. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    25 Nov 2016
    22 Dec 2010
    Link to this post
    Hello Daniel,

    There are two things that you have to do to filter by library

    1. override GetAllLibraries(string sortExpr) method in the data class
    2. Replace the default data provider in the web.config <cmsEngine> node with the custom one for Libraries provider.

    Greetings,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  10. Terry
    Terry avatar
    4 posts
    Registered:
    01 Jun 2008
    24 Dec 2010
    Link to this post
    Hi Ivan, 

    Would you please help me with a working web.config registration for a custom library provider ? I've tried many ways but it keeps saying Missing Provider. 

    At first, i tried to replace DefaultProvider by a custom one (as describe in my previous post), it threw me a missing provider: Libraries. 

    I then tried to create a new custom library provider name CustomLibaryProvider
    public class CustomLibraryProvider : Telerik.Cms.Engine.Data.Providers.DefaultProvider, Telerik.Libraries.ILibraryProvider

    and try to register in Web.Config. My point is instead of customizing the whole library provider which i failed earlier, i rather add a new custom library provider, where i can dynamically refer to it when needed. However, it still throw me back an exception: Missing Provider : CustomLibraries 

    My web.config:

    <genericContentProviders>
    <add providerName="Libraries" publicationDateField="Publication_Date"/>
            <add providerName="CustomLibraries" publicationDateField="Publication_Date"/>
    </genericContentProviders>

    <cmsEngine defaultProvider="Generic_Content">
    <providers>
    <add name="Libraries" urlRewriteFormat="~/{Provider}/{LibraryName}/[Name].sflb.ashx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="False" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Telerik.Libraries.Data.DefaultProvider, Telerik.Libraries.Data" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx"/>

    <add name="CustomLibraries" urlRewriteFormat="~/{Provider}/{LibraryName}/[Name].sflb.ashx" urlDateTimeFormat="yy-MM-dd" urlWhitespaceChar="_" visible="False" defaultMetaField="Name" applicationName="/Libraries" allowVersioning="False" allowLocalization="False" localizationProviderName="" allowWorkflow="False" securityProviderName="" versioningProviderName="" connectionStringName="GenericContentConnection" type="Foo.Web.CustomLibraryProvider, Foo.Web" tagEditorTemplate="~/Sitefinity/Admin/ControlTemplates/Libraries/BatchTagsEditor.ascx"/>
    </providers>

    <!--Add new CustomLibraries provider-->
            <add key="CustomLibraries.Name" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Width" valueType="Integer" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Height" valueType="Integer" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Size" valueType="Integer" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Extension" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.AlternateText" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Author" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Description" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.Category" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <add key="CustomLibraries.PermaLink" valueType="ShortText" visible="True" searchable="True" sortable="True" defaultValue=""/>
            <!--End CustomLibraries-->)

    Would you please help me with a complete working registration for a custom provider ? (btw, i am using Sitefinity 3.7). 

    Thank you very much, 

    Terry
  11. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    25 Nov 2016
    27 Dec 2010
    Link to this post
    Hi Daniel,

    Please check this post which explains how to register custom ( additional)  provider

    All the best,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Register for webinar
11 posts, 0 answered