EPiServer Community member Avatar error - c#

I am developing EPiServer CMS 7 MVC site with Community. I am trying to get and display member Avatar (Avatar exist physically in Contributed files folder). Here is my code:
var user = CurrentUser;
var image = user.GetPortraitUri(ImageSize.Huge).ToString();
variable image gets value:
http://localhost:18000/EPiServerCommunity/Modules/ImageGallery/ImageHandler.ashx?imageId=7&thumbnailId=10
But on View I see only image icon (like when can't upload or display image). When I am trying to open this image link in new tab its redirect me to EPiServer login page. I cant understand why it redirect me to login page if user is authorized. Any ideas?
Additional information:
I installed EPiServer Relate site using Deployment center. There is the same way of getting user Avatar on EditProfile user control or on MyPage. And when I am trying to open image in new tab using getted Url I see it. I think there can be some permissions in Web.config file , but I dont know ....
Add new information (11/10/2014). The problem is in section
I mean in section of EPiServerCommunity section. When I changed to deny in installed previously EpiServer Relate site than I am getting login page when I am trying to open image. In my web.config file I changed all deny to allow, but still I am getting login page when I am trying to open image by url. I guess Episerver doesnt see this section in web.config file.
Add new information (11/11/2014). I added one more role "Everyone" to of section. I see that when I am trying to open localhost:18000\episerver it skip login page. I added the same role "Everyone" to EpiServerCommunity section. Now it looks:
<location path="EPiServerCommunity">
<system.web>
<pages enableViewState="true" />
<authorization>
<allow roles="CommunityAdmins,CommunityModerators,Administrators,Everyone" />
<allow users="*" />
</authorization>
</system.web>
But I am still getting login page when I am trying to open image by url :(
P.S. This question I posted in EPiServer World, but I hope I will get answer here more quickly.

Resolved my problem. EPiServer skips permitions in location section. I created class CommunitySecurityModule with events DefaultSecurity_CreatedUser and MyPageHandler_Register where I set Owner to ImageGallery and other AccessRights for newsfeed and etc. Now when I had registered user and added it to System
newUser = CommunitySystem.CurrentContext.DefaultSecurity.AddUser(newUser);
it calls MyPageHandler_Register and sets all rights:
var user = e.Object as IUser;
if (user != null)
{
var myPage = MyPageHandler.Instance.GetMyPage(user);
if (myPage != null && myPage.ImageGallery != null)
{
foreach (var imageGallery in myPage.ImageGallery.Children)
{
var imageGalleryClone = imageGallery.CreateWritableClone() as ImageGallery;
imageGalleryClone.SetOwner(user);
ImageGalleryHandler.Instance.UpdateImageGallery(imageGalleryClone);
}
}
}
Implementation of SetOwner method below:
public static void SetOwner(this ImageGallery imageGallery, IUser owner)
{
imageGallery.SetAttributeValue("Owner", owner);
}
Implementation of DefaultSecurity_CreatedUser:
private void DefaultSecurity_CreatedUser(ISecurityHandler sender, ICreateUserEventArgs args)
{
// Add user to the community members group
var group = CommunityMembersGroup;
var addedUser = args.User;
addedUser = (IUser)addedUser.CreateWritableClone();
addedUser.Groups.Add(group);
// Update the user
CommunitySystem.CurrentContext.DefaultSecurity.UpdateUser(addedUser);
// Set access rights to the newly created user
// Access right for anonymous users
var anonAccessRights = new ReadModifyRemoveAccessRights
{
Read = true,
};
EntitySecurityHandler.Instance.SetAccessRights(addedUser, AnonymousGroup, anonAccessRights);
// Access right for community members
var communityMembersAccessRights = new ReadModifyRemoveAccessRights
{
Read = true,
};
EntitySecurityHandler.Instance.SetAccessRights(addedUser, group, communityMembersAccessRights);
// Access rights for administrators
var adminAccessRights = new ReadModifyRemoveAccessRights
{
Read = true,
Modify = true,
Remove = true
};
EntitySecurityHandler.Instance.SetAccessRights(addedUser, AdministratorsGroup, adminAccessRights);
// Access rights for the added user
var userAccessRights = new ReadModifyRemoveAccessRights
{
Read = true,
Modify = true,
Remove = true
};
EntitySecurityHandler.Instance.SetAccessRights(addedUser, addedUser, userAccessRights);
// Access rights for moderator
var moderatorAccessRights = new ReadModifyRemoveAccessRights
{
Read = true,
Modify = true,
Remove = true
};
EntitySecurityHandler.Instance.SetAccessRights(addedUser, ModeratorsGroup, moderatorAccessRights);
}
Note: Before that you should create Attribute "Owner" of type IUser for type ImageGallery in admin panel.

Related

Insert permission for users inside sharedDrive

I want to add members inside specific shared drive (Team drive).
i have tried with inserting permission request as below:
var listPermisssion = new List<TeamDrivePermissionDetailsData>() { };
TeamDrivePermissionDetailsData permission = new TeamDrivePermissionDetailsData()
{
Role = role,
TeamDrivePermissionType ="member" ,
};
listPermisssion.Add(permission);
Permission tdrivePermission = new Permission();
tdrivePermission.EmailAddress = who;
tdrivePermission.TeamDrivePermissionDetails = listPermisssion;
var requestPermission = service.Permissions.Create(tdrivePermission, sharedDriveId);
requestPermission.Execute();
i got this error :
Error:'Google.Apis.Requests.RequestError
The permission role field is required. [400]
thnks for the help.
The method Permissions:create requires the specification of role and type as described in the documentation
member is not a valid option for type - it should be one of the following options:
user
group
domain
anyone
role expects one of the following options:
owner
organizer
fileOrganizer
writer
commenter
reader

C# Can not add user to Active Directory. It show error There is no such object on the server

I want to use C# add user to Active Directory from my computer.
AD install in server 10.1.1.5
Username and password for login to AD is "Administrator", "Pass12345678".
I create OU name Guest on AD.
This is my code to add user to AD.
private void Btn_ok_Click(object sender, EventArgs e)
{
UserInfo newUserInfo;
newUserInfo.firstName = "TestName" ;
newUserInfo.lastName = "TestLastName";
newUserInfo.displayName = "TestName Lastname";
newUserInfo.username = "TestName.t";
newUserInfo.sAMAccountName = "TestName.t";
DirectoryEntry adUserFolder = new DirectoryEntry("LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com", "Administrator", "Pass12345678");
/******** It show error this line **********/
if(adUserFolder.SchemaEntry.Name == "container")
{
DirectoryEntry newUser = adUserFolder.Children.Add("CN=" + newUserInfo.username, "User");
if (DirectoryEntry.Exists(newUser.Path))
{
//Remove exist user
adUserFolder.Children.Remove(new DirectoryEntry(newUser.Path));
}
newUser.Properties["sAMAccountName"].Value = newUserInfo.sAMAccountName;
newUser.Properties["givenName"].Value = newUserInfo.firstName;
newUser.Properties["sn"].Value = newUserInfo.lastName;
newUser.Properties["displayName"].Value = newUserInfo.displayName;
newUser.CommitChanges();
newUser.Invoke("setpassword", "Test123456");
newUser.CommitChanges();
}
}
when I click OK button it show error.
System.DirectoryServices.DirectoryServicesCOMException: 'There is no
such object on the server. '
at line
if(adUserFolder.SchemaEntry.Name == "container")
How to fix it ?
The DirectoryEntry constructor will never throw an exception. It doesn't actually connect to AD until you start using it. Since that line is the first time you are using adUserFolder, that's when it first connects to AD.
The error means what it says: there is no object with a distinguishedName of CN=Users,OU=Guest,DC=myhome,DC=com.
Are you sure you have that right? It seems like you are looking for a container called Users inside of an OU called Guest. Is that what you are trying to do?
Is Users a container or an OU?
You can confirm the distinguishedName by using AD Users and Computers: navigate to the object you want -> right-click -> 'Properties' -> Attribute Editor tab and look at the distinguishedName attribute.
For creating user objects in active directory I've always used UserPrincipals as opposed to DirectoryEntries:
public void create(string lanid, string new_password, string container)
{
using (UserPrincipal new_user = new UserPrincipal(new PrincipalContext(ContextType.Domain, this.domain_string, container)))
{
new_user.SamAccountName = lanid;
new_user.SetPassword(new_password);
new_user.Enabled = true;
new_user.Save();
}
}
In that example "container" would be something like:
"OU=container,OU=container,OU=container,OU=container,DC=domain,DC=domain,DC=domain";
As for your original error with the DirectoryEntries I'd step through it and see if the object is actually set to anything:
The string:
"LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com"
Doesn't look right to me;
"LDAP://CN=10.1.1.5,CN=Users,OU=Guest,DC=myhome,DC=com"
May work...

SharePoint: Customize default NewForm.aspx and hide some fields according to given permissions

My requirement is to restrict users to view/add/edit fields of a list as per their given group/permission. To achieve this objective as per my understanding I have to generate custom list forms. If anyone can help me to customize NewFrom.Aspx and code in such a way that we can check current user group/permission and hide fields which should not be accessible to him.
I have derived solution after googling and have thought to apply below thing after creating new custom list form. I want to know if this approach is good enough or give any optimal solution to it.
var web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
web.Update();
var lists = web.Lists["SomeList"];
var f = lists.Fields["SomeField"];
if(){ //to check if user is in role
f.ShowInEditForm = false;
f.ShowInNewForm = false;
f.Update();
}
The same list will be used ac cross all the users so I think above solution might not be optimal.
Thanks in advance.
As SharePoint does not support Column level permissions, there are some third party tools available for column level permissions:
Column Level Security
SharePoint Column/View Permission
For Custom NewForm:
You can develop the custom webpart for NewForm where you can display fields as per the permissions.
Then set this webpart in place of default NewForm.aspx, so when ever user click on NewItem link of the list then rather than default sharepoint form it will open custom webpart.
You can replace the default NewForm webpart with custom webpart with following code:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
try
{
SPLimitedWebPartManager NewForm = currentWeb.GetLimitedWebPartManager("Lists/listname1/NewForm.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
AddWebPart(NewForm);
}
catch (Exception)
{
throw;
}
}
protected void AddWebPart(SPLimitedWebPartManager MainPage)
{
MainPage.WebParts[0].Hidden = true;
MainPage.SaveChanges(MainPage.WebParts[0]);
try
{
var linqqry = from wp in MainPage.WebParts.Cast()
where wp.GetType() == typeof(Webpart1.Webpart1)
select wp;
if (linqqry.Count() == 0)
{
//Create an instance of WPMenu Webpart and add in a Webpart zone
Webpart1.Webpart1 wpWebPart = new Webpart1.Webpart1();
MainPage.AddWebPart(wpWebPart, "Main", 0);
MainPage.SaveChanges(wpWebPart);
}
}
catch (Exception ex)
{
}
}

The current user has insufficient permissions to perform this operation. Add Termset in sharepoint

I am trying to bind a field to a termset, and if the termset does not exist I want to create it by code. However, even when the code is running with elevated privileges I get the following exception.
The current user has insufficient permissions to perform this operation.
public static void BindTaxonomyField(string taxonomyFieldId, string taxonomyNoteFieldId, string termSetName, string termGroup, SPWeb web)
{
try
{
if (web != null)
{
// get the taxonomyfield from the sitecollection
var field = web.Fields[new Guid(taxonomyFieldId)] as TaxonomyField;
if (field != null)
{
// attach the note field
field.TextField = new Guid(taxonomyNoteFieldId);
// set up the field for my termstore
var session = new TaxonomySession(web.Site);
if (session.TermStores.Count > 0)
{
// get termstore values
TermStore ts = session.TermStores[0];
Group group = GetGroup(termGroup, ts);
if (group == null)
{
ts.CreateGroup(termGroup);
//throw new Exception("Group was not found in the termstore");
}
// ReSharper disable PossibleNullReferenceException
TermSet termSet = group.TermSets.Any(s => s.Name == termSetName) ? group.TermSets[termSetName] : group.CreateTermSet(termSetName);
// ReSharper restore PossibleNullReferenceException
//TermSet termSet = group.TermSets[termSetName];
// actually setup the field for using the TermStore
field.SspId = ts.Id;
field.TermSetId = termSet.Id;
}
field.Update();
}
}
}
catch (Exception ex)
{
}
}
private void BindColumnsToTermStore(string url)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
if (!web.AllowUnsafeUpdates)
web.AllowUnsafeUpdates = true;
BindTaxonomyField("EF810CD2-F2D2-4BD2-9ABF-C19815F13568",
"67E6E777-0D1E-4840-B858-17400CFABD14",
"Business Audience", "IctDocumentation",
web);
web.AllowUnsafeUpdates = false;
}
}
});
}
If you go in to central administration and navigate to your term store(this is in the left hand nav) in the main container of the page there is a box with a few usernames. Is the account you are running the code in listed? If not stick them in there.
i think the path is something like Central admin -> Manage service application -> Managed meta data service - and the are on the page is call Term store Administrators
There is also one more place you must check but check this first and them run again.
The next place to check is to highlight your Manage metadata service which is located
Central admin -> Manage service application
and click on permissions on the ribbon and make sure the users your running the code with has the correct access.
I always start by making sure i know who i am running the code as first of all then do the checks

