Cookies problem using web application asp net core - asp.net-mvc

I am working with a shopping cart application. I have developed an application that maintains user shopping carts using cookies. It was working perfectly until I have made some UI changes and now it is not working now I have no clue what I have done wrong because I am maintaining the cookies through c# backend code no interruption with the front end only reading these cookies and passing them into view model to show on cart panel. Here is my code
Startup.cs
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
Adding Items to Cart
public JsonResult AddToShoppingCart(UserProductVM model)
{
try
{
if (string.IsNullOrEmpty(model.SelectedSize))
return Json(new { status = false, msg = "Please select size to proceed." });
var result = ShoppingCartHelper.GetShoppingCartList(model, _httpContextAccessor);
if (result.Status <= 0)
return Json(new { status = false, msg = result.Message });
Response.Cookies.Delete("ShoppingCart");
Response.Cookies.Append("ShoppingCart", JsonConvert.SerializeObject(result.Data));
return Json(new { status = true, msg = "Success! added to shopping cart." });
}
catch (Exception ex)
{
return Json(new { status = false, msg = ex.Message.ToString() });
}
}
Reading From Cart
public static string GetShoppingCartFromCookies(IHttpContextAccessor _httpContextAccessor)
{
return _httpContextAccessor.HttpContext?.Request?.Cookies["ShoppingCart"]?.ToString();
}
Every Thing was working fine and now nothing works no cookies are added to the cookies list. This is the same code I have also the backup my application and when I run that application cookies are working perfectly but the problem is that it is with the old design I am not using that UI design anymore. This is the same code working in one application but not working with another application with a different UI.

Have you added the IHttpContextAccessor to dependency container ?
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

I have resolved my issue. The problem was basically I was adding base64 image string which was not working. When I comment on this line it worked perfectly no need to change any code.
public static GenericResponseDTO<List<ShoppingCartViewModel>> GetShoppingCartList(UserProductVM model, IHttpContextAccessor _httpContextAccessor)
{
var shoppingcartmodel = new List<ShoppingCartViewModel>();
var cartmodel = new ShoppingCartViewModel
{
RestaurantId = model.RestaurantId,
SubCategoryId = model.SubCategoryId,
RestaurantSubCategoryId = model.RestaurantSubCategoryId,
OrderGuid = Guid.NewGuid(),
Quantity = model.Quantity,
//ItemImage = model.ItemImage,
SelectedSize = model.SelectedSize.Split('-')[0],
SingleItemPrice = Convert.ToDecimal(model.SelectedSize.Split('-')[1]),
SubCategoryName = model.SubCategoryName,
TotalItemPrice = (model.Quantity * Convert.ToDecimal(model.SelectedSize.Split('-')[1]))
};
if (string.IsNullOrEmpty(GetShoppingCartFromCookies(_httpContextAccessor)))
shoppingcartmodel.Add(cartmodel);
else
{
shoppingcartmodel = JsonConvert.DeserializeObject<List<ShoppingCartViewModel>>(GetShoppingCartFromCookies(_httpContextAccessor));
if (shoppingcartmodel.Any(x => x.RestaurantSubCategoryId == model.RestaurantSubCategoryId))
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = new List<ShoppingCartViewModel>(), Status = -1, Message = "Item is alreay exists in your cart please remove and add another." };
shoppingcartmodel.Add(cartmodel);
}
return new GenericResponseDTO<List<ShoppingCartViewModel>> { Data = shoppingcartmodel, Status = 1 };
}
I have commented on the ItemImage line and it works like a charm. Maybe it helps someone else problem.

Related

Create team in GraphAPI returns always null

