Search This Blog

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Wednesday, December 21, 2016

How to pass value from SharePoint modal dialog to Parent window

We can pass the value from SharePoint Modal dialog to its parent window.

After a long search i found the below solution:

Parent Window:

function OpenPopUp() {
                var siteCollectionURL = _spPageContextInfo.siteAbsoluteUrl;
                var options = {
                    url: siteCollectionURL + "/Sitepages/PopUpView.aspx",
                    dialogReturnValueCallback: CloseCallback,
                    height: 900,
                    width: 800
                };
                SP.UI.ModalDialog.showModalDialog(options);
                return false;
            }

function CloseCallback(result, target) {
              ///Value given at Popup window will come as target value
                alert(target);

            }

PopUp window:


function Successclosepopup() {
              var returnValue = "PopUp Successfully Closed";
              SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, returnValue);

            }

Hope this may help you.

Thanks.,


Wednesday, March 23, 2016

Creating SharePoint Timer Job

Timer Job:

Timer Job is a background process that are run by SharePoint. It is a periodically executed task inside SharePoint Server. It provides us a task execution environment.


Default Timer Jobs inside SharePoint:

There are many timer jobs inside SharePoint which do internal tasks like:
    • Send emails
    • Validate sites
    • Delete unused sites
    • Health analysis
    • Product versioning
    • Diagnostics
These tasks will having execution periods like:
    • Minute
    • Hour
    • Day
    • Week
    • Month

1) Create an empty SharePoint project and add an class file in that project.
    Derive CustomTimerJob Class from SPJobDefinition which comes from 
    Microsoft.SharePoint.Administration.dll

Example:
    class TestTimerJob : SPJobDefinition
    {
     }

2) Add the three Constructors of the derived class : When ever we create the object of CustomTimerJob  class, corresponding constructor will execute.
   
Example:  
  public TestTimerJob() : base()
        {
        }

   public TestTimerJob(string sJobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(sJobName, service, server, targetType)
        {
        }

   public TestTimerJob (string sJobName, SPWebApplication webApplication)
            : base(sJobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "Test Time Job";
        }

3) Override the Execute method: When ever the timer job start running then the code inside the Execute method will run.

Example: 


public override void Execute(Guid targetInstanceId)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite Osite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb Oweb = Osite.OpenWeb())
                        {
                            SPList TestTasksList = Oweb.Lists.TryGetList("TestTasksList ");                          
                            SPListItemCollection TestTasksListCol = TestTasksList.GetItems();
                            foreach(SPListItem Oitem in TestTasksListCol)
                           {       
                                 Oitem["Title"]="TimerJob";
                                  Oitem.Update();   
                           }
                        }
                    }
                });
            }
            catch (Exception)
            {
                throw;
            }
        }


4) We need to create a Feature and Feature Receiver so on activation of this feature we are going the add our timer job to SharePoint farm.
    1. Create a new feature and set its scope as Site
    2. Add an event receiver by right clicking that feature. 
    3. And also create a name for your timer job;

const string JOB_NAME = "Test TimerJob";

       In that feature include the following code for Feature activated and Feature Deactivating

Feature Activated:
 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                    job.Delete();
            }
            OverdueTasksTimerJob listLoggerJob = new OverdueTasksTimerJob(JOB_NAME, site.WebApplication);
            //SPMinuteSchedule schedule = new SPMinuteSchedule();
            SPDailySchedule schedule = new SPDailySchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 59;
            //schedule.Interval = 5;
            listLoggerJob.Schedule = schedule;
            listLoggerJob.Update();
        }

Feature Deactivated:
       public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // Delete the timer job
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {
                if (job.Name == JOB_NAME)
                    job.Delete();
            }
        }

5) Next deploy you solution and check you timer job is comes under Job definitions in Monitoring option in central admin. If it doesn't come then activate the feature manually using Power shell command.

Example:
Enable-SPFeature FeatureFolderName -Url http://server/site/subsite

Note: you can get the Feature name from the following path:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\FEATURES


    
   
























Thursday, November 5, 2015

Inside Update panel calendar picker controls are not working

When we are using update panel we may face some issues. In that one of the major issue is using calendar picker control inside update panel. 
To over come this issue we have to include the following script tag.

<script type="text/javascript" src="/_layouts/datepicker.js"></script>

Now we can use calendar picker inside update panel without any issues.

thanks,

Inside Update panel people editor is not working

When we are using update panel we may face some issues. In that one of the major issue is using people editor control inside update panel. Update panel does not allow post back. So people editor will not resolve the users.
To over come this issue we have to include the following script tag.

