Sharepoint 2010 SPImport.Run security exception - c#

I want to use SPExport (which is working OK) and SPImport to copy one web to another location. I am using Application Page in Sharepoint Foundation 2010. This code is executed on a Button click event.
using (SPWeb web = site.OpenWeb(sourceWebUrl))
{
SPExportSettings exportSettings = new SPExportSettings();
exportSettings.FileLocation = exportPath;
exportSettings.BaseFileName = exportFileName;
exportSettings.SiteUrl = site.Url;
exportSettings.ExportMethod = SPExportMethodType.ExportAll;
exportSettings.FileCompression = true;
exportSettings.IncludeVersions = SPIncludeVersions.All;
exportSettings.IncludeSecurity = SPIncludeSecurity.All;
exportSettings.ExcludeDependencies = false;
exportSettings.ExportFrontEndFileStreams = true;
exportSettings.OverwriteExistingDataFile = true;
SPExportObject expObj = new SPExportObject();
expObj.IncludeDescendants = SPIncludeDescendants.All;
expObj.Id = web.ID;
expObj.Type = SPDeploymentObjectType.Web;
exportSettings.ExportObjects.Add(expObj);
SPExport export = new SPExport(exportSettings);
export.Run();
}
using (SPWeb web = site.OpenWeb(destinationWebUrl))
{
web.AllowUnsafeUpdates = true;
SPImportSettings importSettings = new SPImportSettings();
web.FileLocation = exportPath;
web.BaseFileName = exportFileName;
web.IncludeSecurity = SPIncludeSecurity.All;
web.UpdateVersions = SPUpdateVersions.Overwrite;
web.RetainObjectIdentity = false;
web.SiteUrl = site.Url;
web.WebUrl = web.Url;
web.Validate();
SPImport import = new SPImport(importSettings);
import.Run();
web.AllowUnsafeUpdates = false;
}
Exception "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. " is thrown when SPImport.Run() is called.
I haven't been able to find a solution for this problem neither adding FormDigest control on application page nor Allowing Unsafe Updates on the destination web.
Also, running this code from Console Application works OK, but if code runs from Application Page it is not working (even with elevated security).
Any help would be appreciated. Thanks.

Managed to do this by adding
SPUtility.ValidateFormDigest();
at line 1.

Related

Save browser data in CefSharp

I have an Windows Form Application which utilises CefSharp.
A while ago I used a chunk of code that saves the state of the browser such as login details etc so that the user does not have to log in multiple times.
This is the code I used:
private static bool _hasRun;
CefSettings settings = new CefSettings();
if (!_hasRun)
{
Cef.Initialize(new CefSettings { CachePath = "MyCachePath", PersistSessionCookies = true });
}
_hasRun = true;
string cache_dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\CEF";
settings.CachePath = cache_dir;
settings.CefCommandLineArgs.Add("persist_session_cookies", "1");
string link = Domain;
chrome = new ChromiumWebBrowser(link);
this.tabPage2.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
This code runs fine in my old application but when using this on my most recent app I receive this error message:
Any suggestions?
You must provide a full path.
non-absolute: "MyCachepath"
absolute: "C:\users\username\documents\MyCachepath"
why did it work in older projects?
Some project types and versions automaticallly translate an relative path into an absolute path like so:
environment.CurrentDirectory + #"\MyCachepath"

Why I can't insert a file into a SharePoint list via code? It goes into exception, seems that the access is denied

