Thursday, June 22, 2017

Application Page in SharePoint Model Dialog Box

Recently i have done some silly tinker works while open application page in SharePoint Model dialog box. In this post i have explained that. This may help someone who needs

My Scenario:
Open an application page, where have a ListFieldIterator, asp.net file upload controls and once save button and one cancel button. On save button handle the required validation and update the item to list.

First Code Snippet
Webpart Solution (Only the button code) 
Ascx
 <script type="text/javascript"">
     function fnOpenUpdateSection(queryString, title, oldJobAidStatusID, jobAidID) {
         addSectionUri = "/_layouts/LisFiedIteratorResize/LFIApplPage.aspx";
         var options = { url: addSectionUri, width: 800, height: 800, title: "Test Page" };
         SP.UI.ModalDialog.showModalDialog(options);
         return false;
     }
 </script>
 <asp:Button ID="btnTest" runat="server" Text="Click" />

Things to discuss that here, I have added a asp.net button control in my webpart solution and written a javascript to open the application page in SharePoint Model popup dialog box.

Ascx.cs
protected void Page_Load(object sender, EventArgs e)
        {
            btnTest.Attributes.Add("onclick""javascript:return fnOpenUpdateSection()");
        }

On Page load, assigned the javascript to the button through button attributes.

Application Page 
Aspx
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table id="tblUpdateScript" runat="server" cellpadding="0" cellspacing="0" width="100%">
        <tr>
            <td>
                <SharePoint:ListFieldIterator ID="lfiUpdateJobAid" runat="server"ControlMode="New" ExcludeFields="DisplayOrder;#IsDeleted">
                </SharePoint:ListFieldIterator>
            </td>
        </tr>
        <tr id="trFileUpload" runat="server">
            <td valign="top">
               <asp:Label ID="lblAttachments" runat="server"CssClass="labelAttachment">Attachments</asp:Label>
            </td>
            <td>
                <asp:FileUpload ID="fuSectionAttachment" runat="server" />&nbsp;
                <asp:Label ID="lblAttach1Error" runat="server"CssClass="labelAttachmentError"></asp:Label><br />
                <asp:FileUpload ID="fuSectionAttachment1" runat="server" />&nbsp;
                <asp:Label ID="lblAttach2Error" runat="server"CssClass="labelAttachmentError"></asp:Label><br />
                <asp:FileUpload ID="fuSectionAttachment2" runat="server" />&nbsp;
                <asp:Label ID="lblAttach3Error" runat="server"CssClass="labelAttachmentError"></asp:Label>                               
            </td>      
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td valign="top" colspan="2">
                <asp:LinkButton ID="lbnSave" CommandName="Save" runat="server"OnClick="btnSave_Click">
                    <img id="Img1" src="/Style%20Library/images/save.png"align="absMiddle" runat="server"
                        alt="Save" />
                </asp:LinkButton>&nbsp;&nbsp;               
                    <img id="Img2" src="/Style%20Library/images/cancel.png"align="absMiddle" runat="server"
                        alt="Cancel"onclick="javascript:SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancelled clicked');" />               
            </td>
        </tr>
        <tr>
            <td valign="top" colspan="2">
                <asp:Label ID="lblErrorMessage" runat="server"></asp:Label>
            </td>
        </tr>
    </table>
</asp:Content>

Designed a table in the Main ContentPlaceHolder with 3 rows. In 1st row added SharePoint ListFieldIterator, 2nd row added asp.net file upload controls and 3rd row added two buttons (Linkbutton and html image control)

Aspx.cs
protected void Page_Init(object sender, EventArgs e)
        {
          if (!IsPostBack)
            {

            using (SPSite osite = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb oweb = osite.OpenWeb())
                {
                    SPList olist = oweb.Lists.TryGetList("Job Aid Sections");
                    if (olist != null)
                    {
                        lfiUpdateJobAid.ListId = olist.ID;
                    }
                }
            }
          }  
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

                lfiUpdateJobAid.ListItem["JobAidID"] = 1;
                lfiUpdateJobAid.ListItem["SectionType"] = 0;
                lfiUpdateJobAid.ListItem["IsDeleted"] = 0;

                lfiUpdateJobAid.Web.AllowUnsafeUpdates = true;
                lfiUpdateJobAid.ListItem.Update();
                lfiUpdateJobAid.Web.AllowUnsafeUpdates = false;

                Response.Write("<script language='javascript'>window.parent.location.href = window.parent.location.href</script>");
            }           
        }
On Page_Init set theListId property for the SharePoint ListFieldIterator and button_Click perform the required action and update the listitem
Note: In the button click used a javascript to close the application page after update the list item.

OutPut:

















Issue 1:  

When maximize application page the ListFieldIterator Field (Multi Line Text Editor) is not extend the width. Refer the below snapshot, also want to increase the height


















Also want to increase the single line of text box width.

Solution:

Multi Line of Text change height:

We can do it by changing the Column setting
List -- List settings -- Multi Line of Text Column -- Number of lines for editing
Change the value as 40

Multi Line of Text change width:

