I try add resource permission to every folder that is created in the portal with the custom listener, with permission to ACCESS for the role "Guest" but in the table of database is not registered successfully,
Is registered only the permissions for the role with action id 0, I try with this:
public void onAfterCreate(DLFolder folder) throws ModelListenerException {
super.onAfterCreate(folder);
long folderId = folder.getFolderId();
primFOLDER = folderId;
try {
long guestId = RoleServiceUtil.getRole(companyId, RoleConstants.GUEST).getRoleId();
ResourcePermission resourcePermission = ResourcePermissionLocalServiceUtil
.createResourcePermission(CounterLocalServiceUtil.increment());
resourcePermission.setCompanyId(companyId);
resourcePermission.setName(folderClass);
resourcePermission.setScope(ResourceConstants.SCOPE_INDIVIDUAL);
resourcePermission.setPrimKey(String.valueOf(folderId));
resourcePermission.setRoleId(guestId);
resourcePermission.setActionIds(2);
ResourcePermissionLocalServiceUtil.addResourcePermission(resourcePermission);
ResourcePermission resourcePermissionRecover = ResourcePermissionLocalServiceUtil.getResourcePermission(
companyId, folderClass, ResourceConstants.SCOPE_INDIVIDUAL, String.valueOf(folderId), guestId);
if (resourcePermissionRecover != null) {
resourcePermissionRecover.setActionIds(2);
ResourcePermissionLocalServiceUtil.updateResourcePermission(resourcePermissionRecover);
}
} catch (PortalException | SystemException e) {
e.printStackTrace();
}
}
I don't know which is my error. Thank you.
I solved my problem with this link:
https://web.liferay.com/es/community/forums/-/message_boards/message/86705430
Related
I'm using azure ad to get the share point context and also in Azure function to manage site collections.
But when I tried to setting property bag,it failed.My azure ad application have the full control of site permission.
Sites.FullControl.All
Application
Have full control of all site collections
Yes
using (ClientContext context = spHelper.GetAzureADOnlyClientContext(hostUrl, spAzureAppId, spTenant, certificate, false))
{
tenant.SetSiteAdmin(hostUrl, siteCreationInfo.TechnicalOwnerEmail, true);
admClientContext.ExecuteQuery();
string description = siteCreationInfo.Description;
if (!string.IsNullOrWhiteSpace(description))
{
//setting the propertyBag to flag the site created by CDA
context.Site.RootWeb.AllProperties["Createdby"] = "CDA-V0.5";
context.Site.RootWeb.Description = description;
context.Site.RootWeb.Update();
}
try
{
if (context.HasPendingRequest)
{
context.ExecuteQuery();
}
logHelper.writeLog("Site updated!");
}
catch (Exception ex)
{
logHelper.writeLog("Update site error:" + ex.Message);
throw;
}
}
Do I miss some more settings?
I created a trial office 365 sharepoint account for learning. While creating my first Insert operation I got an exception as
Access denied. You do not have permission to perform this action or access this resource.
My code is
In Load event
protected void Page_Load(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext == null) return;
Session["clientContext"] = clientContext;
Microsoft.SharePoint.Client.User spUser = clientContext.Web.CurrentUser;
clientContext.Load(spUser, user => user.Title);
clientContext.Load(spUser, user => user.Email);
clientContext.ExecuteQuery();
}
}
On button click save event(Name and EmailId)
protected void Button1_Click(object sender, EventArgs e)
{
try
{
using (var clientContext = Session["clientContext"] as ClientContext)
{
if (clientContext == null) return;
var oList = clientContext.Web.Lists.GetByTitle("SharePointTestList");
var listCreationInformation = new ListItemCreationInformation();
var itemToAdd = oList.AddItem(listCreationInformation);
itemToAdd["EmailId"] = TextBox2.Text; //My List
itemToAdd["Name"] = TextBox1.Text; //My List
itemToAdd.Update();
clientContext.Load(itemToAdd);
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
Response.Write("Error Occured"+ex.Message);
}
}
It seems some permission issue. But I am not able to figure it out.
I have already faced the same problem while creating 1st time.I solved it by doing like this
Go to AppManifest.xml in your SharePointApp
Click Permissions Tab
Give FullControl Permissions to Scope Web and List
As already discussed in the comments I have a strong suspicion, that you are lacking the proper permissions to write to your target list.
As you've said you have "limited access". This means:
Can view specific lists, document libraries, list items, folders, or
documents when given permissions.
In order to write to a list, you need to grant the user at least "Contribute" permissions.
So this is not a programming related issue. Read up on the basic permission levels within SharePoint here.
In an EventReceiver I call this method GetPernNr on Item Added:
public override void ItemAdded(SPItemEventProperties properties)
{
SPSite site = properties.Web.Site;
using (SPWeb currentWeb = site.OpenWeb(properties.Web.ID))
{
.....
perNr = UserProfileUtils.GetPernNr(currentWeb, assignedTo.ToString());
.....
}
}
where assignedTo is a SPUser.
public static string GetPernNr(SPWeb web, string accountName)
{
string perNr = string.Empty;
UserProfile upUser = null;
try
{
PermissionSet ps = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ps.Assert();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteColl = new SPSite(web.Site.ID))
{
SPServiceContext serviceContext = SPServiceContext.GetContext(siteColl);
UserProfileManager upm = new UserProfileManager(serviceContext);
if (upm.UserExists(accountName))
{
upUser = upm.GetUserProfile(accountName);
if (upUser["PersonNumber"] != null)
{
perNr = upUser["PersonNumber"].Value.ToString();
}
}
}
});
}
catch (Exception ex)
{
..
}
finally { System.Security.CodeAccessPermission.RevertAssert(); }
return perNr;
}
It's strange, this code works when I try to get value from a default field in UserProfile (Office, Manager, etc). And also works when I call this method outside EventReceiver, but in my case, upUser["PersonNumber"].Value returns null.
Any help will be much appreciated
Did you check the custom property permission in the central admin.
Central Administration -> Edit User Profile Property -> Policy Settings
Make default privacy policy to everyone and then try.
Here is the steps for SharePoint Server 2013:
Central Admin > Application Management > Manage service applications > Your User Profile Application > Manage User
Properties
Select Edit option from property menu.
Now Under "Policy Settings":
Set Default Privacy Setting: Everyone
I am trying to update the telephone number on all associated contacts of an account entity. the following is the code that i have used,
public class Plugin:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
Entity entity;
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "account") { return; }
}
else
{
return;
}
try
{
string telephoneNum = string.Empty;
IOrganizationServiceFactory serviceFactory =(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service =serviceFactory.CreateOrganizationService(context.UserId);
var id = (Guid)context.OutputParameters["id"];
telephoneNum = entity.GetAttributeValue<string>("telephone1");
UpdateContact(service, id,telephoneNum);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException(
"An error occurred in the plug-in.", ex);
}
}
private static void UpdateContact(IOrganizationService service, Guid id,string telephoneNUm)
{
using (var crm = new XrmServiceContext(service))
{
var res = from c in crm.CreateQuery("contact")
where c["parentcustomerid"].Equals(id)
select c;
foreach (var c in res)
{
Entity e = (Entity)c;
e["telephone1"] = telephoneNUm;
crm.UpdateObject(e);
}
crm.SaveChanges();
}
}
}
I register the plugin on update, and primary entity "account" but whenever i try to save the account form after change of number in the telephone field i see an error pop up. Am i missing something? Thank you all!
Just a hunch..but I think you are getting the Id in the wrong way..try getting it by:
Guid Id = context.PrimaryEntityId
But as Pedro suggested..you need to see what is the exact error or try to debug the plugin using attach to process..
I want to be able to detect when a user signs on to my application using passive acs, so that I can add them to my database if this is the first time using my app. Right now I am subscribing to WSFederationAuthenticationModule.SignedIn but I feel I'm missing something. Mainly I'm not sure the best place to subscribe to the event, I got it to work inside PostAuthenticateRequest but its a bit hacky. Any suggestions?
this code is from global.asax
public override void Init()
{
base.Init();
PostAuthenticateRequest += (s, e) =>
{
try
{
FederatedAuthentication.WSFederationAuthenticationModule.SignedIn -= SignedIn;
}
finally
{
FederatedAuthentication.WSFederationAuthenticationModule.SignedIn += SignedIn;
}
};
}
private void SignedIn(object sender, EventArgs e)
{
//do something
}
EDIT:
For now I'm going to use a flag variable to make sure I only subscribe once to SignedIn. Unless someone has any other suggestions that is :) thanks for the help Sandrino. Here is what I have at the moment.
private static bool isFirstRequest = true;
public override void Init()
{
base.Init();
PostAuthenticateRequest += (s, e) => {
if (isFirstRequest)
{
FederatedAuthentication
.WSFederationAuthenticationModule.SignedIn += SignedIn;
isFirstRequest = false;
}
};
}
private void SignedIn(object sender, EventArgs e)
{
//do something
}
EDIT:
A little more info. This problem happens if I'm using the azure emulator, it probably happens when deployed as well but I haven't tried that. I have tested if I am just not able to debug by trying to write to a text file and no text file was created.
Why do you subscribe to the SignedIn event each time the PostAuthenticateRequest event is raised? You can simple subscribe to it when the application starts (in the Global.asax) and it will be raised for each user that signed in:
public class MvcApplication : System.Web.HttpApplication
{
...
protected void Application_Start()
{
...
FederatedAuthentication.ServiceConfigurationCreated += (s, e) =>
{
FederatedAuthentication.WSFederationAuthenticationModule.SignedIn += new EventHandler(OnUserSignedIn);
};
}
private void OnUserSignedIn(object sender, EventArgs e)
{
// Custom logic here.
}
}
The SignedIn event is the best way to detect a user sign in before the application continues. Take a look at the following diagram. Before redirecting back to a page, the SignedIn event is raised to allow you to detect an user sign in:
Reference: http://msdn.microsoft.com/en-us/library/ee517293.aspx
I created a class that derives from ClaimsAuthenticationManager. There is only one method that you have to override, which is
public virtual IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal);
In my app, I use this method to check if the user, who has successfully authenticated, is really a user of my app (i.e. they exist in my database). If not, I direct them to a signup page.
My class looks something like this:
public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal.Identity.IsAuthenticated)
{
var identity = incomingPrincipal.Identity as IClaimsIdentity;
User user = null;
// Get name identifier and identity provider
var nameIdentifierClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase));
var identityProviderClaim = identity.Claims.SingleOrDefault(c => c.ClaimType.Equals(CustomClaimTypes.IdentityProviderClaimType, StringComparison.OrdinalIgnoreCase));
if (nameIdentifierClaim == null || identityProviderClaim == null)
{
throw new AuthenticationErrorException("Invalid claims", "The claims provided by your Identity Provider are invalid. Please contact your administrator.");
}
try
{
//checking the database here...
using (var context = new CloudContext())
{
user = (from u in context.Users
where u.IdentityProvider == identityProviderClaim.Value &&
u.NameIdentifier == nameIdentifierClaim.Value &&
!u.Account.PendingDelete
select u).FirstOrDefault();
}
}
catch (System.Data.DataException ex)
{
Console.WriteLine(ex.Message);
if (ex.InnerException != null)
Console.WriteLine(ex.InnerException);
throw;
}
}
return incomingPrincipal;
}
Then, in your web.config, you add a section to the <microsoft.identitymodel> area, as so:
<claimsAuthenticationManager type="CloudAnalyzer.UI.Security.CloudAnalyzerClaimsAuthenticationManager" />
I learned this trick from the sample app located here: Windows Azure Marketplace. Even if you're not going to publish in the Window Azure Marketplace it's a good sample with some helpful code snippets you can use for ACS integration.