Exemple #1
0
        public void LogError(LogOptions option, Exception ex, string additionalInfo)
        {
            try
            {
                SPContext context = SPContext.GetContext(HttpContext.Current);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = new SPSite(context.Web.Url).OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        // implementation details omitted
                        SPList list         = web.Lists["Error-Log"];
                        SPField authorField = list.Fields.GetFieldByInternalName("Author0");
                        SPListItem newItem  = list.AddItem();
                        int maxLength       = 255;
                        string trimmedTitle = ex.Message.Length > maxLength - 1 ? ex.Message.Substring(0, maxLength) : ex.Message;

                        int userId      = context.Web.CurrentUser.ID;
                        string userName = context.Web.CurrentUser.LoginName;
                        SPFieldUserValue authorFieldValue = new SPFieldUserValue(web, userId, userName);

                        newItem["Title"]        = trimmedTitle;
                        newItem["Comment"]      = ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + (ex.InnerException != null ? ex.InnerException.Message : "No Inner Exception") + Environment.NewLine + (ex.InnerException != null ? ex.InnerException.StackTrace : "No Inner Exception Detail" + Environment.NewLine + additionalInfo);
                        newItem["Category"]     = categories[(int)option];
                        newItem[authorField.Id] = authorFieldValue;
                        newItem["IP"]           = HttpContext.Current.Request.UserHostAddress;
                        newItem.Update();

                        web.AllowUnsafeUpdates = false;
                    }
                });
            }
            catch { }
        }
Exemple #2
0
        private static string GetExampleDateFormat(SPWeb web, string yearLabel, string monthLabel, string dayLabel)
        {
            Guard.ArgumentIsNotNull(web, nameof(web));

            var format             = string.Empty;
            var context            = SPContext.GetContext(web);
            var spRegionalSettings = context.Web.CurrentUser.RegionalSettings ?? context.RegionalSettings;
            var dateSeparator      = spRegionalSettings.DateSeparator;
            var calendarOrderType  = (SPCalendarOrderType)spRegionalSettings.DateFormat;

            switch (calendarOrderType)
            {
            case SPCalendarOrderType.MDY:
                format = $"{monthLabel}{dateSeparator}{dayLabel}{dateSeparator}{yearLabel}";
                break;

            case SPCalendarOrderType.DMY:
                format = $"{dayLabel}{dateSeparator}{monthLabel}{dateSeparator}{yearLabel}";
                break;

            case SPCalendarOrderType.YMD:
                format = $"{yearLabel}{dateSeparator}{monthLabel}{dateSeparator}{dayLabel}";
                break;

            default:
                Trace.WriteLine($"Unexpected value: {calendarOrderType}");
                break;
            }

            return(format);
        }
Exemple #3
0
        public void LogAudit(string title, string message)
        {
            try
            {
                SPContext context = SPContext.GetContext(HttpContext.Current);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = new SPSite(context.Web.Url).OpenWeb())
                    {
                        int userId      = context.Web.CurrentUser.ID;
                        string userName = context.Web.CurrentUser.LoginName;
                        SPFieldUserValue authorFieldValue = new SPFieldUserValue(web, userId, userName);

                        web.AllowUnsafeUpdates = true;
                        // implementation details omitted
                        SPList list             = web.Lists["Audit-Log"];
                        SPField authorField     = list.Fields.GetFieldByInternalName("Author0");
                        SPListItem newItem      = list.AddItem();
                        newItem["Title"]        = title;
                        newItem["Log"]          = message;
                        newItem[authorField.Id] = authorFieldValue;
                        newItem["IP"]           = HttpContext.Current.Request.UserHostAddress;
                        newItem.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                });
            }
            catch { }
        }
Exemple #4
0
        private static string GetExampleDateFormat(SPWeb web, string yearLabel, string monthLabel, string dayLabel)
        {
            string format = string.Empty;

            SPContext context = SPContext.GetContext(web);

            SPRegionalSettings spRegionalSettings = context.Web.CurrentUser.RegionalSettings ?? context.RegionalSettings;

            string dateSeparator     = spRegionalSettings.DateSeparator;
            var    calendarOrderType = (SPCalendarOrderType)spRegionalSettings.DateFormat;

            switch (calendarOrderType)
            {
            case SPCalendarOrderType.MDY:
                format = monthLabel + dateSeparator + dayLabel + dateSeparator + yearLabel;
                break;

            case SPCalendarOrderType.DMY:
                format = dayLabel + dateSeparator + monthLabel + dateSeparator + yearLabel;
                break;

            case SPCalendarOrderType.YMD:
                format = yearLabel + dateSeparator + monthLabel + dateSeparator + dayLabel;
                break;
            }

            return(format);
        }
        public void Cleanup()
        {
            SPSite    spSite    = new SPSite("http://localhost:9001/sites/pssportal");
            SPContext spContext = SPContext.GetContext(spSite.RootWeb);

            Isolate.WhenCalled(() => SPContext.Current.Site).WillReturn(spSite);
            Isolate.WhenCalled(() => SPContext.Current).WillReturn(spContext);

            List <string> keys = new List <string>()
            {
                "IntegrationTest-FarmLevelKey", "IntegrationTest-WebAppLevelKey", "IntegrationTest-SiteLevelKey", "IntegrationTest-WebLevelKey"
            };

            HierarchicalConfig hierarchicalConfig = new HierarchicalConfig();

            foreach (string key in keys)
            {
                hierarchicalConfig.RemoveKeyFromPropertyBag(key, SPContext.Current.Web);
                hierarchicalConfig.RemoveKeyFromPropertyBag(key, SPContext.Current.Site);
                hierarchicalConfig.RemoveKeyFromPropertyBag(key, SPContext.Current.Site.WebApplication);
                hierarchicalConfig.RemoveKeyFromPropertyBag(key, SPFarm.Local);
            }

            Isolate.CleanUp();
        }
Exemple #6
0
    public bool TrySaveFile()
    {
        if (this.fileUpload.HasFile)
        {
            using (Stream uploadStream = this.fileUpload.FileContent)
            {
                this.OnFileUploading();
                var    originalFileName = this.fileUpload.FileName;
                SPFile file             = UploadFile(originalFileName, uploadStream);
                var    extension        = Path.GetExtension(this.fileUpload.FileName);
                this.itemId = file.Item.ID;

                using (new EventFiringScope())
                {
                    file.Item[SPBuiltInFieldId.ContentTypeId] = this.ContentTypeId;
                    file.Item.SystemUpdate(false);
                    //This code is used to guarantee that the file has a unique name.
                    var newFileName = String.Format("File{0}{1}", this.itemId, extension);
                    Folder = GetTargetFolder(file.Item);
                    if (!String.IsNullOrEmpty(Folder))
                    {
                        file.MoveTo(String.Format("{0}/{1}", Folder, newFileName));
                    }
                    file.Item.SystemUpdate(false);
                }
                this.ResetItemContext();
                this.itemContext = SPContext.GetContext(HttpContext.Current, this.itemId, list.ID, list.ParentWeb);
                this.OnFileUploaded();
                return(true);
            }
        }
        return(false);
    }