By default the Enhanced RTE get expand when maximize the page. But here we have add the LFI within table row. So it’s not working. To solve this we can set the table width as 100%
<table id="tblUpdateScript" runat="server" cellpadding="0" cellspacing="0" width="100%">
 
Single Line of Text change width:

We can handle this through the css. 
The default width for the Single Line of Text is 386px. We can handle the class in our css. Refer the below snippet.
ms-long
    {
        width:50%;
    }

Now refer the below snapshot, which has taken after done the above mentioned changes

















Issue 2:

Want to open the model dialog box in maximized mode, 

Solution:

I used showMaximized option in SharePoint Model Dialog box. Refer the below code snippet

var options = { url: addSectionUri, showMaximized:true, title: "Test Page" };

 This open the application page in maximized mode, but gives another issue 
            “After open the page, if I click save button without enter any value then the application page collapsed” refer the below snap, that taken after click the save button

























Solution:

Then I resolved this issue be replacing height and width as 0 in the SP Model Dialog option

var options = { url: addSectionUri, width: 0, height: 0, showMaximized: true, title: "Test Page" };

Issue 3:

In the above snap, you can see that the validation message placed two times for the Multi Line of Text Field. This is the default behaviour of the SharePoint Multiple Lines of Text with Enhanced Rich Text mode. Now I want to fix this issue also. 

Solution:

After a very long search in Google, I get the below idea and that worked for me.
protected void Page_Load(object sender, EventArgs e)
        {
            lbnSave.Click += new EventHandler(btnSave_Click);
        }
Change the save button click event code as below
protected void btnSave_Click(object sender, EventArgs e)
        {
            //if (Page.IsValid)
            //{
                BaseFieldControl fieldControl = GetFieldControlByName("Section Content");
                if (Convert.ToString(fieldControl.Value.ToString().Trim()) == string.Empty)
                {
                    fieldControl.ErrorMessage = " ";
                    fieldControl.IsValid = false;
                }
                else
                {

                    lfiUpdateJobAid.ListItem["JobAidID"] = 1;
                    lfiUpdateJobAid.ListItem["SectionType"] = 0;
                    lfiUpdateJobAid.ListItem["IsDeleted"] = 0;

                    lfiUpdateJobAid.Web.AllowUnsafeUpdates = true;
                    lfiUpdateJobAid.ListItem.Update();
                    lfiUpdateJobAid.Web.AllowUnsafeUpdates = false;


                    Response.Write("<script language='javascript'>window.parent.location.href = window.parent.location.href</script>");
                }
            //}
        }
Add the new method
protected BaseFieldControl GetFieldControlByName(String fieldNameToFind)
        {
            BaseFieldControl baseField = null;
            foreach (Control control in Page.Validators)
            {
                if (control is BaseFieldControl)
                {
                    baseField = control as BaseFieldControl;
                    String fieldName = baseField.FieldName;
                    if ((fieldName == fieldNameToFind))
                    {
                        return baseField;
                    }
                }
            }
            return baseField;
        }
Refer the below snap

















See Application Page in SharePoint Model Dialog Box - Part II for complete code for this along with the Field setting changes in LFI.

Monday, June 12, 2017

SharePoint List versioning using c#

We can also enable SharePoint List versioning using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPList list = spweb.Lists["CustomList"];
list.EnableVersioning = true;
list.Update();
}

Retrieve SPListItem versions using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
//listitem.Versions.RestoreByID(5);
foreach (SPListItemVersion versionItem in listitem.Versions)
{
Console.WriteLine("VersionId :" + versionItem.VersionId);
Console.WriteLine("VersionLabel :" + versionItem.VersionLabel);
Console.WriteLine("IsCurrentVersion :" + versionItem.IsCurrentVersion);
Console.WriteLine("ListItem.Title :" + versionItem.ListItem.Title);
Console.WriteLine("Created :" + versionItem.Created);
Console.WriteLine("CreatedBy :" + versionItem.CreatedBy);
Console.WriteLine("Level :" + versionItem.Level);
}
}
}

Retrieve SPListItem version changes using c#

using (SPSite spsite = new SPSite("http://win7/"))
{
SPWeb spweb = spsite.OpenWeb();
SPListItemCollection listitems = spweb.GetList("http://win7/Lists/CustomList").Items;

foreach (SPListItem listitem in listitems)
{
for (int i = 0; i < listitem.Versions.Count - 1; i++)
{
SPListItemVersion oldVersion = listitem.Versions[i];
SPListItemVersion latestVersion = listitem.Versions[i + 1];
foreach (SPField field in oldVersion.Fields)
{
if (field.ShowInVersionHistory == false)
{
continue;
}

if (latestVersion == null)
{
Console.WriteLine("  > {0} changed to \"{1}\"",
field.StaticName, oldVersion[field.StaticName]);
continue;
}

if (oldVersion[field.StaticName].Equals(latestVersion[field.StaticName]))
{
continue;
}

Console.WriteLine("  > {0} changed from \"{1}\" to \"{2}\"",
field.StaticName, latestVersion[field.StaticName], oldVersion[field.StaticName]);
}
}

}
}
Console.ReadLine();

Share this: