PhoneCallTask fails - windows-phone-7

This is a really simple task but somehow it fails...
private void TextBlock_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (WasSwipe != true)
{
//JUST TO CHECK THAT CODE GETS HERE - RUNS PERFECT
MessageBox.Show("");
//FUNCTION
var phoneCallTask = new PhoneCallTask
{
DisplayName = "Kunal Chowdhury",
PhoneNumber = "0208795446322"
};
phoneCallTask.Show();
//FAILS HERE, AFTER SHOW
}
else
{
WasSwipe = false;
}
}
When i want to show task it fails with this:
Message: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Source: Microsoft.Phone
Stack-trace: at Microsoft.Phone.Tasks.PhoneCallTask.NativeMethods.PhoneInitiateOutgoingPhoneCall_External(String
pDialString, String pDisplayName)
at Microsoft.Phone.Tasks.PhoneCallTask.PhoneDial(Object
phoneCallTask)
at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
IN ADDITION:
Email task works:
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.Subject = "message subject";
emailComposeTask.Body = "message body";
emailComposeTask.To = "recipient#example.com";
emailComposeTask.Cc = "cc#example.com";
emailComposeTask.Bcc = "bcc#example.com";
emailComposeTask.Show();

You probably didn't specify following permission in your app manifest file:
ID_CAP_PHONEDIALER

Related

Background Job Fails with "Current user did not login to the application"

