.NET Already Open DataReader - asp.net

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}

Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

Related

How to Read barcode image in Xamarin forms

I am trying to read the text from a QRcode image on my mobile app. I am using Xamarin.Forms with ZXing NuGet package.
I have been able to get the file using Xamarin.Essentials FilePicker. But I don't know how to actually read the barcode. I have looked at some stackoverflow solutions and they all seem to be Xamarin.Android based (using BinaryBitmap objects). I need a solution that can work for iOS and UWP as well. Here is what I have so far:
string file = "";
var filePickerOptions = new PickOptions
{
PickerTitle = "Select Barcode Image",
FileTypes = FilePickerFileType.Images
};
var result = await FilePicker.PickAsync(filePickerOptions);
if (result != null)
{
file = result.FullPath;
var res = Decode(file, BarcodeFormat.QR_CODE);
Console.WriteLine(res.Text);
}
public Result Decode(string file, BarcodeFormat? format = null, KeyValuePair<DecodeHintType, object>[] aditionalHints = null)
{
var r = GetReader(format, aditionalHints);
/* I need some function here that will allow me to get the BinaryBitmap from the image file path or something along those lines.*/
var image = GetBinaryBitmap(file);
var result = r.decode(image);
return result;
}
MultiFormatReader GetReader(BarcodeFormat? format, KeyValuePair<DecodeHintType, object>[] aditionalHints)
{
var reader = new MultiFormatReader();
var hints = new Dictionary<DecodeHintType, object>();
if (format.HasValue)
{
hints.Add(DecodeHintType.POSSIBLE_FORMATS, new List<BarcodeFormat>() { format.Value });
}
if (aditionalHints != null)
{
foreach (var ah in aditionalHints)
{
hints.Add(ah.Key, ah.Value);
}
}
reader.Hints = hints;
return reader;
}
https://github.com/Redth/ZXing.Net.Mobile/issues/981. This thread solved it for me. Credit to #jason for this response.

Getting error when a method is made for post request

When made I post request is made its giving internal server. Is the implementation of Flurl is fine or I am doing something wrong.
try
{
Models.PaymentPost paymentPost = new Models.PaymentPost();
paymentPost.Parts = new Models.Parts();
paymentPost.Parts.Specification = new Models.Specification();
paymentPost.Parts.Specification.CharacteristicsValue = new List<Models.CharacteristicsValue>();
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "Amount", Value = amount });
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "AccountReference", Value = accountId });
foreach (var item in extraParameters)
{
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue {
CharacteristicName = item.Key, Value = item.Value });
}
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
var selfCareUrl = "http://svdt5kubmas01.safari/auth/processPaymentAPI/v1/processPayment";
var fUrl = new Flurl.Url(selfCareUrl);
fUrl.WithBasicAuth("***", "********");
fUrl.WithHeader("X-Source-System", "POS");
fUrl.WithHeader("X-Route-ID", "STKPush");
fUrl.WithHeader("Content-Type", "application/json");
fUrl.WithHeader("X-Correlation-ConversationID", "87646eaa-2605-405e-967c-56e8002b5");
fUrl.WithHeader("X-Route-Timestamp", "150935");
fUrl.WithHeader("X-Source-Operator", " ");
var response = await clientFactory.Get(fUrl).Request().PostJsonAsync(paymentInJson).ReceiveJson<IEnumerable<IF.Models.PaymentPost>>();
return response;
}
catch (FlurlHttpException ex)
{
dynamic d = ex.GetResponseJsonAsync();
//string s = ex.GetResponseStringAsync();
return d;
}
You don't need to do this:
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
PostJsonAsync just takes a regular object and serializes it to JSON for you. Here you're effectively double-serializing it and the server is probably confused by that format.
You're also doing a lot of other things that Flurl can do for you, such as creating those Url and client objects explicitly. Although that's not causing errors, this is how Flurl is typically used:
var response = await selfCareUrl
.WithBasicAuth(...)
.WithHeader(...)
...
.PostJsonAsync(paymentPost)
.ReceiveJson<List<IF.Models.PaymentPost>>();

ASP.MVC Image edit