<script type="text/javascript" src="/_layouts/15/entityeditor.js"></script>

Now we can use people editor inside update panel without any issues.

thanks,

Wednesday, October 14, 2015

How to acces sharepoint 2013 user profile using C#

UserProfile profile;
SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
string fromMail = string.Empty;

public void getEmailID()
{
    try
    {
        UserProfileManager upm = new UserProfileManager(serviceContext);
        profile = upm.GetUserProfile(currentUser.LoginName);
        if (profile != null)
         {
             if (!string.IsNullOrEmpty(Convert.ToString(profile[PropertyConstants.WorkEmail].Value)))
              {
                    fromMail = profile[PropertyConstants.WorkEmail].Value.ToString();            
              }
         }
    }
    catch (Exception ex)
    {
       throw;    
    }
 }

Using this UserProfileManger we can access all the details stored for a sharepoint user in User Profile Service Application.

thanks,

Monday, August 3, 2015

Adding User Permissions using Power shell script in SharePoint 2013


In SharePoint we are having permission level operations. To that SharePoint group we can add users through Site Settings -> Site Permissions.

And also we can give permissions using PowerShell scripts.

For Single User:

new-spuser -UserAlias "User1" -Web "http://test:100/sites/home1" -Group "TestUsers"

For Every One:

new-spuser -UserAlias "Everyone" -Web "http://test:100/sites/home1" -Group "TestUsers"

By executing this PowerShell script we can add users to the SharePoint groups.


thank you,

Thursday, July 9, 2015

link button property to open in new tab?

 By Adding following onClientClick even in your link button we can open the url in new tab.

OnClientClick="aspnetForm.target ='_blank';"

so on click it will call Javascript function an will open respective link in News tab.

<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" Text="New Tab"  />

and another option is you can go for Hyper link control to achieve this. By default it has the Target property and you can set that to _blank.

thank you,

Wednesday, June 24, 2015

Two different timer job shows the same name in job definition

This usually happens when you add two or more timer jobs in single solution. This one tested me a lot. This issue usually comes when we go for two features for two timer jobs.
Guess what here is the place we do mistake usually.

When we copy paste the code for feature receiver from one feature to another one we just copy and paste it where we don't much care about any changes in that code. because it is already working fine. Of course its working fine but still it needs a little change.

Feature 1:
      Feature Activated:
       TestJob1 listLoggerJob = new TestJob1 (List_JOB_NAME, site.WebApplication);

Feature 2:
    Feature Activated:
      TestJob2 listLoggerJob = new TestJob2 (List_JOB_NAME, site.WebApplication);

So guys please don't forget to change the class name where you create your timer job. Don't just copy and paste, just review it at-least once. It took me some time to find this silly mistake.


thank you


Get Row ID of inserted data in SharePoint list

SPList spList = spWeb.Lists["Announcements"];
SPListItem spListItem = spList.Items.Add();
spListItem["Title"] = "Hello world";

spListItem.Update();
int RowID = spListItem.ID;  //This is the ID of the new item.

Tuesday, June 23, 2015

How to enable custom errors in Share point error

In share point while getting error we may see the correlation ID. But that is not really understandable i guess.
But we do have an option to enable custom error message which is understandable by anyone.

Here are the steps to enable that settings:

1. 15/Layouts folder we have a web.config file. In that file find Custom Errors and change its mode          as Off
    Ex: customErrors mode="Off"

2. Open your webapplication's web.config file.
     a) Find CallStack and change it's value as true
          Ex: CallStack="true"
     b) Find find Custom Errors and change its mode as Off
          Ex: customErrors mode="Off"
     c) Find debug and change its mode as true
          Ex: debug="true"

Once you finished these steps, hereafter you will get clean error message and you can solve it in your way..


thank you

Saturday, June 20, 2015

page.response.redirect is not working

In sharepoint some times we cant use the Response.Redirect.

So we can use SPUtility.Redirect to redirect to other pages.

SPUtility.Redirect("/SitePages/CustomAccessDenied.aspx", SPRedirectFlags.Static / SPRedirectFlags.Default / SPRedirectFlags.Trusted, HttpContext.Current);

Like this we can redirect to other pages in sharepoint

Saturday, May 30, 2015

Get the checkbox value is checked or not using Jquery

 $(document).ready(function () {
    $('#<%=chkValidateBabyName.ClientID%>').change(function () {
          if ($(this).is(":checked")) {
            alert("Check box checked");
          }
          else{
           alert("Check box un checked");
         }
    });
});