I am using GraphAPI SDK to create a new Team in Microsoft Teams:
var newTeam = new Team()
{
DisplayName = teamName,
Description = teamName,
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
},
Members = new TeamMembersCollectionPage()
{
new AadUserConversationMember
{
Roles = new List<String>()
{
"owner"
},
AdditionalData = new Dictionary<string, object>()
{
{"user#odata.bind", $"https://graph.microsoft.com/v1.0/users/{userId}"}
}
}
}
};
var team = await this.graphStableClient.Teams
.Request()
.AddAsync(newTeam);
The problem is that I get always null. According documentation this method returns a 202 response (teamsAsyncOperation), but the AddAsync method from SDK returns a Team object. Is there any way to get the tracking url to check if the team creation has been finished with the SDK?
Documentation and working SDK works different... As they wrote in microsoft-graph-docs/issues/10840, we can only get the teamsAsyncOperation header values if we use HttpRequestMessage as in contoso-airlines-teams-sample. They wrote to the people who asks this problem, look to the joined teams :)) :)
var newTeam = new Team()
{
DisplayName = model.DisplayName,
Description = model.Description,
AdditionalData = new Dictionary<string, object>
{
["template#odata.bind"] = $"{graph.BaseUrl}/teamsTemplates('standard')",
["members"] = owners.ToArray()
}
};
// we cannot use 'await client.Teams.Request().AddAsync(newTeam)'
// as we do NOT get the team ID back (object is always null) :(
BaseRequest request = (BaseRequest)graph.Teams.Request();
request.ContentType = "application/json";
request.Method = "POST";
string location;
using (HttpResponseMessage response = await request.SendRequestAsync(newTeam, CancellationToken.None))
location = response.Headers.Location.ToString();
// looks like: /teams('7070b1fd-1f14-4a06-8617-254724d63cde')/operations('c7c34e52-7ebf-4038-b306-f5af2d9891ac')
// but is documented as: /teams/7070b1fd-1f14-4a06-8617-254724d63cde/operations/c7c34e52-7ebf-4038-b306-f5af2d9891ac
// -> this split supports both of them
string[] locationParts = location.Split(new[] { '\'', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
string teamId = locationParts[1];
string operationId = locationParts[3];
// before querying the first time we must wait some secs, else we get a 404
int delayInMilliseconds = 5_000;
while (true)
{
await Task.Delay(delayInMilliseconds);
// lets see how far the teams creation process is
TeamsAsyncOperation operation = await graph.Teams[teamId].Operations[operationId].Request().GetAsync();
if (operation.Status == TeamsAsyncOperationStatus.Succeeded)
break;
if (operation.Status == TeamsAsyncOperationStatus.Failed)
throw new Exception($"Failed to create team '{newTeam.DisplayName}': {operation.Error.Message} ({operation.Error.Code})");
// according to the docs, we should wait > 30 secs between calls
// https://learn.microsoft.com/en-us/graph/api/resources/teamsasyncoperation?view=graph-rest-1.0
delayInMilliseconds = 30_000;
}
// finally, do something with your team...
I found a solution from another question... Tried and saw that it's working...

Large File upload to ASP.NET Core 3.0 Web API fails due to Request Body to Large

I have an ASP.NET Core 3.0 Web API endpoint that I have set up to allow me to post large audio files. I have followed the following directions from MS docs to set up the endpoint.
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.0#kestrel-maximum-request-body-size
When an audio file is uploaded to the endpoint, it is streamed to an Azure Blob Storage container.
My code works as expected locally.
When I push it to my production server in Azure App Service on Linux, the code does not work and errors with
Unhandled exception in request pipeline: System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.
Per advice from the above article, I have configured incrementally updated Kesterl with the following:
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel((ctx, options) =>
{
var config = ctx.Configuration;
options.Limits.MaxRequestBodySize = 6000000000;
options.Limits.MinRequestBodyDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
options.Limits.MinResponseDataRate =
new MinDataRate(bytesPerSecond: 100,
gracePeriod: TimeSpan.FromSeconds(10));
options.Limits.RequestHeadersTimeout =
TimeSpan.FromMinutes(2);
}).UseStartup<Startup>();
Also configured FormOptions to accept files up to 6000000000
services.Configure<FormOptions>(options =>
{
options.MultipartBodyLengthLimit = 6000000000;
});
And also set up the API controller with the following attributes, per advice from the article
[HttpPost("audio", Name="UploadAudio")]
[DisableFormValueModelBinding]
[GenerateAntiforgeryTokenCookie]
[RequestSizeLimit(6000000000)]
[RequestFormLimits(MultipartBodyLengthLimit = 6000000000)]
Finally, here is the action itself. This giant block of code is not indicative of how I want the code to be written but I have merged it into one method as part of the debugging exercise.
public async Task<IActionResult> Audio()
{
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
throw new ArgumentException("The media file could not be processed.");
}
string mediaId = string.Empty;
string instructorId = string.Empty;
try
{
// process file first
KeyValueAccumulator formAccumulator = new KeyValueAccumulator();
var streamedFileContent = new byte[0];
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(Request.ContentType),
_defaultFormOptions.MultipartBoundaryLengthLimit
);
var reader = new MultipartReader(boundary, Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(
section.ContentDisposition, out var contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper
.HasFileContentDisposition(contentDisposition))
{
streamedFileContent =
await FileHelpers.ProcessStreamedFile(section, contentDisposition,
_permittedExtensions, _fileSizeLimit);
}
else if (MultipartRequestHelper
.HasFormDataContentDisposition(contentDisposition))
{
var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name).Value;
var encoding = FileHelpers.GetEncoding(section);
if (encoding == null)
{
return BadRequest($"The request could not be processed: Bad Encoding");
}
using (var streamReader = new StreamReader(
section.Body,
encoding,
detectEncodingFromByteOrderMarks: true,
bufferSize: 1024,
leaveOpen: true))
{
// The value length limit is enforced by
// MultipartBodyLengthLimit
var value = await streamReader.ReadToEndAsync();
if (string.Equals(value, "undefined",
StringComparison.OrdinalIgnoreCase))
{
value = string.Empty;
}
formAccumulator.Append(key, value);
if (formAccumulator.ValueCount >
_defaultFormOptions.ValueCountLimit)
{
return BadRequest($"The request could not be processed: Key Count limit exceeded.");
}
}
}
}
// Drain any remaining section body that hasn't been consumed and
// read the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
var form = formAccumulator;
var file = streamedFileContent;
var results = form.GetResults();
instructorId = results["instructorId"];
string title = results["title"];
string firstName = results["firstName"];
string lastName = results["lastName"];
string durationInMinutes = results["durationInMinutes"];
//mediaId = await AddInstructorAudioMedia(instructorId, firstName, lastName, title, Convert.ToInt32(duration), DateTime.UtcNow, DateTime.UtcNow, file);
string fileExtension = "m4a";
// Generate Container Name - InstructorSpecific
string containerName = $"{firstName[0].ToString().ToLower()}{lastName.ToLower()}-{instructorId}";
string contentType = "audio/mp4";
FileType fileType = FileType.audio;
string authorName = $"{firstName} {lastName}";
string authorShortName = $"{firstName[0]}{lastName}";
string description = $"{authorShortName} - {title}";
long duration = (Convert.ToInt32(durationInMinutes) * 60000);
// Generate new filename
string fileName = $"{firstName[0].ToString().ToLower()}{lastName.ToLower()}-{Guid.NewGuid()}";
DateTime recordingDate = DateTime.UtcNow;
DateTime uploadDate = DateTime.UtcNow;
long blobSize = long.MinValue;
try
{
// Update file properties in storage
Dictionary<string, string> fileProperties = new Dictionary<string, string>();
fileProperties.Add("ContentType", contentType);
// update file metadata in storage
Dictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("author", authorShortName);
metadata.Add("tite", title);
metadata.Add("description", description);
metadata.Add("duration", duration.ToString());
metadata.Add("recordingDate", recordingDate.ToString());
metadata.Add("uploadDate", uploadDate.ToString());
var fileNameWExt = $"{fileName}.{fileExtension}";
var blobContainer = await _cloudStorageService.CreateBlob(containerName, fileNameWExt, "audio");
try
{
MemoryStream fileContent = new MemoryStream(streamedFileContent);
fileContent.Position = 0;
using (fileContent)
{
await blobContainer.UploadFromStreamAsync(fileContent);
}
}
catch (StorageException e)
{
if (e.RequestInformation.HttpStatusCode == 403)
{
return BadRequest(e.Message);
}
else
{
return BadRequest(e.Message);
}
}
try
{
foreach (var key in metadata.Keys.ToList())
{
blobContainer.Metadata.Add(key, metadata[key]);
}
await blobContainer.SetMetadataAsync();
}
catch (StorageException e)
{
return BadRequest(e.Message);
}
blobSize = await StorageUtils.GetBlobSize(blobContainer);
}
catch (StorageException e)
{
return BadRequest(e.Message);
}
Media media = Media.Create(string.Empty, instructorId, authorName, fileName, fileType, fileExtension, recordingDate, uploadDate, ContentDetails.Create(title, description, duration, blobSize, 0, new List<string>()), StateDetails.Create(StatusType.STAGED, DateTime.MinValue, DateTime.UtcNow, DateTime.MaxValue), Manifest.Create(new Dictionary<string, string>()));
// upload to MongoDB
if (media != null)
{
var mapper = new Mapper(_mapperConfiguration);
var dao = mapper.Map<ContentDAO>(media);
try
{
await _db.Content.InsertOneAsync(dao);
}
catch (Exception)
{
mediaId = string.Empty;
}
mediaId = dao.Id.ToString();
}
else
{
// metadata wasn't stored, remove blob
await _cloudStorageService.DeleteBlob(containerName, fileName, "audio");
return BadRequest($"An issue occurred during media upload: rolling back storage change");
}
if (string.IsNullOrEmpty(mediaId))
{
return BadRequest($"Could not add instructor media");
}
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
var result = new { MediaId = mediaId, InstructorId = instructorId };
return Ok(result);
}
I reiterate, this all works great locally. I do not run it in IISExpress, I run it as a console app.
I submit large audio files via my SPA app and Postman and it works perfectly.
I am deploying this code to an Azure App Service on Linux (as a Basic B1).
Since the code works in my local development environment, I am at a loss of what my next steps are. I have refactored this code a few times but I suspect that it's environment related.
I cannot find anywhere that mentions that the level of App Service Plan is the culprit so before I go out spending more money I wanted to see if anyone here had encountered this challenge and could provide advice.
UPDATE: I attempted upgrading to a Production App Service Plan to see if there was an undocumented gate for incoming traffic. Upgrading didn't work either.
Thanks in advance.
-A
Currently, as of 11/2019, there is a limitation with the Azure App Service for Linux. It's CORS functionality is enabled by default and cannot be disabled AND it has a file size limitation that doesn't appear to get overridden by any of the published Kestrel configurations. The solution is to move the Web API app to a Azure App Service for Windows and it works as expected.
I am sure there is some way to get around it if you know the magic combination of configurations, server settings, and CLI commands but I need to move on with development.