C# Facebook SDK: How to

I have tried to find answers on following questions for at least one hour but with no success.
I have WPF project (C#) and I have webBrowser control to navigate to my Facebook page http://www.facebook.com/TennisHelper and I want to do next few things:
I want to avoid login by creating user settings in my application which will contain email and password, but I don't know how to do that with C# Facebook SDK,
I want to make able for my user to post textual posts on that page via textBox control,
I want to make able for my user to post photos from his computer directly to that page, but with not creating new albums. Just to post image on page wall.
I was searching Google for all those problems but with no success
Let me know actually what is your requirement.I think your first requirement is to add a facebook login(or register with facebook page) button in your Website login page.
step1:You need to register a new facebook application on facebook.
step 2:install facebook c# sdk .You can either download the zip file manually or install it using nuget.I recommend the second option.I am using c# sdk 5.4.1 What is nuget? How to install a package using nuget?
step 3:Now you can add name space facebook to the page
step 4:Insert a login button(simply a button with text login) in login page(say login.aspx).Let it be button1
step 5:On click button redire to another page (let login1.aspx)
here is a sample code for login 1
using Facebook;//
FacebookOAuthClient fb = new FacebookOAuthClient();
UriBuilder red = new UriBuilder("www.example.com/Login1.aspx");
protected void Page_Load(object sender, EventArgs e)
{
string appid = "{your app id}";
string appsecret = "{your app secret}";
string permissions = "publish_stream";
if(Request.QueryString["code"] == null)
{
try
{
Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=" + red.Uri.ToString() + "&scope=" + permissions +"&state=djfjfdjj");
}
catch (Exception b)
{
Label1.Text = b.ToString();
}
}
else
{
try
{
FacebookOAuthClient cl = new FacebookOAuthClient();
cl.RedirectUri = red.Uri;
cl.AppId = appid;
cl.AppSecret = appsecret;
dynamic result = cl.ExchangeCodeForAccessToken(Request.QueryString["code"]);
Label1.Text = Convert.ToString(result);
if (result["access_token"] != null)
{
Session["access_token"] = result["access_token"].ToString();//Now you have access token
Response.Redirect("Welcome.aspx");//replace welcome.aspx
}
else
{
Label1.Text = "Unable to authenticate\n Please try again later";
}
}
catch(Exception b)
{
Label1.Text = b.ToString();
}
}
}
Now you have access token saved in session.
for getting basic information of the client
dynamic me=fb.Get("\me");
it in cludes first name, last name ,email address,location,image url etc. of the current user.Now you can use this e-mail or name to verify your user or register new user etc.(its up to you ).
posting on that page is possible but diffiult How can I use the Facebook C# SDK to post on Facebook Pages
You should register an application on Facebook in order to use Facebook log in.navigate to
http://developers.facebook.com
create an appllication.You will get an application id and application secret.Use it as appid,appsecret

Categories