I am very new in SharePoint (I am using SharePoint 2013) and I am experiencing a strange problem. This is very strange because in another section of my application it works fine (in another subsite).
So basically into SharePoint I have a SharePoint list named Protocollo.
My code contains the following lines that add a document (a file) into a subfolder of the previous SharePoint List:
internal static int InsertItem(Dictionary<string, object> prot, Documento doc, bool assignVisibility, bool newItem)
{
int state = 0;
SPListItem item = null;
UOR currUOR = null;
List<UOR> path = new List<UOR>();
SPWeb web = SPContext.Current.Web;
string siglaAOO = web.Properties["sigla_aoo"];
DBConnection dbConfig = ArxeiaProtocollo.Util.ProtUtils.InitializeDBConnection();
dbConfig.Database = siglaAOO;
string username = web.CurrentUser.LoginName;
try
{
SPList list = web.Lists["Protocollo"];
web.AllowUnsafeUpdates = true;
SPFolderCollection folders = list.RootFolder.SubFolders;
SPFolder annoFolder;
DateTime dateProt = Convert.ToDateTime(prot["Data protocollo"]);
try
{
annoFolder = folders[dateProt.Year.ToString()];
}
catch
{
annoFolder = folders.Add(dateProt.Year.ToString());
}
SPFolder meseFolder;
try
{
meseFolder = annoFolder.SubFolders[dateProt.Month.ToString("D2")];
}
catch
{
meseFolder = annoFolder.SubFolders.Add(dateProt.Month.ToString("D2"));
}
SPFolder dayFolder;
try
{
dayFolder = meseFolder.SubFolders[dateProt.Day.ToString("D2")];
}
catch
{
dayFolder = meseFolder.SubFolders.Add(dateProt.Day.ToString("D2"));
}
SPFile spFile = dayFolder.Files.Add(doc.Nome, doc.File, true);
............................................................
............................................................
............................................................
}
As you can see the previous code retrievce the Protocollo list from the current website allowing updates on it by:
SPList list = web.Lists["Protocollo"];
web.AllowUnsafeUpdates = true;
Then into this list it creates (it doesn't exist) a gerarcic folders structure for year (annoFolder), month (meseFolder) and day (dayFolder).
It works fine, I tried to delete these folder structure from my SharePoint site and performing this method it is created again, infact this is what I obtained:
As you can see it correctly creates this folder structure into my SharePoint list (named Protocollo) into the current website.
Ok finnally my code try to insert a document into the last subfolder (the dayfolder) by:
SPFile spFile = dayFolder.Files.Add(doc.Nome, doc.File, true);
I am passing to the Add() method: the name of the file, the byte array representing the file and the true boolean value.
The problem is that performing this line I obtain the following exception that is not providing information:
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}
Then in my front end it appears a "denied access" popup window.
The strange thing is that another sites in my SharePoint that uses the same code have no problem. Another strange thing is that manually uploading the file into this location of the list it works fine so I think that it should not be a user permission problem.
Some idea? What can I try to do to solve this strange problem?
SharePoint codes run using the Application Pool user in IIS not the user that you have logged in to SharePoint, so it is common to get an access denied error even when you have access. So I would suggest you check the permission for the AppPool account on the Protocollo library. Or you can use SPSecurity.RunWithElevatedPrivileges if you have trust in the user that will run the code.
Beware of the pitfalls though.
Here is a sample usage:
Guid siteId = SPContext.Current.Site.ID;
Guid webId = SPContext.Current.Web.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteId))
{
using (SPWeb web = site.OpenWeb(webId))
{
// Your code here
}
}
});

ASP.NET Session has expired or could be found in SharePoint 2007

I'm trying to load an .rdlc file in SharePoint 2007 but it is not getting loaded and the following error is coming on that Report Page.
Below mentioned is the code which I've used.
Kindly help what modifications I should have to do.
if (!Page.IsPostBack)
{
this.EnableViewState = true;
rptViewer.Reset();
rptViewer.LocalReport.EnableHyperlinks = true;
rptViewer.KeepSessionAlive = true;
rptViewer.EnableViewState = true;
rptViewer.ProcessingMode = ProcessingMode.Local;
rptViewer.LocalReport.ReportPath = #"C:\New folder\RDLC\RiskReports\RiskReports\Report1.rdlc";
}
It would be a great help and appreciation.

How to list all the users with One Drive in one Office365 domain?

We're using the SharePoint Client Object Model SDK to access Office 365, there's no API to get all the users who has one drive. How can we do that?
There'r is a PowerShell script solution on MSDN, can we implement it with only C# code?
Based on the PowerShell Script from MSDN, I figured it out how to do it in C#:
On command line, run WSDL.exe to generate the proxy code for the user profiler service:
wsdl https://xxxx-admin.sharepoint.com/_vti_bin/UserProfileService.asmx?wsdl /username:aaaaa /password:ppppp
Add the generated file "UserProfileService.cs" to the project
The following code will list all the users with OneDrive:
UserProfileService uprofService = new UserProfileService();
uprofService.Url = adminPortalUrl + "/_vti_bin/UserProfileService.asmx";
uprofService.UseDefaultCredentials = false;
Uri targetSite = new Uri(url);
uprofService.CookieContainer = new CookieContainer();
string authCookieValue = spCredentials.GetAuthenticationCookie();
uprofService.CookieContainer.SetCookies(targetSite, authCookieValue);
var userProfileResult = uprofService.GetUserProfileByIndex(-1);
long numProfiles = uprofService.GetUserProfileCount();
while (userProfileResult.NextValue != "-1")
{
string personalUrl = null;
foreach(var u in userProfileResult.UserProfile)
{
/* (PersonalSpace is the name of the path to a user's OneDrive for Business site. Users who have not yet created a OneDrive for Business site might not have this property set.)*/
if (u.Values.Length != 0 && u.Values[0].Value != null && u.Name == "PersonalSpace" )
{ personalUrl = u.Values[0].Value as string;
break;
}
}
int nextIndex = -1;
nextIndex = Int32.Parse(userProfileResult.NextValue);
userProfileResult = uprofService.GetUserProfileByIndex(nextIndex);
}

C# web browser save search engine settings

I'm working on a web browser where the default search engine is Google until the user clicks on the Yahoo (or another search engine) button. The problem is, after you start a new session, it opens with Google again. How to you save that?
I'm aware how to save settings with Properties.Settings.Default.Save(); however it doesn't seem to work with a click event. (Where the code is to change the search engine)
I'm using GeckoFX. Code for the Yahoo setting is:
goo.Enabled = true;
y.Enabled = false;
bin.Enabled = true;
ba.Enabled = true;
ya.Enabled = true;
sear.Text = "Yahoo!";
And is performed with:
if (y.Enabled == false)
{
W.Navigate("search.yahoo.com/search?p=" + q.Text);
W.Select();
}

Categories

Resources