Installing Umbraco programmatically

I'm trying to install Umbraco without using the visual interface, in order to increase my productivity.
Currently my code looks like this:
var installApiController = new InstallApiController();
var installSetup = installApiController.GetSetup();
var instructions = new Dictionary<string, JToken>();
var databaseModel = new DatabaseModel
{
DatabaseType = DatabaseType.SqlCe
};
var userModel = new UserModel
{
Email = "my#email.com",
Name = "My name",
Password = "somepassword",
SubscribeToNewsLetter = false
};
foreach (var step in installSetup.Steps)
{
if (step.StepType == typeof(DatabaseModel))
{
instructions.Add(step.Name, JToken.FromObject(databaseModel));
}
else if (step.StepType == typeof(UserModel))
{
instructions.Add(step.Name, JToken.FromObject(userModel));
}
}
var installInstructions = new InstallInstructions
{
InstallId = installSetup.InstallId,
Instructions = instructions
};
InstallProgressResultModel progressInfo = null;
do
{
string stepName = "";
if (progressInfo != null)
{
stepName = progressInfo.NextStep;
}
try
{
progressInfo = installApiController.PostPerformInstall(installInstructions);
}
catch (Exception e)
{
throw new Exception(stepName, e);
}
}
while (progressInfo.ProcessComplete == false);
The code fails at this line: https://github.com/umbraco/Umbraco-CMS/blob/dev-v7.8/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs#L47, and I believe it's because the ApplicationContext isnt updated for each of the installation steps (e.g. not updated after the database is created).
Is it possible to update the ApplicationContext manually after each step in the installation progress, or do I have to trigger all installation steps in separate HTTP requests?
The code works, if I run each step in separate HTTP requests.

