Exemplo n.º 1
0
        /// <summary>
        /// Получает данные переданного списка, используя фильтр по колонкам строк
        /// </summary>
        /// <param name="список">Выбранный список, данные которого нужно получить.</param>
        /// <param name="условияВыборки">Условия фильтрации данных списка. Должны быть заключены в теги: Eq - равно<br/>Neq - не равно<br/>Gt - больше, чем...<br/>Geq - больше или равно<br/>Lt - меньше, чем...<br/>Leq - меньше или равно
        /// <br/>IsNull<br/>IsNotNull<br/>BeginsWith - начинается с... (для текста)<br/>Contains - содержит (для текста)<br/>Includes - включает</param>
        /// <param name="максимумСтрок">Максимальное количество строк, которое необходимо возвратить.</param>
        /// <returns>Данные списка</returns>
        public ListItemCollection ПолучитьДанныеСписка(SP.List список, string условияВыборки = "", int максимумСтрок = 3000)
        {
            try
            {
                if (_портал == null || _портал.Web == null) return null;

                CamlQuery camlQuery = new CamlQuery
                {
                    ViewXml = string.Format("<View><Query><Where>{0}</Where></Query><RowLimit>{1}</RowLimit></View>", условияВыборки, максимумСтрок) /*<Geq><FieldRef Name='ID'/><Value Type='Number'>10</Value></Geq>*/
                };
                ListItemCollection данные = список.GetItems(camlQuery);

                _портал.Load(данные);
                _портал.ExecuteQuery();
                return данные;
            }
            catch (Exception ex) { throw new DataException(ОшибкаНетДанных, ex); }
        }
Exemplo n.º 2
0
        public static View ExtractView(SPClient.View listView)
        {
            var schemaElement = XElement.Parse(listView.ListViewXml);

                // Toolbar is not supported

                var toolbarElement = schemaElement.Descendants("Toolbar").FirstOrDefault();
                if (toolbarElement != null)
                {
                    toolbarElement.Remove();
                }

                // XslLink is not supported
                var xslLinkElement = schemaElement.Descendants("XslLink").FirstOrDefault();
                if (xslLinkElement != null)
                {
                    xslLinkElement.Remove();
                }

            View view = new View { SchemaXml = schemaElement.ToString(), PageUrl = listView.ServerRelativeUrl };
            return view;
        }
        internal Model.File RetrieveFieldValues(Web web, Microsoft.SharePoint.Client.File file, Model.File modelFile)
        {
            ListItem listItem = null;
            try
            {
                listItem = file.EnsureProperty(f => f.ListItemAllFields);
            }
            catch { }

            if (listItem != null)
            {
                var list = listItem.ParentList;

                var fields = list.Fields;
                web.Context.Load(fields, fs => fs.IncludeWithDefaultProperties(f => f.TypeAsString, f => f.InternalName, f => f.Title));
                web.Context.ExecuteQueryRetry();

                var fieldValues = listItem.FieldValues;

                var fieldValuesAsText = listItem.EnsureProperty(li => li.FieldValuesAsText).FieldValues;

                var fieldstoExclude = new[] {
                "ID",
                "GUID",
                "Author",
                "Editor",
                "FileLeafRef",
                "FileRef",
                "File_x0020_Type",
                "Modified_x0020_By",
                "Created_x0020_By",
                "Created",
                "Modified",
                "FileDirRef",
                "Last_x0020_Modified",
                "Created_x0020_Date",
                "File_x0020_Size",
                "FSObjType",
                "IsCheckedoutToLocal",
                "ScopeId",
                "UniqueId",
                "VirusStatus",
                "_Level",
                "_IsCurrentVersion",
                "ItemChildCount",
                "FolderChildCount",
                "SMLastModifiedDate",
                "owshiddenversion",
                "_UIVersion",
                "_UIVersionString",
                "Order",
                "WorkflowVersion",
                "DocConcurrencyNumber",
                "ParentUniqueId",
                "CheckedOutUserId",
                "SyncClientId",
                "CheckedOutTitle",
                "SMTotalSize",
                "SMTotalFileStreamSize",
                "SMTotalFileCount",
                "ParentVersionString",
                "ParentLeafName",
                "SortBehavior",
                "StreamHash",
                "TaxCatchAll",
                "TaxCatchAllLabel",
                "_ModerationStatus",
                "HtmlDesignAssociated",
                "HtmlDesignStatusAndPreview",
            };

                foreach (var fieldValue in fieldValues.Where(f => !fieldstoExclude.Contains(f.Key)))
                {
                    if (fieldValue.Value != null && !string.IsNullOrEmpty(fieldValue.Value.ToString()))
                    {
                        var field = fields.FirstOrDefault(fs => fs.InternalName == fieldValue.Key);

                        string value = string.Empty;

                        switch (field.TypeAsString)
                        {
                            case "URL":
                                value = Tokenize(fieldValuesAsText[fieldValue.Key], web.Url);
                                break;
                            case "User":
                                var fieldUserValue = fieldValue.Value as Microsoft.SharePoint.Client.FieldUserValue;
                                if (fieldUserValue != null)
                                {
#if !CLIENTSDKV15
                                    value = fieldUserValue.Email;
#else
                                value = fieldUserValue.LookupValue;
#endif
                                }
                                break;
                            case "LookupMulti":
                            case "TaxonomyFieldType":
                            case "TaxonomyFieldTypeMulti":
                                var internalFieldValue = fieldValue.Value as Microsoft.SharePoint.Client.FieldLookupValue[];
                                if (internalFieldValue != null)
                                {
                                    value = Tokenize(JsonUtility.Serialize(internalFieldValue), web.Url);
                                }
                                break;
                            case "ContentTypeIdFieldType":
                            default:
                                value = Tokenize(fieldValue.Value.ToString(), web.Url);
                                break;
                        }

                        if (fieldValue.Key == "ContentTypeId")
                        {
                            // Replace the content typeid with a token
                            var ct = list.GetContentTypeById(value);
                            if (ct != null)
                            {
                                value = string.Format("{{contenttypeid:{0}}}", ct.Name);
                            }
                        }

                        // We process real values only
                        if (value != null && !String.IsNullOrEmpty(value) && value != "[]")
                        {
                            modelFile.Properties.Add(fieldValue.Key, value);
                        }
                    }
                }
            }

            return modelFile;
        }
Exemplo n.º 4
0
        private void SetUI()
        {
            
            // define initial script, needed to render the chrome control
            string script = @"
            function chromeLoaded() {
                $('body').show();
            }

            //function callback to render chrome after SP.UI.Controls.js loads
            function renderSPChrome() {
                //Set the chrome options for launching Help, Account, and Contact pages
                var options = {
                    'appTitle': document.title,
                    'onCssLoaded': 'chromeLoaded()'
                };

                //Load the Chrome Control in the divSPChrome element of the page
                var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
                chromeNavigation.setVisible(true);
            }";

            //register script in page
            Page.ClientScript.RegisterClientScriptBlock(typeof(Default), "BasePageScript", script, true);

            lblBasePath.Text = Request["SPHostUrl"] + "/";

            var availableWebTemplatesForWeb = _ctx.Web.GetAvailableWebTemplates(1033, true);
            _ctx.Load(availableWebTemplatesForWeb);
            bool isPublishingWeb = _ctx.Web.IsPublishingWeb();

            var _siteFactory = SiteTemplateFactory.GetInstance();
            var _tm = _siteFactory.GetManager();
            var _templates = _tm.GetAvailableTemplates();

            var pubTemplates = new[] { "ENTERWIKI#0" };
            
            listSites.DataSource = _templates.Where(x => !x.RootWebOnly && x.Enabled
                                        && availableWebTemplatesForWeb.Any(y=>y.Name ==  x.RootTemplate)
                                        && (isPublishingWeb || !pubTemplates.Any(y => y == x.RootTemplate)));
            listSites.DataBind();

            listSites.SelectedIndex = 0;
        }
Exemplo n.º 5
0
 /// <summary>
 /// Dedicated code to wrap ExecuteQuery on file ops and check for errors.
 /// We have to check for the exceptions thrown to know about file /folder existence.
 /// Why the funny guys at MS provided an .Exists field stays a mystery...
 /// </summary>
 /// <param name="fileNameInfo"> the filename  </param>
 private void wrappedExecuteQueryOnConext(SP.ClientContext ctx, string serverRelPathInfo, bool isFolder)
 {
     try { ctx.ExecuteQuery(); }
     catch (ServerException ex)
     {
         // funny: If a folder is not found, we still get a FileNotFoundException from Server...?!?
         // Thus, we help ourselves by just passing the info if we wanted to query a folder.
         if (ex.ServerErrorTypeName == "System.IO.DirectoryNotFoundException"
             || (ex.ServerErrorTypeName == "System.IO.FileNotFoundException" && isFolder))
             throw new Interface.FolderMissingException(Strings.SharePoint.MissingElementError(serverRelPathInfo, m_spWebUrl));
         if (ex.ServerErrorTypeName == "System.IO.FileNotFoundException")
             throw new Interface.FileMissingException(Strings.SharePoint.MissingElementError(serverRelPathInfo, m_spWebUrl));
         else
             throw;
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Builds a client context and tries a simple query to test if there's a web.
        /// Returns 0 on success, negative if completely invalid, positive if SharePoint error (likely wrong creds).
        /// </summary>
        private static int testUrlForWeb(string url, System.Net.ICredentials userInfo, bool rethrow, out SP.ClientContext retCtx)
        {
            int result = -1;
            retCtx = null;
            SP.ClientContext ctx = new ClientContext(url);
            try
            {
                ctx.Credentials = userInfo;
                result = testContextForWeb(ctx, rethrow);
                if (result >= 0)
                {
                    retCtx = ctx;
                    ctx = null;
                }
            }
            finally { if (ctx != null) { ctx.Dispose(); } }

            return result;
        }
Exemplo n.º 7
0
 /// <summary>
 /// Tries a simple query to test the passed context.
 /// Returns 0 on success, negative if completely invalid, positive if SharePoint error (wrong creds are negative).
 /// </summary>
 private static int testContextForWeb(SP.ClientContext ctx, bool rethrow = true)
 {
     try
     {
         ctx.Load(ctx.Web, w => w.Title);
         ctx.ExecuteQuery(); // should fail and throw if anything wrong.
         string webTitle = ctx.Web.Title;
         if (webTitle == null)
             throw new UnauthorizedAccessException(Strings.SharePoint.WebTitleReadFailedError);
         return 0;
     }
     catch (Microsoft.SharePoint.Client.ServerException)
     {
         if (rethrow) throw;
         else return 1;
     }
     catch (Exception)
     {
         if (rethrow) throw;
         else return -1;
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// SharePoint has nested subwebs but sometimes different webs
        /// are hooked into a sub path.
        /// For finding files SharePoint is picky to use the correct
        /// path to the web, so we will trial and error here.
        /// The user can give us a hint by supplying an URI with a double
        /// slash to separate web.
        /// Otherwise it's a good guess to look for "/documents", as we expect
        /// that the default document library is used in the path.
        /// If that won't help, we will try all possible pathes from longest
        /// to shortest...
        /// </summary>
        private static string findCorrectWebPath(Utility.Uri orgUrl, System.Net.ICredentials userInfo, out SP.ClientContext retCtx)
        {
            retCtx = null;

            string path = orgUrl.Path;
            int webIndicatorPos = path.IndexOf("//");

            // if a hint is supplied, we will of course use this first.
            if (webIndicatorPos >= 0)
            {
                string testUrl = new Utility.Uri(orgUrl.Scheme, orgUrl.Host, path.Substring(0, webIndicatorPos), null, null, null, orgUrl.Port).ToString();
                if (testUrlForWeb(testUrl, userInfo, false, out retCtx) >= 0)
                    return testUrl;
            }

            // Now go through path and see where we land a success.
            string[] pathParts = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            // first we look for the doc library
            int docLibrary = Array.FindIndex(pathParts, p => StringComparer.InvariantCultureIgnoreCase.Equals(p, "documents"));
            if (docLibrary >= 0)
            {
                string testUrl = new Utility.Uri(orgUrl.Scheme, orgUrl.Host,
                    string.Join("/", pathParts, 0, docLibrary),
                    null, null, null, orgUrl.Port).ToString();
                if (testUrlForWeb(testUrl, userInfo, false, out retCtx) >= 0)
                    return testUrl;
            }

            // last but not least: try one after the other.
            for (int pi = pathParts.Length - 1; pi >= 0; pi--)
            {
                if (pi == docLibrary) continue; // already tested

                string testUrl = new Utility.Uri(orgUrl.Scheme, orgUrl.Host,
                    string.Join("/", pathParts, 0, pi),
                    null, null, null, orgUrl.Port).ToString();
                if (testUrlForWeb(testUrl, userInfo, false, out retCtx) >= 0)
                    return testUrl;
            }

            // nothing worked :(
            return null;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Retrieves the document and List GUID
        /// </summary>
        /// <param name="client">Client object containing list data</param>        
        /// <param name="clientContext">Client Context</param>     
        /// <returns>Returns the document and List GUID</returns>
        public dynamic GetDocumentAndClientGUID(Client client)
        {
            try
            {
                using (ClientContext clientContext = spoAuthorization.GetClientContext(client.Url))
                {
                    string listInternalName = string.Empty;
                    string documentGUID = string.Empty;
                    string result = string.Empty;
                    ListCollection lists = clientContext.Web.Lists;
                    clientContext.Load(lists, list => list.Include(listItem => listItem.Id, listItem => listItem.RootFolder.ServerRelativeUrl));
                    SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(client.Id);
                    clientContext.Load(file, files => files.ListItemAllFields);
                    clientContext.ExecuteQuery();
                    if (0 < file.ListItemAllFields.FieldValues.Count)
                    {
                        documentGUID = Convert.ToString(file.ListItemAllFields.FieldValues[ServiceConstants.DOCUMENT_GUID_COLUMN_NAME], CultureInfo.InvariantCulture);
                    }

                    List retrievedList = (from list in lists
                                          where list.RootFolder.ServerRelativeUrl.ToUpperInvariant().Equals(client.Name.ToUpperInvariant())
                                          select list).FirstOrDefault();
                    if (null != retrievedList)
                    {
                        listInternalName = Convert.ToString(retrievedList.Id, CultureInfo.InvariantCulture);
                    }
                    var documentAsset = new
                    {
                        ListInternalName = listInternalName,
                        DocumentGuid = documentGUID
                    };
                    return documentAsset;
                }
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
        }
Exemplo n.º 10
0
        private void CreateOrUpdateView(Web web, View view, SPClient.View existingView, List createdList, PnPMonitoredScope monitoredScope)
        {
            try
            {
                var viewElement = view.XmlNode;
                var viewTitle = view.GetAttributeValue("DisplayName");
                if (string.IsNullOrEmpty(viewTitle))
                {
                    throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName.");
                }
                monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, viewTitle);

                // Type
                var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.Attribute("Type").Value : "None";
                viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower();
                var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString);

                // Fields
                string[] viewFields = null;
                var viewFieldsElement = viewElement.Descendants("ViewFields").FirstOrDefault();
                if (viewFieldsElement != null)
                {
                    viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray();
                }

                // Default view
                var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value);

                // Row limit
                var viewPaged = true;
                uint viewRowLimit = 30;
                var rowLimitElement = viewElement.Descendants("RowLimit").FirstOrDefault();
                if (rowLimitElement != null)
                {
                    if (rowLimitElement.Attribute("Paged") != null)
                    {
                        viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value);
                    }
                    viewRowLimit = uint.Parse(rowLimitElement.Value);
                }

                // Query
                var viewQuery = new StringBuilder();
                foreach (var queryElement in viewElement.Descendants("Query").Elements())
                {
                    viewQuery.Append(queryElement);
                }

                var viewCI = new ViewCreationInformation
                {
                    ViewFields = viewFields,
                    RowLimit = viewRowLimit,
                    Paged = viewPaged,
                    Title = viewTitle,
                    Query = viewQuery.ToString(),
                    ViewTypeKind = viewType,
                    PersonalView = false,
                    SetAsDefaultView = viewDefault,
                };

                // Allow to specify a custom view url. View url is taken from title, so we first set title to the view url value we need,
                // create the view and then set title back to the original value
                var urlAttribute = viewElement.Attribute("Url");
                var urlHasValue = urlAttribute != null && !string.IsNullOrEmpty(urlAttribute.Value);
                if (urlHasValue)
                {
                    //set Title to be equal to url (in order to generate desired url)
                    viewCI.Title = Path.GetFileNameWithoutExtension(urlAttribute.Value);
                }

                if (null != existingView)
                {
                    bool needToDelete = false;
                    bool isDirty = false;
                    if (!string.Equals(viewCI.ViewTypeKind.ToString(), existingView.ViewType, StringComparison.OrdinalIgnoreCase))
                    {
                        needToDelete = true;
                    }
                    else
                    {
                        if (string.Join(",", existingView.ViewFields.ToArray()) != string.Join(",", viewCI.ViewFields))
                        {
                            existingView.ViewFields.RemoveAll();
                            foreach (string fieldName in viewCI.ViewFields)
                            {
                                existingView.ViewFields.Add(fieldName);
                            }
                            isDirty = true;
                        }
                        if (existingView.RowLimit != viewCI.RowLimit)
                        {
                            existingView.RowLimit = viewCI.RowLimit;
                            isDirty = true;
                        }
                        if (existingView.Paged != viewCI.Paged)
                        {
                            existingView.Paged = viewCI.Paged;
                            isDirty = true;
                        }
                        if (existingView.Title != viewTitle)
                        {
                            existingView.Title = viewTitle;
                            isDirty = true;
                        }
                        if (existingView.ViewQuery != viewCI.Query)
                        {
                            existingView.ViewQuery = viewCI.Query;
                            isDirty = true;
                        }
                        if (existingView.DefaultView != viewCI.SetAsDefaultView)
                        {
                            existingView.DefaultView = viewCI.SetAsDefaultView;
                            isDirty = true;
                        }
                    }

                    if (needToDelete)
                    {
                        existingView.DeleteObject();
                web.Context.ExecuteQueryRetry();
                        existingView = null;
                    }
                    else if (isDirty)
                    {
                        existingView.Update();
                        web.Context.ExecuteQueryRetry();
                    }
                }

                SPClient.View createdView = null;
                if (null == existingView)
                {
                    createdView = createdList.Views.Add(viewCI);
                    web.Context.Load(createdView);
                    web.Context.ExecuteQueryRetry();
                }
                else
                {
                    createdView = existingView;
                }

                bool dirty = false;
                if ( createdView.Title != viewTitle )
                {
                    //restore original title
                    createdView.Title = viewTitle;
                    dirty = true;
                }

                // ContentTypeID
                var contentTypeID = viewElement.Attribute("ContentTypeID") != null ? viewElement.Attribute("ContentTypeID").Value : null;
                if (!string.IsNullOrEmpty(contentTypeID) && (contentTypeID != BuiltInContentTypeId.System))
                {
                    ContentTypeId childContentTypeId = null;
                    if (contentTypeID == BuiltInContentTypeId.RootOfList)
                    {
                        var childContentType = web.GetContentTypeById(contentTypeID);
                        childContentTypeId = childContentType != null ? childContentType.Id : null;
                    }
                    else
                    {
                        childContentTypeId = createdList.ContentTypes.BestMatch(contentTypeID);
                    }
                    if (childContentTypeId != null)
                    {
                        if ((null == createdView.ContentTypeId) || (createdView.ContentTypeId.ToString() != childContentTypeId.ToString()))
                        {
                        createdView.ContentTypeId = childContentTypeId;
                            dirty = true;
                        }
                }
                }

                // Default for content type
                bool parsedDefaultViewForContentType;
                var defaultViewForContentType = viewElement.Attribute("DefaultViewForContentType") != null ? viewElement.Attribute("DefaultViewForContentType").Value : null;
                if (!string.IsNullOrEmpty(defaultViewForContentType) && bool.TryParse(defaultViewForContentType, out parsedDefaultViewForContentType))
                {
                    if (createdView.DefaultViewForContentType != parsedDefaultViewForContentType)
                    {
                    createdView.DefaultViewForContentType = parsedDefaultViewForContentType;
                        dirty = true;
                    }
                }

                // Scope
                var scope = viewElement.Attribute("Scope") != null ? viewElement.Attribute("Scope").Value : null;
                ViewScope parsedScope;
                if (!string.IsNullOrEmpty(scope) && Enum.TryParse(scope, out parsedScope))
                {
                    if (createdView.Scope != parsedScope)
                    {
                    createdView.Scope = parsedScope;
                        dirty = true;
                    }
                }

                // JSLink
                var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault();
                if (jslinkElement != null)
                {
                    var jslink = jslinkElement.Value;
                    if (createdView.JSLink != jslink)
                    {
                        createdView.JSLink = jslink;
                        dirty = true;
                    }
                }
                if (dirty)
                {
                        createdView.Update();
                    }
                createdList.Update();
                web.Context.ExecuteQueryRetry();
            }
            catch (Exception ex)
            {
                monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace);
            }
        }
Exemplo n.º 11
0
        private void VisualizzaAttivita(SP.ListItem lastItem)
        {
            if (lastItem != null)
            {
                var attivita = new Attivita()
                {
                    Titolo = lastItem["Title"] as string,
                    IdCommessa = Convert.ToInt32(lastItem["Commessa"] ?? 0),
                    DataInizio = Convert.ToDateTime(lastItem["DataInizio"]).ToLocalTime(),
                    //DataFine = Convert.ToDateTime(lastItem["DataFine"] ?? DateTime.Now).ToLocalTime()
                };

                frmAttivitaCorrente.DataSource = new List<Attivita>() { attivita };
                frmAttivitaCorrente.DataBind();
            }
        }