Exemple #7
0
        void context_PostAcquireRequestState(object sender, EventArgs e)
        {
            // get required contexts
            SPHttpApplication application = (SPHttpApplication)sender;
            HttpContext       context     = application.Context;
            HttpSessionState  session     = context.Session;

            if (session == null)
            {
                return;
            }
            if (session["TPL"] != null)
            {
                return;
            }
            // get SharePoint context and current SPWeb.
            SPContext sharepointContext = SPContext.GetContext(context);
            SPWeb     currentWeb        = sharepointContext.Web;
            // build a url to the redirect page.
            string layoutsFolder =
                SPUtility.GetLayoutsFolder(currentWeb);
            string url = string.Format("{0}/{1}{2}{3}", currentWeb.Url, layoutsFolder, LAYOUTS_SUBFOLDER, START_PAGE);

            // prevent redirection loop
            if (context.Request.Url.AbsoluteUri.Equals(url, StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }
            SPUtility.Redirect(url, SPRedirectFlags.Trusted, context);
        }
        public void CanSetAndGetValues()
        {
            SPSite    spSite    = new SPSite("http://localhost:9001/sites/pssportal");
            SPContext spContext = SPContext.GetContext(spSite.RootWeb);

            Isolate.WhenCalled(() => SPContext.Current.Site).WillReturn(spSite);
            Isolate.WhenCalled(() => SPContext.Current).WillReturn(spContext);

            //Set Values at levels of hierarchy
            HierarchicalConfig target1 = new HierarchicalConfig();

            target1.SetInPropertyBag("IntegrationTest-FarmLevelKey", "FarmLevelValue", new SPFarmPropertyBag());
            target1.SetInPropertyBag("IntegrationTest-WebAppLevelKey", "WebAppLevelValue", new SPWebAppPropertyBag());
            target1.SetInPropertyBag("IntegrationTest-SiteLevelKey", "SiteLevelValue", new SPSitePropertyBag());
            target1.SetInPropertyBag("IntegrationTest-WebLevelKey", "WebLevelValue", new SPWebPropertyBag());

            HierarchicalConfig target2 = new HierarchicalConfig();

            Assert.AreEqual("FarmLevelValue", target2.GetByKey <string>("IntegrationTest-FarmLevelKey"));
            Assert.AreEqual("WebAppLevelValue", target2.GetByKey <string>("IntegrationTest-WebAppLevelKey"));
            Assert.AreEqual("SiteLevelValue", target2.GetByKey <string>("IntegrationTest-SiteLevelKey"));
            Assert.AreEqual("WebLevelValue", target2.GetByKey <string>("IntegrationTest-WebLevelKey"));

            Assert.AreEqual("FarmLevelValue", SPFarm.Local.Properties["IntegrationTest-FarmLevelKey"]);
            Assert.AreEqual("WebAppLevelValue", SPContext.Current.Site.WebApplication.Properties["IntegrationTest-WebAppLevelKey"]);
            Assert.AreEqual("SiteLevelValue", SPContext.Current.Site.RootWeb.AllProperties["IntegrationTest-SiteLevelKey"]);
            Assert.AreEqual("WebLevelValue", SPContext.Current.Web.AllProperties["IntegrationTest-WebLevelKey"]);
        }
Exemple #9
0
        internal void AddListFormWebPart(IDictionary action, int itemID)
        {
            SPList          list;
            SPListItem      item;
            ListFormWebPart lfwp;

            try {
                list = web.Lists [new Guid(Request.QueryString ["l"])];
                PhVals ["List_Title"] = list.Title;
                if (string.IsNullOrEmpty(Title))
                {
                    Title = list.Title;
                }
                item = list.GetItemById(itemID);
                string itemTitle = ProductPage.GetListItemTitle(item, false);
                PhVals ["Context_Title"] = PhVals ["Item_Title"] = itemTitle;
                if ((!string.IsNullOrEmpty(itemTitle)) && (itemTitle != Title))
                {
                    Title = ((string.IsNullOrEmpty(Title) ? string.Empty : (Title + " - ")) + (string.IsNullOrEmpty(itemTitle) ? ("#" + item.ID) : itemTitle));
                }
                InitWebPart(lfwp = new ListFormWebPart());
                lfwp.ControlMode = SPControlMode.Display;
                lfwp.FormType    = 4;
                lfwp.ItemContext = SPContext.GetContext(Context, itemID, list.ID, web);
                lfwp.ListName    = ProductPage.GuidBracedUpper(list.ID);
                lfwp.ListItemId  = itemID;
                lfwp.Toolbar     = "None";
                MainWebPart.Controls.Add(lfwp);
                PhVals ["WebPart_Title"] = lfwp.DisplayTitle;
            } catch (Exception ex) {
                Errors.Add(ex);
            }
        }
        public void CanSetValueAndOverrideAtLowerLevel()
        {
            SPSite    spSite    = new SPSite("http://localhost:9001/sites/pssportal");
            SPContext spContext = SPContext.GetContext(spSite.RootWeb);

            Isolate.WhenCalled(() => SPContext.Current.Site).WillReturn(spSite);
            Isolate.WhenCalled(() => SPContext.Current).WillReturn(spContext);

            //Set Values at levels of hierarchy
            HierarchicalConfig target = new HierarchicalConfig();

            target.SetInPropertyBag("IntegrationTest-FarmLevelKey", "FarmLevelValue", new SPFarmPropertyBag());
            Assert.AreEqual("FarmLevelValue", target.GetByKey <string>("IntegrationTest-FarmLevelKey"));

            target.SetInPropertyBag("IntegrationTest-FarmLevelKey", "Over-riddenValue1", new SPWebAppPropertyBag());
            Assert.AreEqual("Over-riddenValue1", target.GetByKey <string>("IntegrationTest-FarmLevelKey"));

            target.SetInPropertyBag("IntegrationTest-FarmLevelKey", "Over-riddenValue2", new SPWebAppPropertyBag());
            Assert.AreEqual("Over-riddenValue2", target.GetByKey <string>("IntegrationTest-FarmLevelKey"));

            target.SetInPropertyBag("IntegrationTest-FarmLevelKey", "Over-riddenValue3", new SPSitePropertyBag());
            Assert.AreEqual("Over-riddenValue3", target.GetByKey <string>("IntegrationTest-FarmLevelKey"));

            target.SetInPropertyBag("IntegrationTest-FarmLevelKey", "Over-riddenValue4", new SPWebPropertyBag());
            Assert.AreEqual("Over-riddenValue4", target.GetByKey <string>("IntegrationTest-FarmLevelKey"));
        }
Exemple #11
0
        /// <summary>
        /// No SPContext available...
        /// </summary>
        /// <param name="dependencyResolver"></param>
        private static void SignalRScaleOutDatabase(ref IDependencyResolver dependencyResolver)
        {
            Guid   siteId = SPContext.GetContext(HttpContext.Current).Site.ID;//.Current.Site.ID;
            string key    = "ClubCloudService_SignalR";
            string value  = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSiteCollection = new SPSite(siteId))
                {
                    using (SPWeb currentWeb = currentSiteCollection.OpenWeb())
                    {
                        currentWeb.AllowUnsafeUpdates = true;



                        if (!currentWeb.AllProperties.ContainsKey(key))
                        {
                            ClubCloudServiceClient client = new ClubCloudServiceClient(SPServiceContext.Current);
                            value = client.ScaleOutConnection(key);
                            currentWeb.Properties.Add(key, value);
                            currentWeb.Properties.Update();
                        }
                        else
                        {
                            value = currentWeb.AllProperties[key].ToString();
                            SqlConnectionStringBuilder builder = null;
                            using (SqlConnection connection = new SqlConnection(value))
                            {
                                builder = new SqlConnectionStringBuilder(connection.ConnectionString);

                                if (!builder.InitialCatalog.Equals(key, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    ClubCloudServiceClient client = new ClubCloudServiceClient(SPServiceContext.Current);
                                    value = client.ScaleOutConnection(key);
                                    currentWeb.AllProperties[key] = value;
                                    currentWeb.Properties.Update();
                                }
                            }
                        }

                        currentWeb.AllowUnsafeUpdates = false;
                    }
                }
            });

            if (string.IsNullOrWhiteSpace(value))
            {
                dependencyResolver.UseSqlServer(value);
            }
        }
        protected override void CreateChildControls()
        {
            buildParams();

            if (SPContext.Current.ViewContext.View != null)
            {
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingleInit", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
                try
                {
                    typeof(ListTitleViewSelectorMenu).GetField("m_wpSingle", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Page.FindControl("ctl00$PlaceHolderPageTitleInTitleArea$ctl01$ctl00").Controls[1], true);
                }
                catch { }
            }

            EnsureChildControls();

            EPMLiveCore.Act act = new EPMLiveCore.Act(web);
            activation = act.CheckFeatureLicense(EPMLiveCore.ActFeature.WebParts);
            if (activation != 0)
            {
                return;
            }

            try
            {
                toolbar = new ViewToolBar();
                toolbar.EnableViewState = false;

                list = SPContext.Current.List;
                view = SPContext.Current.ViewContext.View;

                SPContext context = SPContext.GetContext(this.Context, view.ID, list.ID, web);
                toolbar.RenderContext = context;

                Controls.Add(toolbar);
            }
            catch { }
        }