asp.net mvc 5 sent email attachments are damaged

I am trying to send an email using the method described in this tutorial with a model structure form this tutorial and im partially successfull in doing so. The only issue I am having is the fact that files sent as attachments are damaged. I have tried to get it working in so many ways that I lost count. Obviously haven't been trying hard enough since I didn't find the answer, but decided to ask while I continue looking for an answer.
My controller action is as follows:
public async Task<ActionResult> Index( [Bind(Include = "column names..")] Contact contact, HttpPostedFileBase upload){
if (ModelState.IsValid && status)
{
var message = new MailMessage();
if (upload != null && upload.ContentLength > 0)
{
// 4MB -> 4000 * 1024
const int maxFileSize = 4096000;
if (upload.ContentLength < maxFileSize)
{
var document = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Document,
ContentType = upload.ContentType
};
var supportedTypes = new[] {"doc", "docx", "pdf", "jpg"};
var extension = System.IO.Path.GetExtension(document.FileName);
if (extension != null)
{
var fileExt = extension.Substring(1);
if (!supportedTypes.Contains(fileExt))
{
ModelState.AddModelError("document", "Wrong format");
return View();
}
//this is the line that sends damaged attachments,
//I believe I should be using document in some way (using reader bit below),
//but whatever I use the code complains or crashes.
message.Attachments.Add(new Attachment(upload.InputStream, Path.GetFileName(upload.FileName)));
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
document.Content = reader.ReadBytes(upload.ContentLength);
//message.Attachments.Add(new Attachment(document.Content, document.FileName));
}
contact.Files = new List<File> {document};
}
}else
{
ModelState.AddModelError("document", "File too big. Max 4MB.");
}
}
EDIT: A lot of times the code cannot find the file, how do I make sure I give it correct path each time?