using MVC jQuery .NET Core
using Abp Background Job
I have a background job that get Enqueued correctly and I can see the job in the db.
However the logging shows me I'm getting and authorization error (ee below) despite being logged in. I have the same AbpAuthorize attributes placed on the services and background jobs.
Not sure how to proceed debugging the problem - any suggestions welcome.
SERVICE CODE USING/ENQUEUING THE JOB:
public async Task BulkImportBackground(IList<CreatePracticeDto> inputs)
{
await _backgroundJobManager.EnqueueAsync<ImportBulkPracticesBackgroundJob, ImportBulkPracticesBackgroundJobArgs>(
new ImportBulkPracticesBackgroundJobArgs
{
CreatePracticeDtos = inputs
});
_backgroundJobManager.Start();
}
JOB CLASS CODE:
using Abp.Authorization;
using Abp.BackgroundJobs;
using Abp.Dependency;
using Abp.Modules;
using Gp.Authorization;
using Gp.Ccre.ImportResult;
using Gp.Ccre.ImportResult.Dtos;
using Gp.Ccre.Practice.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using Abp.Domain.Uow;
namespace Gp.Ccre.Practice.BackgroundJobs
{
[DependsOn(
typeof(IPracticeAppService),
typeof(IImportResultsAppService))]
[AbpAuthorize(PermissionNames.Pages_Practices, RequireAllPermissions = false)]
public class ImportBulkPracticesBackgroundJob : BackgroundJob<ImportBulkPracticesBackgroundJobArgs>, ITransientDependency
{
private readonly IPracticeAppService _practiceAppService;
private readonly IImportResultsAppService _importResultsAppService;
public ImportBulkPracticesBackgroundJob(IImportResultsAppService importResultsAppService, IPracticeAppService practiceAppService)
{
_practiceAppService = practiceAppService;
_importResultsAppService = importResultsAppService;
}
public override void Execute(ImportBulkPracticesBackgroundJobArgs args)
{
IList<CreateImportResultDto> createResultsDto = new List<CreateImportResultDto>();
var k = 0;
DateTime importedOn = DateTime.Now;
foreach (CreatePracticeDto createDto in args.CreatePracticeDtos)
{
k++;
try
{
//this correctly automatically ignores 'soft' deleted records.
var count = _practiceAppService.GetAllIdName().Result.Count(x => x.Name.Equals(createDto.Name, StringComparison.CurrentCultureIgnoreCase));
if (count > 0)
{
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = "Already exists. Skipped.",
MessageType = AppConsts.ImportMessageType.Warning.ToString(),
ImportedOn = importedOn
});
continue;
}
// ** GOOGLE MAP API CALL **
var coordinatesFound = false; //_practiceAppService.TryGetGeoCodeAddress(createDto);
createDto.ImportedOn = importedOn;
// *** SAVE SINGLE ****
_practiceAppService.Create(createDto);
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = "Successful.",
MessageType = AppConsts.ImportMessageType.Info.ToString(),
ImportedOn = importedOn,
GoogleMapCoordinatesFound = coordinatesFound
});
}
catch (Exception e)
{
createResultsDto.Add(new CreateImportResultDto
{
Row = k,
Name = createDto.Name,
Message = e.Message,
MessageType = AppConsts.ImportMessageType.Error.ToString(),
ImportedOn = importedOn
});
continue;
}
}
//*** SAVE RESULTS ***
foreach (var resultDto in createResultsDto)
{
_importResultsAppService.Create(resultDto);
}
CurrentUnitOfWork.SaveChanges();
}
}
[Serializable]
public class ImportBulkPracticesBackgroundJobArgs
{
public IList<CreatePracticeDto> CreatePracticeDtos { get; set; }
}
}
STACK TRACE (partial)
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Abp.Authorization.AbpAuthorizationException: Current user did not login to the application!
at Abp.Authorization.AuthorizationHelper.AuthorizeAsync(IEnumerable`1 authorizeAttributes) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 43
at Abp.Authorization.AuthorizationHelper.CheckPermissions(MethodInfo methodInfo, Type type) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 98
at Abp.Authorization.AuthorizationHelper.AuthorizeAsync(MethodInfo methodInfo, Type type) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationHelper.cs:line 57
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
at Abp.Authorization.AuthorizationInterceptor.Intercept(IInvocation invocation) in D:\Github\aspnetboilerplate\src\Abp\Authorization\AuthorizationInterceptor.cs:line 20
at Castle.DynamicProxy.AbstractInvocation.Proceed()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Abp.BackgroundJobs.BackgroundJobManager.TryProcessJob(BackgroundJobInfo jobInfo) in D:\Github\aspnetboilerplate\src\Abp\BackgroundJobs\BackgroundJobManager.cs:line 119
The problem was caused by trying to inject a service into the background job. stick to IRepository and all good.

OpenAuth / Google API donet An existing connection was forcibly closed by the remote host

I am using open auth with google api's to authenticate users using .NET. I have been receiving this error on a sever with a high level of requests. On smaller servers there is no issue. I can't find any documentation to help me verify that this is related to sending to many requests. I thought perhaps someone else has seen these excpetions and found the root cause. Thanks!
Edit: Added code sample
X509Certificate2 certificate = new X509Certificate2(svcAccount_FilePath, "password", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountUser = username,
ServiceAccountId = label,
Scope = scope
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth
});
var listReq = service.Users.List();
listReq.Domain = emailServer.domainServerIP;
listReq.MaxResults = 1;
Users results = listReq.Execute()
Exception thrown on the listReq.Execute()
DotNetOpenAuth.Messaging.ProtocolException: Web request to 'https://accounts.google.com/o/oauth2/token' failed. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.TlsStream.CallProcessAuthentication(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.ConnectStream.WriteHeaders(Boolean async)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
at System.Net.HttpWebRequest.GetRequestStream()
at DotNetOpenAuth.Messaging.StandardWebRequestHandler.GetRequestStreamCore(HttpWebRequest request)
--- End of inner exception stack trace ---
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
You appear to be mixing dotnetopenauth with the Google .net client library. that is not going to work at all. The Google .net client library has its own auth module.
The following code is ripped from my sample project.
you apear to be trying to use a service account
public static DirectoryService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Analytics service.
return new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Directory Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the Directory service.
return new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Directory Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
throw new Exception("CreateServiceAccountDirectoryFailed", ex);
}
}
I am not very familiar with dotnetopenauth but it looks like you are either behind a proxy or a fire wall and its not letting you though.

How to get output value (customOut) from EnvDTE Commands.Raise method?

I am writing a Visual Studio 2012 add-in that needs to send a command to the built-in T-SQL Editor. The command in question, sqlEditorSqlDatabaseCommand, can be used to either set or get the name of the current database in the editor. Here is some (working) code that sets the database name:
const string guidSqlEditorCommandSet = "b371c497-6d81-4b13-9db8-8e3e6abad0c3";
const int sqlEditorSqlDatabaseCommand = 0x312;
object customIn = "myDatabaseName";
object customOut = null;
m_applicationObject.Commands.Raise(guidSqlEditorCommandSet, sqlEditorSqlDatabaseCommand, ref customIn, ref customOut);
The problem is, I need to get the current database name, which would require use of the customOut parameter, and I can't figure out how to make customOut work.
The implementation of sqlEditorSqlDatabaseCommand is as follows (via Reflector):
protected override int HandleExec(uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
AuxiliaryDocData auxiliaryDocDataForEditor = base.GetAuxiliaryDocDataForEditor();
if (auxiliaryDocDataForEditor != null)
{
QueryExecutor queryExecutor = auxiliaryDocDataForEditor.QueryExecutor;
if (queryExecutor != null)
{
if (pvaIn != IntPtr.Zero)
{
string objectForNativeVariant = (string) Marshal.GetObjectForNativeVariant(pvaIn);
this.SetDatabase(auxiliaryDocDataForEditor, objectForNativeVariant);
}
else if (pvaOut != IntPtr.Zero)
{
object database = string.Empty;
IDbConnection connection = queryExecutor.ConnectionStrategy.Connection;
if (((connection != null) && (connection.State == ConnectionState.Open)) && !string.IsNullOrEmpty(connection.Database))
{
database = connection.Database;
}
else
{
database = string.Empty;
}
Marshal.GetNativeVariantForObject(database, pvaOut);
}
}
}
return 0;
}
According to every marshaling example I've seen, I should be able to pass null for both customIn and customOut, and the database name should be placed in customOut. When I do this, I get an E_INVALIDARG exception from Commands.Raise:
System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
at EnvDTE.Commands.Raise(String Guid, Int32 ID, Object& CustomIn, Object& CustomOut)
at RDSVisualStudioAddIn.Exec(String commandName, vsCommandExecOption executeOption, Object& varIn, Object& varOut, Boolean& handled) in c:\RDS\RDSVisualStudioAddIn\Connect.cs:line 193
Has anyone used Commands.Raise with the customOut parameter?

EPPLUS - Unable to save in different folder

I'm trying to save the excel file. It working fine if i save the file in same location but if i wanted to save different location it throwm me error.
Error:
System.NotSupportedException was unhandled
Message=The given path's format is not supported.
Source=mscorlib
StackTrace:
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.Create(String path)
at Report.Form1.ExportToExcelReport(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 142
at Report.Form1.button2_Click(Object sender, EventArgs e) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 113
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Report.Program.Main() in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
My Code
FileInfo newFile = new FileInfo("C:\\Excel\\SampleStockTakeReport.xlsx");
ExcelPackage pck = new ExcelPackage(newFile);
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
ws.View.ShowGridLines = false;
ws.Cells["G13"].Value = "Rent";
ws.Cells["G14"].Value = "Level 1";
ws.Cells["G15"].Value = "Cell 1";
ws.Cells["V14"].Value = "Level 3";
ws.Cells["V15"].Value = "Cell 3";
ws.Cells["W12"].Value = "Bukit Raja";
ws.Cells["AJ13"].Value = "Row 1";
var tracksql = new TrackingSql();
var numberoftag = tracksql.getNumberofTag();
ws.Cells["S19"].Value = DateTime.Now;
ws.Cells["Y19"].Value = numberoftag.ToString();
var numberoftagscanned = 9;
var diff = numberoftag - numberoftagscanned;
ws.Cells["Q22"].Value = numberoftagscanned;
ws.Cells["X22"].Value = numberoftag;
ws.Cells["AD22"].Value = diff;
var thispath = "testing path for report";
Stream stream = File.Create(path); // throw error here
pck.SaveAs(stream);
System.Diagnostics.Process.Start(path);
MessageBox.Show("Report Generated at " + path + "");
Appreciated if anyone could advice/help on this.
This issue is not related to EPPlus. You get the NotSupportedException at
Stream stream = File.Create(path);
which is documented here: File.Create Method (String)
So this "path is in an invalid format." because of the colons in the time-part of DateTime.Now:
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + DateTime.Now + ".xlsx";
So this should work:
var dayPart = DateTime.Now.ToString("yyyy-MM-dd");
var path = "C:\\Excel\\Report\\SampleStockTakeExceptionReport" + dayPart + ".xlsx";
If you need the time part, you could create a custom DateTimeFormatInfo:
var timeFormat = (DateTimeFormatInfo)CultureInfo.CurrentCulture.DateTimeFormat.Clone();
timeFormat.TimeSeparator = "_";
var dayPart = DateTime.Now.ToString(timeFormat); // replaces the colons with _ implicitely
You need to format DateTime.Now to something like DateTime.Now.ToString("MMddyyyy");

Error updating Sharepoint List item, when called from web service

I'm using ajax to call a webservice which updates a sharepoint list.
It works when I call the code from unit tests, but running the code in a browser causes an exception:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context)
at Microsoft.SharePoint.SPContext.get_Current()
at Microsoft.SharePoint.SPListItem.AddOrUpdateItem(Boolean bAdd, Boolean bSystem, Boolean bPreserveItemVersion, Boolean bNoVersion, Boolean bMigration, Boolean bPublish, Boolean bCheckOut, Boolean bCheckin, Guid newGuidOnAdd, Int32& ulID, Object& objAttachmentNames, Object& objAttachmentContents, Boolean suppressAfterEvents)
at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion, Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish, Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents)
at Microsoft.SharePoint.SPListItem.Update()
My code to update the list item is:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb(path))
{
SPList userProfile = web.Lists[userList];
SPQuery qry = new SPQuery
{
Query =
"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" +
accountName +
"</Value></Eq></Where><ViewFields><FieldRef Name='ID' /><FieldRef Name='Title' /><FieldRef Name='LastUpdated' /><FieldRef Name='Reason' /></ViewFields>"
};
SPListItemCollection spListItemCollection = userProfile.GetItems(qry);
if (spListItemCollection.Count == 1)
{
//edit user
SPListItem item = spListItemCollection[0];
item["Updated"] = DateTime.Now;
item["Reason"] = updateReason;
item.Update();
}
}
}
});
It errors on item.Update();
Try adding this:
HttpContext context = HttpContext.Current;
if (HttpContext.Current != null)
{
if (context.Items["HttpHandlerSPWeb"] == null)
context.Items["HttpHandlerSPWeb"] = site.RootWeb;
if (context.Items["Microsoft.Office.ServerContext"] == null)
context.Items["Microsoft.Office.ServerContext"] = ServerContext.GetContext(site);
}
The problem was with security. The following line needs to be added (although not ideal)
web.AllowUnsafeUpdates = true;
I also removed the line
SPSecurity.RunWithElevatedPrivileges(delegate()
and changed the SPSite and SPWeb to not use "using".

Resources