public ActionResult Edit([Bind(Include = "id,category,title,image,active,ImageFile")] page_image page_image)
{
if (ModelState.IsValid)
{
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.category = new SelectList(db.page, "id", "title", page_image.category);
return View(page_image);
}
Here I'm able to edit the User but is not showing the previous Image so If I click submit with out loading a new Image it will delete the previous one. What I have to do is the Edit view, I want it to show the name of the image. Can you guide me to the right direction?
The problem is because you save the view model as is to the Database, you should have a DTO. Anyway, try to get the ImageFile from the DB again, in case it submitted null.
if(page_image.ImageFile != null)
{
// your uploading logic
}
else
{
var oldData = db.Set<page_image>().Where(x => x.id == page_image.id).FirstOrDefault();
page_image.ImageFile = oldData.ImageFile;
}
If page_image.Image is null then get previous image and assign
if (page_image.ImageFile != null)
{
string fileName = Path.GetFileNameWithoutExtension(page_image.ImageFile.FileName);
string extension = Path.GetExtension(page_image.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssff") + extension;
page_image.image = "/Uploads/page_images/" + fileName;
fileName = Path.Combine(Server.MapPath("/Uploads/page_images"), fileName);
page_image.ImageFile.SaveAs(fileName);
} else {
// get existing image from database
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
//assign to existing image
page_image.image = data.image ;
}
db.Entry(page_image).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
Update :
Error is throwing here because of same instance of dbcontext. You can create new instance to fetch or do as following.
var data = db.page_image.AsNoTracking().Where(b => b.id == page_image.id).FirstOrDefault();
or
using (var db2 = new YourDbContext())
{
var data = db2.page_image.Where(b => b.id == page_image.id).FirstOrDefault();
}

If statement in Controller not saving changes

I have an if statement in my Controller which decides whether a checkbox is checked or not.
It works fine in the if statement and changes the properties, but when i go to send it back to the view these changes aren't saved.
Controller
public ActionResult GetUserRights(string userLogin)
{
if (userLogin != null)
{
Manager manager = new Manager();
var userlogin = manager.GetUserData(userLogin);
var userrights = userlogin.RightsId.Select(s => new { id = s, text = s });
var rightdetails = manager.GetAllRightsRows();
var rightsDetails = from r in rightdetails
orderby r.Id
select new RightDetail
{
RightID = r.Id,
RightDescription = r.Description,
RightName = r.Name,
ParentID = r.ParentId,
TypeColor = r.TypeColor,
Value = r.Value,
Checked = false
};
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
return View("_RightsTreeListPartial", rightsDetails); <==== ALL CHECKED
PROPERTIES ARE false EVEN THOUGH SOME ARE BEING CHANGED IN THE IF STATEMENT.
}
return View("Index");
}
Let me know if you need any more info.
Thanks
With an IEnumerable, I am not sure of the reason why, but you cannot edit an item using an if statement so the code below is correct and does what it is supposed to, however as it is IEnumerable non of the changes are saved, also the process below is very heavy and long winded for what we need to do.
Original Code
foreach (var userright in userrights)
{
foreach (var rightdets in rightsDetails)
{
if(rightdets.RightID == userright.id)
{
rightdets.Checked = true;
break;
}
}
}
The new code takes a lot less time and will therefore improve the wait time. Firstly the IEnumerable is converted to a List, then, using a for-loop, the data is iterated through until a match is found, then within an if statement the item is changed (using original code and just converting from IEnumerable to List should work but I wouldn't recommend using it).
New Code
var rightdetail = rightsDetails.ToList();
foreach (var userright in userrights)
{
for (var i = 0; i < rightdetail.Count(); i++)
{
if (rightdetail[i].RightID == userright.id)
{
rightdetail[i].Checked = true;
break;
}
}
}

Retrieving CRM 4 entities with custom fields in custom workflow activity C#

I'm trying to retrieve all phone calls related to opportunity, which statecode isn't equal 1. Tried QueryByAttribute, QueryExpression and RetrieveMultipleRequest, but still has no solution.
Here some code i wrote.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
ICrmService crmService = context.CreateCrmService(true);
if (crmService != null)
{
QueryByAttribute query = new Microsoft.Crm.Sdk.Query.QueryByAttribute();
query.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
query.EntityName = EntityName.phonecall.ToString();
query.Attributes = new string[] { "regardingobjectid" };
query.Values = new string[] { context.PrimaryEntityId.ToString() };
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
return ActivityExecutionStatus.Closed;
}
And almost same for QueryExpression
QueryExpression phCallsQuery = new QueryExpression();
ColumnSet cols = new ColumnSet(new string[] { "activityid", "regardingobjectid" });
phCallsQuery.EntityName = EntityName.phonecall.ToString();
phCallsQuery.ColumnSet = cols;
phCallsQuery.Criteria = new FilterExpression();
phCallsQuery.Criteria.FilterOperator = LogicalOperator.And;
phCallsQuery.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, "1");
phCallsQuery.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId.ToString();
I always get something like Soap exception or "Server was unable to proceed the request" when debugging.
To get exception details try to use following code:
RetrieveMultipleResponse retrieved = null;
try
{
retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
catch(SoapException se)
{
throw new Exception(se.Detail.InnerXml);
}

Resources