Why is Xamarin.Auth throwing authentication error with OAuth1Authenticator and Twitter

I am currently using Xamarin.Auth on a iOS project to handle some user authentication via Facebook and Twitter in my application. The Facebook authentication using OAuth2Authenticator works great and my implementation was based mainly off the docs (http://components.xamarin.com/gettingstarted/xamarin.auth). Twitter however still uses OAuth1 it seems and thus I based my implementation mainly off the answer in this StackOverflow questions (https://stackoverflow.com/a/21982205). Everything works properly and I am able to retrieve user, tweets, etc. but after all the code executes I receive a "Authentication Error" popup on the screen saying "Object reference not set to an instance of an object." there is nothing printed to the console however as is the case with most normal errors I have seen thus far. I can dismiss the popup and everything continues to preform correctly. I believe I have narrowed the problem down to something within the OAuth1Authenticator request as I still receive the error when all of the other handling code has been commented out. Please reference the code below to see what might be the cause of this.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
signupBtn.TouchUpInside += delegate {
LoginToTwitter(true, this);
};
}
void LoginToTwitter(bool allowCancel, UIViewController _vc)
{
var auth = new OAuth1Authenticator (
consumerKey: "My Consumer Key",
consumerSecret: "My Consumer Secret",
requestTokenUrl: new Uri("https://api.twitter.com/oauth/request_token"),
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"),
accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"),
callbackUrl: new Uri("My callback url"),
getUsernameAsync: (IDictionary<string, string> accountProperties) => {
string screen_name = "";
if (accountProperties.TryGetValue("screen_name", out screen_name)) {
Console.WriteLine("SN: {0}", screen_name);
Account a = new Account(screen_name, accountProperties);
AuthenticatorCompletedEventArgs e = new AuthenticatorCompletedEventArgs(a);
TwitterCompleted(e, _vc);
}
return null;}
);
auth.AllowCancel = allowCancel;
UIViewController authView = auth.GetUI ();
_vc.PresentViewController (authView, true, null);
}
void TwitterCompleted (AuthenticatorCompletedEventArgs e, UIViewController _vc)
{
var theAccount = e.Account;
var theProperties = theAccount.Properties;
foreach (var item in theProperties) {
Console.WriteLine (item); //debugging
}
InvokeOnMainThread (delegate {
_vc.DismissViewController (true, null);
});
AccountStore.Create ().Save (e.Account, "Twitter");
if (!e.IsAuthenticated) {
Console.WriteLine("Not authorized");
return;
}
theScreenName = e.Account.Properties["screen_name"];
theCount = "2";
IDictionary<string, string> theDict = new Dictionary<string, string>();;
theDict.Add("screen_name", theScreenName);
theDict.Add("count", theCount);
var request = new OAuth1Request("GET", new Uri("https://api.twitter.com/1.1/statuses/user_timeline.json"), theDict, e.Account, false);
request.GetResponseAsync().ContinueWith (t => {
if (t.IsFaulted)
Console.WriteLine("Error: {0}", t.Exception.InnerException.Message);
else if (t.IsCanceled)
Console.WriteLine("Canceled");
else
{
var obj = JsonValue.Parse (t.Result.GetResponseText());
Console.WriteLine("object: {0}", obj); // debugging
}
}, uiScheduler);
return;
}
private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
instead of returning null in "getUsernameAsync" return Task

Resources