Include this code in document ready function. then you will get checkbox value when the check box value is changed..

Monday, May 25, 2015

How to create a static variable at client side

Actually we cant create a static variable at client side. But we can keep the value even after page postback using Hidden field control.

First we need to create a hidden control and need to set ClientIDMode as "Static"

Ex: <asp:HiddenField ID="hndControl" ClientIDMode="Static" runat="server" />

After that we need to assign the value to that hidden field.

document.getElementById('<%= hndControl.ClientID %>').value = "Static";

Here after we can use that value until we change hidden field value.



Sunday, May 24, 2015

How to avoid alphabets and special character from text box using javascript

Use the following code OnKeyPress Event in your text box:

<asp:TextBox ID="txtNumber" runat="server" OnKeyPress="return IsNumeric(event);"></asp:TextBox>


function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    document.getElementById("error").style.display = ret ? "none" : "inline";
    //TestOnTextChange();
    return ret;
}

Disable Copy, Cut and Paste options in text box

Include the following options in your text box:

onpaste="return false"
oncut="return false"
oncopy="return false"

it will avoid the cut, copy and paste options from your text box

Thursday, May 21, 2015

Timer Job Issues


This is the most common error in timer job.

Keep your scope as site

  public override void FeatureActivated(SPFeatureReceiverProperties properties)
  {
            SPSite site = properties.Feature.Parent as SPSite;
}

get the site as mentioned above.

If still you get the same error please check your code whether you are using any custom dll.
Because timer job sometimes will not accept custom dll files. so try to avoid those.



Wednesday, May 20, 2015

Timer Job with Sharepoint

Timer Job:

Timer Job is a background process that are run by SharePoint. It is a periodically executed task inside SharePoint Server. It provides us a task execution environment.

Default Timer Jobs inside SharePoint:

There are many timer jobs inside SharePoint which do internal tasks like:
    • Send emails
    • Validate sites
    • Delete unused sites
    • Health analysis
    • Product versioning
    • Diagnostics
These tasks will having execution periods like:
    • Minute
    • Hour
    • Day
    • Week
    • Month
Components of Connectable web parts : 
  1. Derive CustomTimerJob Class from SPJobDefinition
  2. Add the three Constructors of the derived class : When ever we create the object of CustomTimerJob  class, corresponding constructor will execute.
  3. Override the Execute method: When ever the timer job start running then the code inside the Execute method will run.
  4. We need to create a Feature and Feature Receiver so on activation of this feature we are going the add our timer job to SharePoint farm.

Sunday, May 10, 2015

Update managed meta data values into SPList

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    TaxonomySession taxonomySession = new TaxonomySession(site);
                    TermStore termStore = taxonomySession.TermStores["Test_ManagedMetaData"];
                    Group group = termStore.Groups["College"];
                    TermSet termSet = group.TermSets["Karur"];
                    Term term = termSet.Terms["CCET"];
                    SPList list = web.Lists.TryGetList("TimerJobList");
                    if (list != null)
                    {
                        TaxonomyField taxonomyField = list.Fields["College"] as TaxonomyField;
                        TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);
                        taxonomyFieldValue.TermGuid = term.Id.ToString();
                        taxonomyFieldValue.Label = term.Name;
                        SPListItem item = list.Items.Add();
                        item["Title"] = "Sample";
                        item["College"] = taxonomyFieldValue;
                        item.Update();
                        //list.Update();
                    }
                }
            }

Friday, April 17, 2015

How to check a value is SPGroup or SPUser

SPList olist = oweb.Lists.TryGetList("Test_List");
if (olist != null)
{
SPListItemCollection ocoll = olist.Items;
foreach(SPItem oitem in ocoll)
{
SPFieldUserValueCollection GetAllGroup = new SPFieldUserValueCollection(oweb, Convert.ToString(oitem["SPGroups"]));

for (int i = 0; i < GetAllGroup.Count; i++)
{
SPFieldUserValue singlevalue = GetAllGroup[i];
if (singlevalue.User == null)   // If it is GROUP condition is true
{
SPGroup group = oweb.Groups[singlevalue.LookupValue];
foreach (SPUser user in group.Users)
{
if (ouser.Name == user.Name)
{
isuserval = true;
break;
}
}
}
else
{
if (ouser.Name == singlevalue.User.Name) // Checks User is Current Login User
{
isuserval = true;
break;
}
}
}
}
}


Impersonation in Sharepoint

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code.
And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code.
If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Restricting Custom People Picker to only one Sharepoint group programatically

Refer the following script files in your page,     <!-- For People Picker -->     <script type="text/javascript" src...