Exemple #13
0
        public VideoSettings Load()
        {
            if (SPContext.Current != null)
            {
                _context = SPContext.Current;
                Load(SPContext.Current.Site);
            }
            else
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    if (_context != null)
                    {
                        _context = SPContext.GetContext(context);
                    }

                    SPSite site = Context.Site;// (context.Request.Url.ToString());
                    Load(site);
                }
            }

            return(this);
        }
Exemple #14
0
        /// <summary>
        /// Generates the form containing all the fields
        /// </summary>
        private void LoadForm()
        {
            try
            {
                using (new SPMonitoredScope("SP2010 BatchEdit Get Fields (and default values)"))
                {
                    string webId  = Request["web"];
                    string listId = Request["source"];

                    using (SPWeb web = SPContext.Current.Site.OpenWeb(new Guid(webId)))
                    {
                        SPList list = web.Lists[new Guid(listId)];

                        foreach (SPField field in list.Fields)
                        {
                            if (field.ShowInNewForm.GetValueOrDefault(true) && field.FieldRenderingControl != null && (field.ShowInEditForm ?? field.CanBeDisplayedInEditForm))
                            {
                                string lblText = field.Title;
                                if (field.Required)
                                {
                                    lblText += " *";
                                }

                                pnlFields.Controls.Add(new System.Web.UI.WebControls.Label {
                                    Text = lblText
                                });
                                pnlFields.Controls.Add(new Literal {
                                    Text = "<br/>"
                                });

                                try
                                {
                                    if (!field.FieldRenderingControl.GetType().Equals(typeof(TaxonomyFieldControl)))
                                    {
                                        BaseFieldControl editControl = field.FieldRenderingControl;
                                        editControl.ID = "fld_" + field.Id.ToString().Replace("-", "_"); // fix for Lookup picker
                                        Trace.Write(field.Id.ToString());
                                        editControl.ControlMode   = SPControlMode.New;
                                        editControl.ListId        = list.ID;
                                        editControl.FieldName     = field.InternalName;
                                        editControl.RenderContext = SPContext.GetContext(HttpContext.Current, list.DefaultView.ID, list.ID, web);

                                        pnlFields.Controls.Add(editControl);
                                    }

                                    else
                                    {
                                        var session = new TaxonomySession(field.ParentList.ParentWeb.Site);

                                        var taxonomyControl = new TaxonomyWebTaggingControl
                                        {
                                            IsMulti    = true,
                                            IsAddTerms = true,
                                            ID         = "fld_" + field.Id,
                                            FieldName  = field.Title,
                                            FieldId    = field.Id.ToString()
                                        };

                                        taxonomyControl.TermSetId.Add(session.TermStores[0].Id);
                                        taxonomyControl.SSPList     = ((TaxonomyField)field).SspId.ToString();
                                        taxonomyControl.AnchorId    = ((TaxonomyField)field).AnchorId;
                                        taxonomyControl.TermSetList = ((TaxonomyField)field).TermSetId.ToString();
                                        pnlFields.Controls.Add(taxonomyControl);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    SPCriticalTraceCounter.AddDataToScope(66, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
                                }

                                pnlFields.Controls.Add(new Literal {
                                    Text = "<br/><br/>"
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SPCriticalTraceCounter.AddDataToScope(66, "SP2010 BatchEdit", 1, ex.Message + ": " + ex.StackTrace);
            }
        }
        void WebSiteControllerModule_OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            application = sender as HttpApplication;

            string absolutePath = application.Request.Url.AbsolutePath.ToLower();

            if (absolutePath.Contains(".dll") ||
                absolutePath.Contains(".asmx") ||
                absolutePath.Contains(".svc") ||
                absolutePath.Contains(".axd") ||
                absolutePath.Contains(".ashx") ||
                absolutePath.Contains("favicon.ico"))
            {
                return;
            }

            HttpContext context = HttpContext.Current;

            /*
             * bool IsA = false;
             * if (context != null && context.User != null)
             * {
             *  IsA = context.User.Identity.IsAuthenticated;
             * }
             */

            SPContext _current = SPContext.Current;

            if (context != null && _current == null)
            {
                try
                {
                    if (!context.Request.FilePath.Contains("/_"))
                    {
                        _current = SPContext.GetContext(context);
                    }
                }
                catch { };
            }

            try
            {
                if (_current != null)
                {
                    bool          IsAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
                    SPControlMode mode            = _current.FormContext.FormMode;
                    bool          isMode          = (mode == SPControlMode.Display || mode == SPControlMode.Invalid);

                    if (!IsAuthenticated && isMode)
                    {
                        bool isPage        = Hemrika.SharePresence.WebSite.Page.WebSitePage.IsWebSitePage(_current.ListItem);
                        bool isContentType = contentTypeFilter.IsMatch(context.Response.ContentType);
                        bool isMethod      = (context.Request.HttpMethod == "GET");

                        if (isMethod && isContentType && IsCompressionSupported(context))
                        {
                            //context.Items["filter"] = context.Response.Filter;
                            //WebPageProcessor.Compress(context);
                        }


                        //context.Response.Filter = new WebPageScriptFilter(context.Response);
                        //context.Response.Filter = new WebPageViewStateFilter(context.Response);
                        //context.Response.Filter = new WebPageWhiteSpaceFilter(context.Response);
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
Exemple #16
0
        private void UpdateFileInformation(SPFile file)
        {
            string extension = Path.GetExtension(file.Name);

            if (extension != ".jpg" && extension != ".png" && extension != ".vtt")
            {
                string guiID      = file.UniqueId.ToString();
                string tempfile   = file.Name.Replace(file.Item.DisplayName, guiID);
                string tempvideo  = string.Empty;
                string tempPoster = string.Empty;

                SPContext context = SPContext.Current;

                if (context == null)
                {
                    context = SPContext.GetContext(file.Web);
                }

                FFMpegProcessWrapper wrapper    = new FFMpegProcessWrapper(context);
                FileSystemWrapper    filesystem = new FileSystemWrapper();

                if (!filesystem.DirectoryExists(wrapper.settings.InputVideoPath))
                {
                    filesystem.CreateDirectory(wrapper.settings.InputVideoPath);
                }

                bool Isnew = false;

                if (filesystem.DirectoryExists(wrapper.settings.InputVideoPath))
                {
                    tempvideo = Path.Combine(wrapper.settings.InputVideoPath, tempfile);

                    if (!filesystem.FileExists(tempvideo))
                    {
                        filesystem.CreateFile(tempvideo);
                        Isnew = true;
                    }

                    if (Isnew)
                    {
                        Stream filestream = file.OpenBinaryStream();
                        filesystem.DemandFileIOPermission(System.Security.Permissions.FileIOPermissionAccess.AllAccess, tempvideo);
                        filesystem.WriteStreamToFile(filestream, tempvideo);
                        filestream.Flush();
                        filestream.Close();
                    }
                }

                SPSecurity.RunWithElevatedPrivileges(
                    delegate()
                {
                    if (Isnew)
                    {
                        VideoFile video    = new VideoFile(tempvideo);
                        video.UniqueId     = file.UniqueId;
                        video.infoGathered = false;

                        try
                        {
                            wrapper.GetVideoInfo(video);

                            if (video.infoGathered)
                            {
                                try
                                {
                                    file.Item[BuildFieldId.Audio_Format]     = video.AudioFormat;
                                    file.Item[BuildFieldId.Content_Bitrate]  = video.BitRate;
                                    file.Item[BuildFieldId.Content_Duration] = video.Duration.TotalMinutes;
                                    file.Item[BuildFieldId.Content_Height]   = video.Height;
                                    file.Item[BuildFieldId.Content_Width]    = video.Width;
                                    file.Item[BuildFieldId.Video_Format]     = video.VideoFormat;
                                    file.Item.SystemUpdate(false);
                                }
                                catch (Exception ex)
                                {
                                    ex.ToString();
                                }
                            }

                            wrapper.GetVideoPoster(video);

                            try
                            {
                                tempPoster = tempvideo.Replace(Path.GetExtension(tempvideo), ".jpg");

                                while (!filesystem.FileExists(tempPoster))
                                {
                                    Thread.Sleep(1000);
                                }

                                if (filesystem.FileExists(tempPoster))
                                {
                                    Stream posterStream = null;

                                    try
                                    {
                                        posterStream = filesystem.FileOpenRead(tempPoster);

                                        if (posterStream != null)
                                        {
                                            string PosterFile = file.Item.DisplayName + ".jpg";
                                            if (PosterFile.IndexOf('-') > -1)
                                            {
                                                PosterFile = PosterFile.Split(new char[1] {
                                                    '-'
                                                })[0].ToString();
                                            }

                                            SPFile poster = null;

                                            try
                                            {
                                                poster = file.ParentFolder.Files[PosterFile];
                                            }
                                            catch (Exception ex)
                                            {
                                                ex.ToString();
                                                poster = null;
                                            }

                                            if (poster == null)
                                            {
                                                poster = file.ParentFolder.Files.Add(PosterFile, posterStream, true);
                                                poster.Update();

                                                poster.Item[SPBuiltInFieldId.ContentTypeId] = ContentTypes.ContentTypeId.Video;

                                                if (video.infoGathered)
                                                {
                                                    poster.Item[BuildFieldId.Content_Buffer]   = wrapper.settings.Buffer;
                                                    poster.Item[BuildFieldId.Content_AutoPlay] = wrapper.settings.AutoPlay;
                                                    poster.Item[BuildFieldId.Content_Loop]     = wrapper.settings.Loop;
                                                    poster.Item[BuildFieldId.Audio_Format]     = video.AudioFormat;
                                                    poster.Item[BuildFieldId.Content_Bitrate]  = video.BitRate;
                                                    poster.Item[BuildFieldId.Content_Duration] = video.Duration.TotalMinutes;
                                                    poster.Item[BuildFieldId.Content_Height]   = video.Height;
                                                    poster.Item[BuildFieldId.Content_Width]    = video.Width;
                                                    poster.Item[BuildFieldId.Video_Format]     = video.VideoFormat;
                                                }
                                                poster.Item.SystemUpdate(false);
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.ToString();
                                    }
                                    finally
                                    {
                                        if (posterStream != null)
                                        {
                                            posterStream.Flush();
                                            posterStream.Close();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ex.ToString();
                            }
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                        }
                        finally
                        {
                            try
                            {
                                if (!string.IsNullOrEmpty(tempvideo))
                                {
                                    filesystem.DemandFileIOPermission(System.Security.Permissions.FileIOPermissionAccess.AllAccess, tempvideo);
                                    filesystem.DeleteFile(tempvideo);
                                }
                                if (!string.IsNullOrEmpty(tempPoster))
                                {
                                    filesystem.DemandFileIOPermission(System.Security.Permissions.FileIOPermissionAccess.AllAccess, tempPoster);
                                    filesystem.DeleteFile(tempPoster);
                                }
                            }
                            catch (Exception ex)
                            {
                                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(ex.Source, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, ex.Message, ex.Data);
                            }
                        }
                    }
                });
            }
        }
        /*
         * private SPListItem _Author;
         *
         * public SPListItem Author
         * {
         *  get { return _Author; }
         *  set { _Author = value; }
         * }
         *
         * private SPListItem _Editor;
         *
         * public SPListItem Editor
         * {
         *  get { return _Editor; }
         *  set { _Editor = value; }
         * }
         */
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            try
            {
                SPContext _current = SPContext.Current;

                if (_current == null)
                {
                    _current = SPContext.GetContext(HttpContext.Current);
                }

                settings = new MetaDataSettings();
                settings = settings.Load(_current.Site);

                facebook = new FaceBookSettings();
                facebook = facebook.Load(_current.Site);

                twitter = new TwitterSettings();
                twitter = twitter.Load(_current.Site);

                listItem = _current.ListItem;

                /*
                 * try
                 * {
                 *  SPSecurity.RunWithElevatedPrivileges(delegate()
                 *  {
                 *      SPList userList = _current.Site.RootWeb.SiteUserInfoList;
                 *
                 *      if (userList != null && listItem != null)
                 *      {
                 *          SPFieldUserValue userValue = new SPFieldUserValue(_current.Web, listItem[SPBuiltInFieldId.Editor].ToString());
                 *          SPUser editor = userValue.User;
                 *          Editor = userList.Items.GetItemById(editor.ID);
                 *
                 *          userValue = new SPFieldUserValue(_current.Web, listItem[SPBuiltInFieldId.Author].ToString());
                 *          SPUser author = userValue.User;
                 *          Author = userList.Items.GetItemById(editor.ID);
                 *      }
                 *  });
                 * }
                 * catch { }
                 */

                GetMetaFields();

                if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    UpdateMetaFields();
                }


                if (_current.List == null)
                {
                    HtmlMeta compatible = new HtmlMeta();
                    compatible.HttpEquiv = "X-UA-Compatible";
                    compatible.Content   = "IE=edge,chrome=1";
                    this.Control.Controls.Add(compatible);
                    this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                }
                else
                {
                    string editform = _current.List.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl;
                    //string editdialogform = SPContext.Current.List.Forms[PAGETYPE.PAGE_EDITFORMDIALOG].ServerRelativeUrl;
                    string newform = _current.List.Forms[PAGETYPE.PAGE_NEWFORM].ServerRelativeUrl;
                    //string newdialogform = SPContext.Current.List.Forms[PAGETYPE.PAGE_NEWFORMDIALOG].ServerRelativeUrl;

                    bool isEdit = Page.Request.Url.OriginalString.Contains(editform);
                    bool isNew  = Page.Request.Url.OriginalString.Contains(newform);

                    bool isSharePresence = false;
                    if (listItem != null && listItem.ContentType != null && listItem.ContentType.Id.IsChildOf(ContentTypeId.PageTemplate))
                    {
                        isSharePresence = true;
                    }

                    if (isSharePresence)
                    {
                        this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                        this.Control.Controls.Add(new LiteralControl("<!-- Managed MetaData -->"));
                        this.Control.Controls.Add(new LiteralControl(Environment.NewLine));

                        HtmlMeta compatible = new HtmlMeta();
                        compatible.HttpEquiv = "X-UA-Compatible";

                        DisplayControlModes modes = WebSitePage.DetermineDisplayControlModes();

                        if (modes.displayMode == SPControlMode.Display && (!isNew && !isEdit))
                        {
                            //compatible.Content = "IE=10";
                            compatible.Content = "IE=edge,chrome=1";
                        }
                        else
                        {
                            if (isNew && isEdit)
                            {
                                compatible.Content = "IE=8";
                            }
                            else
                            {
                                compatible.Content = "IE=edge,chrome=1";
                            }
                        }


                        this.Control.Controls.Add(compatible);
                        this.Control.Controls.Add(new LiteralControl(Environment.NewLine));

                        /*
                         * string googleId = Editor["Google_x0020_Id"] as string;
                         * string twitterId = Editor["Twitter_x0020_Id"] as string;
                         * string linkedinId = Editor["LinkedIn_x0020_Id"] as string;
                         * string facebookId = Editor["FaceBook_x0020_Id"] as string;
                         */

                        if (SPContext.Current.FormContext.FormMode == SPControlMode.Display)
                        {
                            if (settings.UseMSNBotDMOZ)
                            {
                                HtmlMeta msnbot = new HtmlMeta();
                                msnbot.Name    = "msnbot";
                                msnbot.Content = "NOODP";
                                this.Control.Controls.Add(msnbot);
                                this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                            }

                            /*
                             * if (!string.IsNullOrEmpty(Editor["Google_x0020_Id"] as string))
                             * {
                             *  HtmlLink googleplus = new HtmlLink();
                             *  googleplus.Attributes.Add(HtmlTextWriterAttribute.Rel.ToString().ToLower(), "author");
                             *  googleplus.Attributes.Add(HtmlTextWriterAttribute.Href.ToString().ToLower(), string.Format("https://plus.google.com/{0}/posts", Editor["Google_x0020_Id"] as string));
                             *  this.Control.Controls.Add(googleplus);
                             *  this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                             * }
                             */

                            Regex mapping = new Regex(@"\[(.*?)\]", RegexOptions.Compiled);

                            foreach (SPField oField in metafields)
                            {
                                string fieldname = SharePointWebControls.GetFieldName(oField);

                                if (listItem.Fields.ContainsField(fieldname))
                                {
                                    string value = listItem.GetFormattedValue(fieldname);// field.Title);
                                    //string value = listItem[fieldname] as string;
                                    HtmlMeta meta = new HtmlMeta();
                                    meta.Name = fieldname;

                                    if (String.IsNullOrEmpty(value))
                                    {
                                        value = oField.DefaultValue;
                                        //meta.Content = oField.DefaultValue;
                                    }
                                    else
                                    {
                                        value = value.Replace(";#", ",");
                                        //meta.Content = value;
                                    }

                                    if (!string.IsNullOrEmpty(value) && mapping.IsMatch(value))
                                    {
                                        string shallow = value.ToString();

                                        foreach (Match match in mapping.Matches(shallow))
                                        {
                                            string field  = match.Value;
                                            string sfield = field.Trim(new char[2] {
                                                '[', ']'
                                            });

                                            if (listItem.Fields.ContainsField(sfield))
                                            {
                                                //string fieldvalue = listItem.GetFormattedValue(sfield);
                                                string fieldvalue = listItem[sfield] as string;


                                                if (string.IsNullOrEmpty(fieldvalue))
                                                {
                                                    try
                                                    {
                                                        SPField internalfield = listItem.Fields.GetFieldByInternalName(sfield);
                                                        if (internalfield != null)
                                                        {
                                                            fieldvalue = internalfield.DefaultValue as string;
                                                        }

                                                        //fieldvalue = listItem.Fields[sfield].DefaultValue;
                                                    }
                                                    catch { }
                                                }

                                                if (sfield.ToLower().Contains("author") || sfield.ToLower().Contains("editor") || sfield.ToLower().Contains("publisher"))
                                                {
                                                    /*
                                                     * if (sfield.ToLower().Contains("author"))
                                                     * {
                                                     *  fieldvalue = Author["Title"] as string;
                                                     * }
                                                     * else
                                                     * {
                                                     *  fieldvalue = Editor["Title"] as string;
                                                     * }
                                                     */
                                                    /*
                                                     * string[] sections = fieldvalue.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                                                     * if (sections.Length > 1)
                                                     * {
                                                     *  fieldvalue = sections[1];
                                                     * }
                                                     */
                                                    //meta.Content = value;
                                                }

                                                if (sfield.ToLower().Contains("html5"))
                                                {
                                                    if (sfield.ToLower().Contains("image"))
                                                    {
                                                        HTML5Image      image  = listItem.Fields.GetFieldByInternalName(sfield) as HTML5Image;
                                                        HTML5ImageField ifield = new HTML5ImageField(image.FieldRenderingControl.Value.ToString());
                                                        fieldvalue = listItem.Web.Site.Url + "/" + ifield.Src;
                                                    }

                                                    if (sfield.ToLower().Contains("header"))
                                                    {
                                                        HTML5Header      header = listItem.Fields.GetFieldByInternalName(sfield) as HTML5Header;
                                                        HTML5HeaderField ifield = new HTML5HeaderField(header.FieldRenderingControl.Value.ToString());
                                                        fieldvalue = ifield.Text;
                                                    }

                                                    if (sfield.ToLower().Contains("footer"))
                                                    {
                                                        HTML5Footer      footer = listItem.Fields.GetFieldByInternalName(sfield) as HTML5Footer;
                                                        HTML5FooterField ifield = new HTML5FooterField(footer.FieldRenderingControl.Value.ToString());
                                                        fieldvalue = ifield.Text;
                                                    }

                                                    if (sfield.ToLower().Contains("video"))
                                                    {
                                                        HTML5Video      video  = listItem.Fields.GetFieldByInternalName(sfield) as HTML5Video;
                                                        HTML5VideoField ifield = new HTML5VideoField(video.FieldRenderingControl.Value.ToString());
                                                        fieldvalue = listItem.Web.Site.Url + "/" + ifield.Src;
                                                    }

                                                    //fieldvalue = fieldvalue.Replace("//", "/");
                                                }

                                                value = value.Replace(field, fieldvalue);
                                            }

                                            /*
                                             * if (sfield.Contains("Twitter_x0020_Id"))
                                             * {
                                             *  value = Editor["Twitter_x0020_Id"] as string;
                                             * }
                                             *
                                             * if (sfield.Contains("Google_x0020_Id"))
                                             * {
                                             *  value = Editor["Google_x0020_Id"] as string;
                                             * }
                                             *
                                             * if (sfield.Contains("FaceBook_x0020_Id"))
                                             * {
                                             *  value = Editor["FaceBook_x0020_Id"] as string;
                                             * }
                                             *
                                             * if (sfield.Contains("LinkedIn_x0020_Id"))
                                             * {
                                             *  value = Editor["LinkedIn_x0020_Id"] as string;
                                             * }
                                             */

                                            if (sfield.ToLower().Contains("site"))
                                            {
                                                value = listItem.Web.Site.Url + "/";
                                            }

                                            if (sfield.ToLower().Contains("url"))
                                            {
                                                value = HttpContext.Current.Request.Url.OriginalString;
                                                //value = listItem.Web.Site.Url + "/" + listItem.Url;
                                            }
                                        }
                                    }

                                    meta.Content = value;

                                    if (fieldname == "keywords")
                                    {
                                        if (settings.AutoKeywords)
                                        {
                                            if (String.IsNullOrEmpty(value))
                                            {
                                                value = String.Empty;
                                            }

                                            meta.Content += GetAutoKeywords(value);
                                        }
                                    }

                                    if (fieldname == "language" && settings.UseSiteLanguage)
                                    {
                                        CultureInfo cult = new CultureInfo((int)SPContext.Current.Web.RegionalSettings.LocaleId);
                                        //CultureInfo cult = new CultureInfo((int)SPContext.Current.Web.Language);
                                        meta.Content = cult.DisplayName.ToLower();

                                        HtmlMeta equiv = new HtmlMeta();
                                        equiv.HttpEquiv = "content-language";
                                        equiv.Content   = cult.Name;

                                        this.Control.Controls.Add(equiv);
                                        this.Control.Controls.Add(new LiteralControl(Environment.NewLine));

                                        equiv           = new HtmlMeta();
                                        equiv.HttpEquiv = "language";
                                        equiv.Content   = cult.Name;

                                        this.Control.Controls.Add(equiv);
                                        this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                                    }

                                    /*
                                     * if (fieldname == "author" && settings.AuthorOverride != Authors.NoOverride)
                                     * {
                                     *  value = listItem[settings.AuthorOverride.ToString()] as string;
                                     *  meta.Content = value;
                                     * }
                                     *
                                     * if (fieldname == "web_author" && settings.WebAuthorOverride != Authors.NoOverride)
                                     * {
                                     *  value = listItem[settings.AuthorOverride.ToString()] as string;
                                     *  meta.Content = value;
                                     * }
                                     */

                                    this.Control.Controls.Add(meta);
                                    this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                                }
                            }
                            this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                        }
                        else
                        {
                            HtmlMeta pragma = new HtmlMeta();
                            pragma.HttpEquiv = "Pragma";
                            pragma.Content   = "no-cache";
                            this.Control.Controls.Add(pragma);
                            this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                            HtmlMeta expires = new HtmlMeta();
                            expires.HttpEquiv = "Expires";
                            expires.Content   = "-1";
                            this.Control.Controls.Add(expires);
                            this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                            HtmlMeta store = new HtmlMeta();
                            store.HttpEquiv = "Cache-Control";
                            store.Content   = "no-store, no-cache, must-revalidate";
                            this.Control.Controls.Add(store);
                            this.Control.Controls.Add(new LiteralControl(Environment.NewLine));

                            HtmlMeta post = new HtmlMeta();
                            post.HttpEquiv = "Cache-Control";
                            post.Content   = "post-check=0, pre-check=0";
                            this.Control.Controls.Add(post);
                            this.Control.Controls.Add(new LiteralControl(Environment.NewLine));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
Exemple #18
0
        /// <summary>
        /// Open the page layout.
        /// </summary>
        /// <returns></returns>
        public override Stream Open()
        {
            bool        authenticated = false;// HttpContext.Current.User.Identity.IsAuthenticated;
            SPContext   spcontext     = null;
            HttpContext context       = null;

            if (HttpContext.Current != null)
            {
                context       = HttpContext.Current;
                authenticated = HttpContext.Current.User.Identity.IsAuthenticated;

                if (SPContext.Current == null)
                {
                    spcontext = SPContext.GetContext(HttpContext.Current);
                }
                else
                {
                    spcontext = SPContext.Current;
                }
            }

            if (context == null && spcontext == null)
            {
                throw (new HttpException((int)HttpStatusCode.NotFound, this.VirtualPath));
            }

            Stream stream = new MemoryStream();


            //SPSite site = new SPSite(spcontext.Web.Url);
            using (SPSite site = new SPSite(spcontext.Web.Url))
            {
                bool found = false;
                //SPWeb web = site.OpenWeb(this.VirtualPath);
                using (SPWeb web = site.OpenWeb(this.VirtualPath))
                {
                    found = web.Exists;
                    if (found)
                    {
                        GetFileContents(authenticated, stream, context, site, web);
                    }
                }


                if (!found)
                {
                    if (this.VirtualPath.StartsWith("/_"))
                    {
                        using (SPWeb web = site.RootWeb)
                        {
                            found = web.Exists;
                            if (found)
                            {
                                GetFileContents(authenticated, stream, context, site, web);
                            }
                        }
                    }
                    else
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            found = web.Exists;
                            if (found)
                            {
                                GetFileContents(authenticated, stream, context, site, web);
                            }
                        }
                    }

                    if (!found)
                    {
                        using (SPWeb web = site.RootWeb)
                        {
                            found = web.Exists;
                            if (found)
                            {
                                GetFileContents(authenticated, stream, context, site, web);
                            }
                        }
                    }
                }


                //});

                if (stream != null)
                {
                    return(stream);
                }
                else
                {
                    throw (new HttpException((int)HttpStatusCode.NoContent, ""));
                }
            }
            #endregion
        }
Exemple #19
0
        private void AddFormControl(SPField field, SPListItem listItem, SPList list, SPWeb spWeb)
        {
            // our table row
            HtmlTableRow  newRow      = new HtmlTableRow();
            HtmlTableCell lblCell     = new HtmlTableCell();
            HtmlTableCell controlCell = new HtmlTableCell();

            // our form control types
            TaxonomyWebTaggingControl taxonomyControl = null;
            BaseFieldControl          webControl      = null;
            DateTimeControl           dateTimeControl = null;

            using (SPSite site = list.ParentWeb.Site)
            {
                using (SPWeb web = site.OpenWeb(spWeb.ID))
                {
                    if (field.FieldRenderingControl != null && !skipField(field))
                    {
                        //add our label to the table
                        System.Web.UI.WebControls.Label newLabel = new System.Web.UI.WebControls.Label();
                        newLabel.Width = Unit.Pixel(150);
                        newLabel.Text  = field.Title;
                        lblCell.Controls.Add(newLabel);
                        newRow.Cells.Add(lblCell);

                        try
                        {
                            switch (field.FieldRenderingControl.GetType().Name)
                            {
                            case ("DateTimeField"):
                                dateTimeControl          = new DateTimeControl();
                                dateTimeControl.DateOnly = true;
                                dateTimeControl.ID       = string.Format("ctrl_{0}", field.InternalName);
                                break;

                            case ("TaxonomyFieldControl"):
                                TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site);
                                var             store   = session.TermStores[0];

                                taxonomyControl            = new TaxonomyWebTaggingControl();
                                taxonomyControl.IsMulti    = true;
                                taxonomyControl.IsAddTerms = true;
                                taxonomyControl.TermSetId.Add(session.TermStores[0].Id);
                                taxonomyControl.ID          = string.Format("ctrl_{0}", field.InternalName);
                                taxonomyControl.FieldName   = field.Title;
                                taxonomyControl.FieldId     = field.Id.ToString();
                                taxonomyControl.SSPList     = ((TaxonomyField)field).SspId.ToString();
                                taxonomyControl.AnchorId    = ((TaxonomyField)field).AnchorId;
                                taxonomyControl.TermSetList = ((TaxonomyField)field).TermSetId.ToString();
                                break;

                            default:
                                webControl             = field.FieldRenderingControl;
                                webControl.ID          = string.Format("ctrl_{0}", field.InternalName);
                                webControl.ControlMode = SPControlMode.New;
                                webControl.ListId      = list.ID;
                                webControl.FieldName   = field.InternalName;
                                SPContext Context = SPContext.GetContext(HttpContext.Current, list.Items.GetItemById(listItem.ID).ID, list.ID, web);
                                webControl.RenderContext = Context;
                                webControl.ItemContext   = Context;
                                break;
                            }

                            //add our new row with controls to our placeholder
                            phDynamicFormControls.Controls.Add(newRow);
                            // add the cell into our row
                            newRow.Cells.Add(controlCell);
                            // add the row to the table
                            phDynamicFormControls.Controls.Add(newRow);
                            if (webControl != null)
                            {
                                controlCell.Controls.Add(webControl);
                            }
                            else if (taxonomyControl != null)
                            {
                                controlCell.Controls.Add(taxonomyControl);
                            }
                            else if (dateTimeControl != null)
                            {
                                controlCell.Controls.Add(dateTimeControl);
                            }
                        }
                        catch (Exception ex)
                        { }
                    }
                }
            }
        }
        /// <summary>
        /// Returns an instance of a class that implements the <see cref="T:System.Web.IHttpHandler"></see> interface.
        /// </summary>
        /// <param name="context">An instance of the <see cref="T:System.Web.HttpContext"></see> class that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        /// <param name="requestType">The HTTP data transfer method (GET or POST) that the client uses.</param>
        /// <param name="url">The <see cref="P:System.Web.HttpRequest.RawUrl"></see> of the requested resource.</param>
        /// <param name="pathTranslated">The <see cref="P:System.Web.HttpRequest.PhysicalApplicationPath"></see> to the requested resource.</param>
        /// <returns>
        /// A new <see cref="T:System.Web.IHttpHandler"></see> object that processes the request.
        /// </returns>
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            // First of all we want to check what a request is running. There are three different
            // requests that are made to this handler:
            //		1) GET core,prototype,converter.ashx which will include the common AJAX communication
            //		2) GET typename,assemblyname.ashx which will return the AJAX wrapper JavaScript code
            //		3) POST typename,assemblyname.ashx which will invoke a method.
            // The first two requests will return the JavaScript code or a HTTP 304 (not changed).

            string filename = Path.GetFileNameWithoutExtension(context.Request.Path);
            Type   t        = null;


            //iiunknown added @16:06 2013/11/9 增加AjaxPro客户端请求对SharePoint的SPContext.Current的支持,方便服务器端Ajax方法能正确定位到当前真正的SharePoint路径下的SPContext.Current,而不需要传递过多的参数去自己构造SharePoint上下文环境。
            #region AjaxPro请求的时候构造SPContext传递到当前上下文中。
            string siteid   = HttpContext.Current.Request.QueryString.Get("siteid");
            string webid    = HttpContext.Current.Request.QueryString.Get("webid");
            string listid   = HttpContext.Current.Request.QueryString.Get("listid");
            string itemid   = HttpContext.Current.Request.QueryString.Get("itemid");
            string lcid     = HttpContext.Current.Request.QueryString.Get("lcid");
            string formmode = HttpContext.Current.Request.QueryString.Get("formmode");
            int    lcidNum  = 2052;
            if (!string.IsNullOrEmpty(lcid))
            {
                int.TryParse(lcid, out lcidNum);
            }
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lcidNum);
            SPContext spcontext = null;
            if (!string.IsNullOrEmpty(siteid))
            {
                SPSite site = new SPSite(new Guid(siteid));
                if (site != null && !string.IsNullOrEmpty(webid))
                {
                    SPWeb web = site.OpenWeb(new Guid(webid));
                    if (web != null)
                    {
                        spcontext = SPContext.GetContext(HttpContext.Current, int.Parse(itemid), new Guid(listid), web);
                        int fm = int.Parse(formmode);
                        if (fm > 0)
                        {
                            spcontext.FormContext.FormMode = (Microsoft.SharePoint.WebControls.SPControlMode) int.Parse(formmode);
                        }
                        if (HttpContext.Current.Items["HttpHandlerSPSite"] == null)
                        {
                            HttpContext.Current.Items["HttpHandlerSPSite"] = site;
                        }
                        if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
                        {
                            HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
                        }
                    }
                    //if (string.IsNullOrEmpty(listid))
                    //{
                    //    spcontext = SPContext.GetContext(web);
                    //}
                    //else
                    //{
                    //    if (string.IsNullOrEmpty(itemid))
                    //    {
                    //        spcontext = SPContext.GetContext(HttpContext.Current, 0, new Guid(listid), web);
                    //    }
                    //    else
                    //    {
                    //        spcontext = SPContext.GetContext(HttpContext.Current, int.Parse(itemid), new Guid(listid), web);
                    //    }
                    //}
                }
            }

            if (spcontext != null)
            {
                //SharePoint获取当前上下文的方法。
                //public static SPContext GetContext(HttpContext context)
                //{
                //    if (context == null)
                //    {
                //        throw SPUtility.GetStandardArgumentNullException("context");
                //    }
                //    SPContext context2 = (SPContext) context.Items["DefaultSPContext"];
                //    if (context2 == null)
                //    {
                //        context2 = new SPContext(context, 0, Guid.Empty, null);
                //        context.Items["DefaultSPContext"] = context2;
                //        string str = DefaultKey(context, null);
                //        context.Items[str] = context2;
                //    }
                //    return context2;
                //}
                context.Items["DefaultSPContext"] = spcontext;
            }
            #endregion


            Exception typeException = null;
            bool      isInTypesList = false;

            try
            {
                if (Utility.Settings != null && Utility.Settings.UrlNamespaceMappings.Contains(filename))
                {
                    isInTypesList = true;
                    t             = Type.GetType(Utility.Settings.UrlNamespaceMappings[filename].ToString(), true);
                }

                if (t == null)
                {
                    t = Type.GetType(filename, true);
                }
            }
            catch (Exception ex)
            {
                typeException = ex;
            }

            switch (requestType)
            {
            case "GET":                 // get the JavaScript files

                switch (filename.ToLower())
                {
                case "prototype":
                    return(new EmbeddedJavaScriptHandler("prototype"));

                case "core":
                    return(new EmbeddedJavaScriptHandler("core"));

                case "ms":
                    return(new EmbeddedJavaScriptHandler("ms"));

                case "prototype-core":
                case "core-prototype":
                    return(new EmbeddedJavaScriptHandler("prototype,core"));

                case "converter":
                    return(new ConverterJavaScriptHandler());

                default:

                    if (typeException != null)
                    {
#if (WEBEVENT)
                        string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

                        Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 201, typeException);
                        ev.Raise();
#endif
                        return(null);
                    }

                    if (Utility.Settings.OnlyAllowTypesInList == true && isInTypesList == false)
                    {
                        return(null);
                    }

                    return(new TypeJavaScriptHandler(t));
                }

            case "POST":        // invoke the method

                if (Utility.Settings.OnlyAllowTypesInList == true && isInTypesList == false)
                {
                    return(null);
                }

                IAjaxProcessor[] p = new IAjaxProcessor[2];

                p[0] = new XmlHttpRequestProcessor(context, t);
                p[1] = new IFrameProcessor(context, t);

                for (int i = 0; i < p.Length; i++)
                {
                    if (p[i].CanHandleRequest)
                    {
                        if (typeException != null)
                        {
#if (WEBEVENT)
                            string errorText = string.Format(Constant.AjaxID + " Error", context.User.Identity.Name);

                            Management.WebAjaxErrorEvent ev = new Management.WebAjaxErrorEvent(errorText, WebEventCodes.WebExtendedBase + 200, typeException);
                            ev.Raise();
#endif
                            p[i].SerializeObject(new NotSupportedException("This method is either not marked with an AjaxMethod or is not available."));
                            return(null);
                        }

                        AjaxMethodAttribute[] ma = (AjaxMethodAttribute[])p[i].AjaxMethod.GetCustomAttributes(typeof(AjaxMethodAttribute), true);

                        bool useAsync = false;
                        HttpSessionStateRequirement sessionReq = HttpSessionStateRequirement.ReadWrite;

                        if (Utility.Settings.OldStyle.Contains("sessionStateDefaultNone"))
                        {
                            sessionReq = HttpSessionStateRequirement.None;
                        }

                        if (ma.Length > 0)
                        {
                            useAsync = ma[0].UseAsyncProcessing;

                            if (ma[0].RequireSessionState != HttpSessionStateRequirement.UseDefault)
                            {
                                sessionReq = ma[0].RequireSessionState;
                            }
                        }

                        switch (sessionReq)
                        {
                        case HttpSessionStateRequirement.Read:
                            if (!useAsync)
                            {
                                return(new AjaxSyncHttpHandlerSessionReadOnly(p[i]));
                            }
                            else
                            {
                                return(new AjaxAsyncHttpHandlerSessionReadOnly(p[i]));
                            }

                        case HttpSessionStateRequirement.ReadWrite:
                            if (!useAsync)
                            {
                                return(new AjaxSyncHttpHandlerSession(p[i]));
                            }
                            else
                            {
                                return(new AjaxAsyncHttpHandlerSession(p[i]));
                            }

                        case HttpSessionStateRequirement.None:
                            if (!useAsync)
                            {
                                return(new AjaxSyncHttpHandler(p[i]));
                            }
                            else
                            {
                                return(new AjaxAsyncHttpHandler(p[i]));
                            }

                        default:
                            if (!useAsync)
                            {
                                return(new AjaxSyncHttpHandlerSession(p[i]));
                            }
                            else
                            {
                                return(new AjaxAsyncHttpHandlerSession(p[i]));
                            }
                        }
                    }
                }
                break;
            }

            return(null);
        }
Exemple #21
0
        private void CreateChildControlsInternal()
        {
            if (CheckParameters())
            {
                if (_showTree)
                {
                    _folderExplorer = new FolderExplorerControl(_listGuid, _listViewGuid)
                    {
                        ExpandAll      = true,
                        FollowListView = true,
                        ID             = (ID + "fe"),
                        AutoCollapse   = false,
                        ShowCounter    = _showNumberOfItems,
                        SortHierarchy  = _sortHierarchyTree,
                        CacheService   = GetCacheService()
                    };

                    Controls.Add(_folderExplorer);
                }

                // we are using this control to check RootFolder and generate
                // upload and goback buttons
                // we can hide it but we need create this always
                _breadCrumb = new BreadCrumbControl(_listGuid, _listViewGuid)
                {
                    MaxLevels = 3
                };

                Controls.Add(_breadCrumb);

                _listViewWP = new SPSListView
                {
                    ListId          = _listGuid,
                    ViewId          = _listViewGuid,
                    EnableViewState = true,
                };

                SPWeb  web  = SPContext.Current.Web;
                SPList list = web.Lists[new Guid(_listGuid)];
                SPView view = list.Views[new Guid(_listViewGuid)];

                SPContext context = SPContext.GetContext(Context, view.ID, list.ID, web);

                _toolbar = new ViewToolBar
                {
                    RenderContext = context
                };

                CustomButtons();

                // Up Folder button

                _buttonUpFolder = new SPLinkButton
                {
                    Text     = SPSResources.GetResourceString("SPS_UpFolderButton"),
                    ImageUrl = "/_layouts/images/UPFOLDER.GIF",
                    HoverCellActiveCssClass   = "ms-buttonactivehover",
                    HoverCellInActiveCssClass = "ms-buttoninactivehover",
                    NavigateUrl     = "#",
                    EnableViewState = false
                };



                Controls.Add(_toolbar);
                Controls.Add(_listViewWP);
            }
        }
Exemple #22
0
 // Methods
 public static SPContextBase GetContext(SPWebBase web)
 {
     return(new SPContextWrapper(SPContext.GetContext(((SPWebWrapper)web).Web)));
 }
        protected override void CreateChildControls()
        {
            Act        = new Act(SPContext.Current.Web);
            Activation = Act.CheckFeatureLicense(ActFeature.Timesheets);

            if (Activation != 0)
            {
                return;
            }

            var web = SPContext.Current.Web;
            {
                try
                {
                    SpList = SPContext.Current.List;
                    View   = SPContext.Current.ViewContext.View;
                }
                catch (Exception exception)
                {
                    Trace.WriteLine(exception);
                }

                if (View != null && SpList != null)
                {
                    _viewToolbar = new ViewToolBar
                    {
                        TemplateName = "TSViewToolBar"
                    };

                    var context = SPContext.GetContext(Context, View.ID, SpList.ID, SPContext.Current.Web);
                    _viewToolbar.RenderContext = context;

                    Controls.Add(_viewToolbar);

                    foreach (Control control in _viewToolbar.Controls)
                    {
                        ProcessControls(control, FullGridId, View.ServerRelativeUrl, web);
                    }

                    _timeSheetMenu.Text             = TimeSheetText;
                    _timeSheetMenu.TemplateName     = "ToolbarPMMenu";
                    _timeSheetMenu.ToolTip          = TimeSheetText;
                    _timeSheetMenu.MenuControl.Text = TimeSheetText;
                    _timeSheetMenu.GetMenuItem("ApproveItems").ClientOnClickScript = $"approve{FullGridId}();";
                    _timeSheetMenu.GetMenuItem("RejectItems").ClientOnClickScript  = $"reject{FullGridId}();";

                    _viewToolbar.Controls[0].Controls[1].Controls[0].Controls.AddAt(6, _timeSheetMenu);

                    SPSecurity.RunWithElevatedPrivileges(
                        delegate
                    {
                        try
                        {
                            using (var sqlConnection = new SqlConnection(CoreFunctions.getConnectionString(web.Site.WebApplication.Id)))
                            {
                                sqlConnection.Open();

                                using (var sqlCommand = new SqlCommand(
                                           "SELECT * from TSPERIOD where site_id=@siteid and locked = 0 order by period_id",
                                           sqlConnection)
                                {
                                    CommandType = CommandType.Text
                                })
                                {
                                    sqlCommand.Parameters.AddWithValue("@siteid", web.Site.ID);

                                    using (var dataReader = sqlCommand.ExecuteReader())
                                    {
                                        while (dataReader.Read())
                                        {
                                            _dropDownList.Items.Add(
                                                new ListItem(
                                                    $"{dataReader.GetDateTime(1).ToShortDateString()} - {dataReader.GetDateTime(2).ToShortDateString()}",
                                                    dataReader.GetInt32(0).ToString()));
                                            Periods.Add(
                                                dataReader.GetInt32(0),
                                                $"{dataReader.GetDateTime(1).ToShortDateString()} - {dataReader.GetDateTime(2).ToShortDateString()}");
                                        }
                                    }

                                    _dropDownList.SelectedValue = Period.ToString();
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            Trace.WriteLine(exception);
                        }
                    });

                    if (Page.IsPostBack)
                    {
                        Page.Response.Cookies[EpmLiveTsPeriod].Value   = _dropDownList.SelectedValue;
                        Page.Response.Cookies[EpmLiveTsPeriod].Expires = DateTime.Now.AddMinutes(30);
                    }

                    _dropDownList.ID = "ddlPeriod";
                    _dropDownList.SelectedIndexChanged += ddl_SelectedIndexChanged;
                    _dropDownList.AutoPostBack          = true;
                    _dropDownList.EnableViewState       = true;

                    _buttonNext.Click          += btn_Click;
                    _buttonNext.ImageUrl        = "/_layouts/epmlive/images/right.gif";
                    _buttonNext.EnableViewState = true;

                    _buttonPrev.Click          += btnPrev_Click;
                    _buttonPrev.ImageUrl        = "/_layouts/epmlive/images/left.gif";
                    _buttonPrev.EnableViewState = true;

                    var pnl = new Panel();
                    pnl.Controls.Add(
                        new LiteralControl(
                            "<table border=\"0\"><tr><td class=\"ms-toolbar\" valign=\"center\"><div class=\"ms-buttoninactivehover\" onmouseover=\"this.className='ms-buttonactivehover'\" onmouseout=\"this.className='ms-buttoninactivehover'\">"));
                    pnl.Controls.Add(_buttonPrev);
                    pnl.Controls.Add(new LiteralControl("</div></td><td valign=\"center\">"));
                    pnl.Controls.Add(_dropDownList);
                    pnl.Controls.Add(
                        new LiteralControl(
                            "</td><td valign=\"center\"><div class=\"ms-buttoninactivehover\" onmouseover=\"this.className='ms-buttonactivehover'\" onmouseout=\"this.className='ms-buttoninactivehover'\">"));
                    pnl.Controls.Add(_buttonNext);
                    pnl.Controls.Add(new LiteralControl("</div></td></tr></table>"));

                    _viewToolbar.Controls[0].Controls[1].Controls[0].Controls.AddAt(7, pnl);
                }
            }
        }
        protected override void CreateChildControls()
        {
            act        = new Act(SPContext.Current.Web);
            activation = act.CheckFeatureLicense(ActFeature.ResourcePlanner);

            if (activation != 0)
            {
                return;
            }

            strAction = Page.Request["action"];

            curWeb = SPContext.Current.Web;

            {
                resUrl = CoreFunctions.getConfigSetting(curWeb, "EPMLiveResourceURL");

                if (!string.IsNullOrWhiteSpace(resUrl))
                {
                    try
                    {
                        if (!resUrl.Equals(curWeb.ServerRelativeUrl, StringComparison.OrdinalIgnoreCase))
                        {
                            if (resUrl.StartsWith("/"))
                            {
                                resWeb = curWeb.Site.OpenWeb(resUrl);
                            }
                            else
                            {
                                using (var tempSite = new SPSite(resUrl))
                                {
                                    resWeb = tempSite.OpenWeb();

                                    if (!resWeb.Url.Equals(resUrl, StringComparison.OrdinalIgnoreCase))
                                    {
                                        resWeb = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            resWeb = curWeb;
                        }

                        if (resWeb != null)
                        {
                            try
                            {
                                reslist = resWeb.Lists["Resources"];
                            }
                            catch (Exception exception)
                            {
                                DiagTrace.WriteLine(exception);
                            }

                            if (reslist == null)
                            {
                                error = "Error: Resource list was not found.";
                            }
                            else
                            {
                                resview = reslist.DefaultView;
                                var viewListBuilder = new StringBuilder();

                                foreach (SPView spView in resview.Views)
                                {
                                    if (!spView.Hidden)
                                    {
                                        viewListBuilder.Append(
                                            spView.DefaultView
                                                ? $"<option selected value=\"{spView.Title.Replace(" ", "%20")}\">{spView.Title}</option>"
                                                : $"<option value=\"{spView.Title.Replace(" ", "%20")}\">{spView.Title}</option>");
                                    }
                                }

                                viewList = viewListBuilder.ToString();

                                lnk               = new LinkButton();
                                lnk.Click        += lnk_Click;
                                lnk.OnClientClick = $"Javascript:return postResources{ZoneIndex}{ZoneID}();";
                                lnk.Text          = "<img src=\"/_layouts/images/epmlivegantt.GIF\" border=\"0\" style=\"vertical-align: middle;\"> View Resource Plan";
                                Controls.Add(lnk);
                            }

                            rcList = SPContext.Current.List;
                            var view = SPContext.Current.ViewContext.View;

                            toolbar = new ViewToolBar
                            {
                                TemplateName = "GanttViewToolBar"
                            };

                            var context = SPContext.GetContext(Context, view.ID, rcList.ID, curWeb);
                            toolbar.RenderContext = context;

                            Controls.Add(toolbar);

                            foreach (Control control in toolbar.Controls)
                            {
                                processControls(control, $"{ZoneIndex}{ZoneID}", view.ServerRelativeUrl, curWeb);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        DiagTrace.WriteLine(exception);
                    }
                }
            }
        }