Adding CampaignActivityItem in CRM 2011 gives 403 error - silverlight-4.0

I am creating a Silverlight 4 web resource in CRM 2011 using the Otganizational Data service. I am able to create Campaigns, Marketing Lists, and Print Activities as well as linking the lists to the campaigns. However when I go to link the marketing lists to the print activity using the CampaignActivityItem I get a 403 Forbidden error. Below is the code I am using.
Models.CampaignActivityItem activityItem = new CampaignActivityItem()
{
CampaignActivityItemId = Guid.NewGuid(),
ItemId = EmailMarketingList.ListId, //Id of my marketing list I have
//already created
CampaignActivityId = new Models.EntityReference()
{
Id = MyCampaignPrintActivity.ActivityId, //Id of the print activity
//I have already created
LogicalName = "CampaignActivity",
Name = "CampaignActivity"
}
};
context.AddObject("CampaignActivityItemSet", activityItem);
context.BeginSaveChanges(System.Data.Services.Client.SaveChangesOptions.ContinueOnError, OnChangesSaved, context);
private void OnChangesSaved(IAsyncResult result)
{
// Use the Dispatcher to ensure that the
// asynchronous call returns in the correct thread.
OnUiThread(() =>
{
try
{
DataServiceResponse response = context.EndSaveChanges(result);
}
catch (DataServiceRequestException ex) // Errors with code=403
// message=Forbidden
{
WriteOperationResponse(ex.Response, "ListLink");
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
);
}
Any direction on what I am doing wrong would be greatly appreciated. Using the context I am able to perform actions on other objects but not the CampaignActivityItemSet.

Related

Exception shows up in console although try...catch must prevent it

In my minimal API I try to save entity to database. The table contains UNIQUE constraint on license_plate column, so DbUpdateException would be thrown if same license plate would be passed in. I used try..catch in order to handle this situation:
app.MapPost("/vehicles", (VehiclesContext db, Vehicle vehicle) =>
{
var entity = db.Add(vehicle);
try
{
db.SaveChanges();
return Results.CreatedAtRoute("GetVehicle", new { inventoryNumber = entity.Entity.InventoryNumber }, entity.Entity);
}
catch (DbUpdateException)
{
var error = new JsonObject
{
["error"] = $"Creating vehicle failed because such license plate already exists: {vehicle.LicensePlate}"
};
return Results.BadRequest(error);
}
}).AddFilter<ValidationFilter<Vehicle>>();
However, when I pass duplicate license plate, I see this exception in console:
So, why does this exception show up in console? I tried to play with LogLevel for Microsoft.AspNetCore in appsettings.json (and appsettings.Development.json also) by changing Warning to Information, but still exceptions shows up.
The exception is logged prior to throwing, so you cannot stop the logging mechanism from being invoked.
However, you should be able to control output using LogLevel.
Note that the log comes from "Microsoft.EntityFrameworkCore" not "Microsoft.AspNetCore".
I just don't want to see errors which I handle in try...catch block!
Do you mean you don't want to see the fail ? Use Try-catch in minimal API?
Below is a demo, you can refer to it.
without try-catch
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () =>{
string s = null;
if (s == null)
{
throw new ArgumentNullException(paramName: nameof(s), message: "parameter can't be null.");
}}
);
app.Run();
result:
use try-catch:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () =>{
try
{
string s = null;
if (s == null)
{
throw new ArgumentNullException(paramName: nameof(s), message: "parameter can't be null.");
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
);
app.Run();
result:

how can I fix this error, The message filter indicated that the application is busy

I keep getting this error in word, excel powerpoint how can i fix it
Error=The message filter indicated that the application is busy.
(Execption from HRESULT: 0x8001010A(RPC_E_SERVERCALL_RETRYLATER))
foreach (Presentation document in Globals.ThisAddIn.Application.Presentations.Cast<Presentation>().ToList())
{
while (document.ReadOnly!= Microsoft.Office.Core.MsoTriState.msoTrue)
{
break;
}
var item = FODocumentRepository.GetByLocalPath(document.FullName);
if (item == null)
{
if (DocHelper.IfFileOrbisDocument(document.FullName))
{
FODocumentRepository.Add(document.FullName, document.FullName);
}
}
}
var repositoryList = FODocumentRepository.GetAll().ToList();
// var abc = Globals.ThisAddIn.Application.Workbooks.Cast<Workbook>().Select(x => x.FullName).ToList();
List<FODocument> deleteList = new List<FODocument>();
foreach (var item in repositoryList)
{
bool founded = false;
foreach (Presentation document in Globals.ThisAddIn.Application.Presentations)
{
if (item.LocalPath == document.FullName)
{
founded = true;
break;
}
}
if (!founded)
{
MessageBox.Show("DocumentClosed");
FileorbisConflictManager.DocumentClosed(ServiceSettings.GetToken(), DocHelper.GetDocumentKey(item.FOPath),DocumentType.PowerPoint);
deleteList.Add(item);
}
}
foreach (var item in deleteList)
{
FODocumentRepository.Remove(item.LocalPath);
}
These kind of errors occur due to threading contention issues between external multi-threaded applications and Visual Studio. They can be eliminated by implementing IOleMessageFilter error handlers in your Visual Studio automation application. Read more about that in the How to: Fix 'Application is Busy' and 'Call was Rejected By Callee' Errors article.
Also you can find the same issue described on the Exception thread.

change phone number in asp identity

I have problem with updating of phone number in my ASP net core application.
All fields except phone number are saving in DB. I tried 3 different ways to update phone:
set manualy
use UserManager.SetPhoneNumberAsync()
use UserManager.ChangePhoneNumberAsync() with token generation
All of them are not working. And there are no any errors. Help me please
[HttpPost][AllowAnonymous]
public async Task UpdateLogin(UpdateAccountRequest request)
{
try {
var user = await UserService.FindExistingUserAsync(request.CurrentEmail, request.CurrentPhoneNumber);
var account = user.Accounts.SingleOrDefault(x = > x.AccountId == request.AccountId);
account.FirstName = request.PatientFirstName;
account.LastName = request.PatientLastName;
var changePhoneNumberToken = await UserManager.GenerateChangePhoneNumberTokenAsync(user, request.UpdatedPhoneNumber);
var changePhoneResult = await UserManager.ChangePhoneNumberAsync(user, request.UpdatedPhoneNumber, changePhoneNumberToken);
if (!changePhoneResult.Succeeded) {
return StatusCode(StatusCodes.Status500InternalServerError, changePhoneResult.Errors);
}
var updateResult = await UserManager.UpdateAsync(user);
if (!result.Succeeded) {
return StatusCode(StatusCodes.Status500InternalServerError);
}
return Ok("User updated");
}
catch (Exception ex) {
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
Problem disappeared. Loks like DB was not updated

Accessing HttpContext.Session from static method

I am getting following error when accessing HttpContext.Session from static method placed in separate task:
Session has not been configured for this application or request.
I used this article to implement access to HttpContext outside the controller
From controller I invoke this static method that used to retrieve image data:
public static void CreateDummyGallery(Gallery gallery)
{
Logger.LogDebug(LogModule.Dummy, $"Starting gallery creation.");
Task.Factory.StartNew(() =>
{
try
{
List<DummyPicture> pictures;
using (var context = new MyzeumContext())
{
int top = 10;
pictures = context.DummyPictures.FromSql($"SELECT * FROM dummypictures ORDER BY RAND() LIMIT {top}").ToList();
}
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
Parallel.ForEach(pictures, picture => {
using (WebClient client = new WebClient())
{
}
});
Logger.LogDebug(LogModule.Dummy, $"Done retrieving images.");
}
catch(Exception e)
{
Logger.LogError(LogModule.Server, e.Message, e);
}
});
}
The problem occurs in Logger.LogDebug() because this is where I access HttpContext:
public void LogDebug(LogModule module, string message, Exception stackTrace = null)
{
Log record = new Log();
record.Module = module;
record.ThreadId = Environment.CurrentManagedThreadId;
record.SessionId = HttpContextHelper.Current?.Session?.Id;
record.Message = message;
record.Logged = DateTime.UtcNow;
if(stackTrace != null)
{
record.Message += $" :{stackTrace.StackTrace}";
}
queue.Enqueue(record);
}
The problem 99% occurs in the first call inside task:
Logger.LogDebug(LogModule.Dummy, $"Starting retrieving images.");
BUT, right after application starts this whole task block works fine and does not throw any exception. Problem starts after following requests.

Flurl Post Not Returning from Web Api

I've got a Xamarin application using Flurl, with the following post to a Web Api
Xamarin App:
private async Task<LoginResponse> processLogin()
{
try
{
return await "http://192.168.0.12:60257/api/loginapi/Login".WithTimeout(10).PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson<LoginResponse>();
}
catch (Exception e)
{
return new LoginResponse { ResponseStatusCode = -1 };
}
}
Web Api:
public LoginResponse Login([FromBody]LoginRequest loginRequest)
{
var result = new LoginResponse();
try
{
var user = this.UserManager.FindAsync(loginRequest.username, loginRequest.password);
if (user != null)
{
result.ResponseStatusCode = 1;
}
else
{
result.ResponseStatusCode = 0;
}
}
catch (Exception e)
{
result.ResponseStatusCode = -1;
}
return result;
}
I can see my Web Api method getting hit, and it returns the expected object type, not my Xamarin application continues to wait on the Flurl Post.
Can anyone advise what I might be doing wrong?
UPDATE:
I have noticed that the following does work, but it's not ideal:
dynamic result = await "http://192.168.0.12:60257/api/loginapi/Login".PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson();
Fixed it. For whatever reason, it was the type I was trying to return. Changing the object variable type to "dynamic" fixed this, and allowed me to deserialise the object correctly.
dynamic result = await "http://192.168.0.12:60257/api/loginapi/Login".PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson();
Returns a dynamic object with the properties I'd expect in the normal structure.
If anyone can enlighten my why I couldn't do:
LoginRequest result = ...
It'd be appreciated.