none
problem with openning application page that contains templates in documnt library RRS feed

  • Question

  • i create two site collection http://test.local and second http://test.local/sekt3/2020. in site collection http://test.local i created document library that contains document templates and in second document template i created new ribbon button for document libraries. when i click on this button it's opens application page  that displays templates from document library from site collection http://test.local. the problem is next. when i activate this button on site collection http://test.local, it's all ok, like on picture

    but, when click on button in document library i receive error like on picture

    my code in cs page is

    using System;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using Microsoft.SharePoint.Administration;
    using System.Collections;
    using System.Data;
    using Microsoft.SharePoint.Utilities;
    using System.Web;
    
    using System.Web.UI.WebControls;
    using System.Web.UI;
    
    using Microsoft.SharePoint.Client;
    
    
    
    namespace Obrasci.Layouts.Obrasci
    {
       
    
        public partial class TemplateSelector : LayoutsPageBase
           {
    
                    // datasource for the Template ListView
                 public readonly DataTable _dataTable = new DataTable();
                   
                    protected void Page_Load(object sender, EventArgs e)
                {
                    if (!IsPostBack)
                    {
    
                        SetTemplateLibraryFolders();
                    }
                  
                          _dataTable.Columns.Add("ImageUrl", typeof(string));
                         _dataTable.Columns.Add("Title", typeof(string));
                        _dataTable.Columns.Add("Url", typeof(string));
                       var selectedNode = tvFolders.SelectedNode == null ? tvFolders.Nodes[0].Value : tvFolders.SelectedNode.Value;
                     
                     GetTemplatesInSelectedFolder(selectedNode);
                    // set the templates as the datasource for the template list view
                      lvTemplates.DataSource = _dataTable;
                      lvTemplates.DataBind();
                 }
    
    
                    private void SetTemplateLibraryFolders()
                    {
                        SPSite currentsite = new SPSite("http://test-net.dri.local");
                        using (SPWeb web = currentsite.OpenWeb())
                        {
                            tvFolders.EnableClientScript = true;
                            tvFolders.Target = "_self";
                            tvFolders.ShowLines = true;
                            tvFolders.ExpandDepth = 1;
                            SPList list = web.Lists["Обрасци за ревизију"];
    
                            TreeNode rootnode = new System.Web.UI.WebControls.TreeNode(list.Title);
                            rootnode.SelectAction = TreeNodeSelectAction.SelectExpand;
                            rootnode.ImageUrl = currentsite.RootWeb.Url + "/_layouts/images/FOLDER16.GIF";
                            TraverseFolder(list.RootFolder, rootnode);
                            tvFolders.Nodes.Add(rootnode);
                          
                        //    placeHolder.Controls.Add(tvFolders);
                        }
                    }
    
    private void TraverseFolder(SPFolder sPFolder,TreeNode rootnode)
    {
     	 try
                        {
                            // add the files contained in this folder   
                            foreach (SPFile file in sPFolder.Files)
                            {
                                // create a new node and add to the tree   
                                TreeNode childNode = new System.Web.UI.WebControls.TreeNode(file.Name + " (" + file.TimeLastModified.ToShortDateString() + ")", "", "~/_layouts/images/" + file.IconUrl, file.ServerRelativeUrl.ToString(), "");
                                rootnode.ChildNodes.Add(childNode);
                            }
                            // test if we have child folders   
                            bool blnRecurseFolders = sPFolder.SubFolders.Count > 0 ? true : false;
                            SPSite currentsite = new SPSite("http://test-net.dri.local");
                            // if we have sub folders then loop through them   
                            if (blnRecurseFolders)
                            {
                                // loop through the child folders   
                                foreach (SPFolder childFolder in sPFolder.SubFolders)
                                {
                                    if (childFolder.Name.ToString() != "Forms")
                                    {
                                        // create a new node and loop through the files   
                                        TreeNode childNode = new TreeNode();
                                        childNode.Text = childFolder.Name;
                                        childNode.Value = childFolder.ServerRelativeUrl.ToString();
    
                                        childNode.ImageUrl = currentsite.RootWeb.Url + "/_layouts/images/FOLDER16.GIF";
                                        //SPUtility.ConcatUrls("/_layouts/images/", SPUtility.MapToIcon(file.Web, SPUtility.ConcatUrls(file.Web.Url, file.Url),"", IconSize.Size32));
                                        rootnode.ChildNodes.Add(childNode);
                                        //  rootnode.ChildNodes.Add(TraverseFolder(childFolder, childNode));
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            //TODO: handle error   
                        }
                     return ;
    }
    
             /// <summary>
            /// Open selected folder of the templates library and fill
            /// the data table with the templates in the folder
            /// </summary>
            /// <param name="folderUrl">Target folder</param>
    private void GetTemplatesInSelectedFolder(string folderURL)
    {
     	using (SPSite site = new SPSite("http://test-net.dri.local"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        
                        SPList list = web.Lists.TryGetList("Обрасци за ревизију");
                        if (list != null)
                       {
                            SPDocumentLibrary docLib = (SPDocumentLibrary)list;
                            SPFolder folder = web.GetFolder(folderURL);
                           AddFilesToDataTable(web, folder);
                       }
                   }
               }
    }
    
              /// <summary>
            /// Add templates to the data source
            /// </summary>
            /// <param name="docWeb"></param>
            /// <param name="folder"></param>
    private void AddFilesToDataTable(SPWeb docWeb,SPFolder folder)
    {
     	 foreach (SPFile file in folder.Files)
               {
                   // get template icon
                   string docIcon = SPUtility.ConcatUrls("/_layouts/images/", SPUtility.MapToIcon(file.Web, SPUtility.ConcatUrls(file.Web.Url, file.Url),"", IconSize.Size32));
    
                   // absolute url of the template
                   string absUrl = (string)file.Item[SPBuiltInFieldId.EncodedAbsUrl];
                   
                   // click action
                   string action;
    
                   if (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["DocLib"]))
    
                   {
                       // get the list from the List query string
                       Guid? docLibId =  new Guid(HttpContext.Current.Request.QueryString["DocLib"]);
                    //   string docLibId = HttpContext.Current.Request.QueryString["DocLib"];
                      
                       // create list object and list item object
                    //   SPList selectedLibrary = docWeb.Lists[new Guid(docLibId)];
                     SPList selectedLibrary = docWeb.Lists.GetList(docLibId.Value,true);
    
                       string docLibUrl = selectedLibrary.DefaultViewUrl;
                       // remove Forms[%] from the view url to get the
                       // correct document library url
                       docLibUrl = docLibUrl.Remove(docLibUrl.LastIndexOf("Forms",StringComparison.Ordinal));
                       string[] splitdocLibUrl = docLibUrl.Split('/');
                       SPSite site = new SPSite("http://test-net.dri.local");
                       action = string.Format("javascript:OpenNewTemplate('{0}','{1}');", absUrl, site.RootWeb.Url + '/' + selectedLibrary.Title.ToString() + '/');
                   }
                   else
                   {
                       // if query string DocLib is empty use the default web url
                       action =string.Format("javascript:OpenNewTemplateThenClose('{0}','{1}');",absUrl,SPContext.Current.Web.Url);
                   }
     
    
                  
                   AddDataToDataTable(docIcon, file.Name, action);
    
                   
               }
    }
      /// <summary>
           /// Add template to the data source
           /// </summary>
           /// <param name="docIcon">Template icon</param>
           /// <param name="title">Template title</param>
           /// <param name="url">Template url</param>
    private void AddDataToDataTable(string docIcon,string title,string url)
    {
     	DataRow row = _dataTable.NewRow();
               row["ImageUrl"] = docIcon;
               row["Title"] = title;
                row["Url"] = url;
               _dataTable.Rows.Add(row);
    }
    
                    
                          
             
                          
           
           
          
        }
    }
    

    the code in aspx page is next

    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
    <%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
    <%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
    <%@ Register TagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"%>
    <%@ Import Namespace="Microsoft.SharePoint" %>
    <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TemplateSelector.aspx.cs" Inherits="Obrasci.Layouts.Obrasci.TemplateSelector" DynamicMasterPageFile="~masterurl/default.master" %>
    
    <asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script language='javascript' type="text/javascript">
        // Open template with the corresponding Office app
        function OpenNewTemplate(strTemplate, strSaveLocation) {
            var strProgID = "SharePoint.OpenDocuments";
            createNewDocumentWithProgID(makeAbsUrl(strTemplate), makeAbsUrl(strSaveLocation), strProgID, false);
            window.frameElement.commitPopup();
        }
    </script>
    </asp:Content>
    
    <asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    
    <div>
    <div id="Navigation" style="; top: 0; left: 0;" >
    
    <asp:TreeView ID="tvFolders" runat="server" ShowLines="true"></asp:TreeView>
    </div>
    
    
    <!-- </div> -->
    <div id="Content" style="margin-left: 30em;">
        <asp:ListView ID="lvTemplates" runat="server" GroupItemCount="5" DataKeyNames="Title">
            <LayoutTemplate>
                 <table cellpadding="5" runat="server" id="tblTemplates">
                     <tr id="groupplaceholder" runat="server"></tr>
                  </table>
             </LayoutTemplate>
             <GroupTemplate>
              <tr id="itemPlaceholderContainer" runat="server" style="height: 80px;">
                <td id="itemPlaceholder" runat="server">
                </td>
              </tr>
            </GroupTemplate>
             <ItemTemplate>
               <td id="Td1" valign="top" align="center" style="width: 100px;" runat="server">
                <asp:HyperLink ID="TemplateLink" runat="server" NavigateUrl='<%# Eval("Url") %>' Target="">
                     
                <asp:Image ID="IconImage" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' />
                 <br />
                     
                 <%# Eval("Title") %>
                </asp:HyperLink>
               </td>
              </ItemTemplate>
            </asp:ListView>
      </div>
      </div>
    
    </asp:Content>
    
    <asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Application Page
    </asp:Content>
    
    <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    My Application Page
    </asp:Content>
    

    i debugged code and i found error in line 

     SPList selectedLibrary = docWeb.Lists.GetList(docLibId.Value,true);

    Value does not fall within the expected range

    why this code is not working?what i do? what i change in them?

    Wednesday, July 31, 2019 12:24 PM

All replies

  • Hi

    What is the doclibId.Value value?


    Justin Liu Office Apps & Services MVP, MCSE
    Senior Software Engineer
    Please Vote and Mark as Answer if it helps you.

    Thursday, August 1, 2019 1:15 AM
  • Hi,

    Please check if Document Library Guid is valid, here is a basic demo for your reference:

               SPSite site = new SPSite("http://sp/sites/dev/");
                using (SPWeb web =site.OpenWeb())
                {
                    Guid guid=new Guid("A8D3596E-4929-43BF-B29D-7641E910DC08");
    
                    SPList list = web.Lists.GetList(guid, true);
                }
       

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Thursday, August 1, 2019 3:16 AM