|
Google has lots of resources on these issues. And the answers to your question really depend on what you project is going to do.
|
|
|
|
|
Just suggestion try to start with only one or two views with small text on it and few Controllers. I have gone through your situation, right now little better but still learning. Once you get used to it, you will become perfect - go ahead buddy start putting small things, MVC looks difficult when you think, but once you start putting things together slowly it will become possible.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
Hi,
I am getting the error when trying to load data from the WebApi call,
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":
"The operation cannot be completed because the DbContext has been disposed.","ExceptionType":"System.InvalidOperationException","StackTrace":"
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator()\r\n at
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.IEnumerable.GetEnumerator()\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList
(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"}}
My code looks like:
public List<UserList> Get()
{
dynamic model = null;
using (AppDevSecEntities ctx = new AppDevSecEntities())
{
var temp = ctx.UserLists.OrderByDescending(x => x.LastName);
if (temp != null)
model = temp.ToList<UserList>();
}
return model;
}
Any help would be very helpful thanks in advance.
Thanks,
Abdul Aleem
"There is already enough hatred in the world lets spread love, compassion and affection."
|
|
|
|
|
It looks like your entity has a navigation property, which isn't being eagerly loaded. When the framework tries to serialize the object to JSON, the main entity tries to load the related entity using lazy-loading. This fails because the DbContext has been disposed.
Entity Framework Loading Related Entities[^]
There are several options to solve this:
1) Turn off lazy loading:
The navigation properties in the returned JSON will all be null .
public List<UserList> Get()
{
using (AppDevSecEntities ctx = new AppDevSecEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
return ctx.UserLists.AsNoTracking().OrderByDescending(x => x.LastName).ToList();
}
}
2) Eagerly load the navigation properties:
You'll need to load all of the navigation properties you need to return. You'll still want to turn off lazy-loading.
public List<UserList> Get()
{
using (AppDevSecEntities ctx = new AppDevSecEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
return ctx.UserLists.AsNoTracking().Include(x => x.YourNavigationProperty).OrderByDescending(x => x.LastName).ToList();
}
}
3) Return a data transfer object (DTO)
Create a specific class containing just the data you need to return. You can either map the entities by hand, or use something like AutoMapper[^] to do the mapping for you.
public List<UserListDto> Get()
{
using (AppDevSecEntities ctx = new AppDevSecEntities())
{
ctx.Configuration.LazyLoadingEnabled = false;
return ctx.UserLists.AsNoTracking().OrderByDescending(x => x.LastName).ProjectTo<UserListDto>().ToList();
}
}
4) Store the context at the controller level:
A new instance of the controller class is created to serve each request, so it's safe to store the context at the controller level. You'll need to override Dispose to clean it up.
public class YourController : ApiController
{
public YourController()
{
Context = new AppDevSecEntities();
}
private AppDevSecEntities Context { get; }
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing) Context.Dispose();
}
public List<UserList> Get()
{
return Context.UserLists.AsNoTracking().OrderByDescending(x => x.LastName).ToList();
}
}
NB: Since you're not updating the entities, it's a good idea to use the AsNoTracking method[^] to load them without tracking.
Entity Framework No-Tracking Queries[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Your WebAPI is attempting to serialize the object returned by your method, but the navigation properties point to the database connection built by the disposed connection.
There are many, many ways to skin this. The easiest (to me) is to locate the relationships in the Model that you do not want passed along with the basic call and decorate them with [JsonIgnore]. After doing that you can explicitly include them with the LINQ .Include(). You MUST have a reference to System.Data.Entity to use the strongly-typed extension of this method.
For example:
public class FooBar
{
...
[JsonIgnore]
public virtual ICollection<Foo> Foos { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
Now your Get:
using System.Data.Entity;
...
public IEnumerable<FooBar> Get()
{
using(var context = new MyDbContext()){
{
return context.FooBars.Include(x => x.Bars).ToArray();
}
}
This will have the API respond to requests with all FooBars, with all associated Bars and no Foos. It's important to note that this will also need to be done with any other related models, so if Bar has relationship properties, you'll need to configure them for serialization.
By the way, using dynamic in a context where a strong type or generic will suffice is bad juju; it invites trouble.
"There are three kinds of lies: lies, damned lies and statistics."
- Benjamin Disraeli
|
|
|
|
|
Hello again experts,
We have a RadioButtonList inside a Repeater control with two options, Yes or No.
We would like to force our users to choose a Yes or No before proceeding.
In other words, if a user clicks to submit or in our case, click the Next button to go to the next without selecting either Yes or No, an error needs to be raised letting the user know that s/he must select a Yes or No to continue.
The following code uses RequiredValidator control to handle this but it does not do anything.
Any ideas how to resolve this?
Purchased:<asp:radiobuttonlist ID="rblType" runat="server" ValidationGroup ="stype" RepeatDirection="Horizontal" TextAlign="Right" style="display:inline;">
<asp:ListItem Text="Yes" />
<asp:ListItem Text="No" />
</asp:RadioButtonList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
ControlToValidate="rblType"
ErrorMessage="required"
ValidationGroup ="stype"
runat="server"/>
Thanks a lot in advance.
|
|
|
|
|
Have you added the validation group to the submit button?
<asp:Button ID="btnSubmit" Text="Submit" runat="server" ValidationGroup="stype" />
If you don't need validation groups then don't add them at all.
|
|
|
|
|
EXCELLENT CATCH!
This proves once again that two heads are better than one.
I simply neglected that.
Thanks soo much.
|
|
|
|
|
just read a article on web api core versioning from this url http://www.c-sharpcorner.com/article/asp-net-core-api-versioning-in-simple-words-update-1-2-0/
i have few question about
[ApiVersion("2.0")] and MapToApiVersion("2.0")
1) why we need to use two attribute for a controller and action called
[ApiVersion("2.0")] and MapToApiVersion("2.0").
if i use
[ApiVersion("2.0")] for controller then it should work for whole controller then why i need to decorate action with
MapToApiVersion("2.0")
2) why
[ApiVersion("1.0")] and [Route("api/v{version:apiVersion}/[controller]")]
needed to decorate controller for versioning ?
3) this attribute
MapToApiVersion("2.0") is used for action only and this [ApiVersion("1.0")] used for controller only ?
4)
[ApiVersion("2.0")] or MapToApiVersion("2.0") for versioning then how web api action url would look like ?
please guide me.
|
|
|
|
|
Greetings experts,
I have a Repeater control with radiobuttonlist:
<asp:Repeater ID="repeaterItems" runat="server"
Purchased:<asp:radiobuttonlist ID="rblPurchaseType" runat="server" RepeatDirection="Horizontal" TextAlign="Right" style="display:inline;">
<asp:ListItem Text="New" />
<asp:ListItem Text="Used" />
</asp:RadioButtonList>
</asp:Repeater>
Then I have some textbox controls inside a div. This div is outside the Repeater control:
<div id="purchaseNewUsed" runat="server">
<table border="0" width="100%">
<tr>
<td>
<tr>
<td>NAME:</td><td><div class="input text"> <asp:TextBox ID="txtPrevOnwerName" style="width:450px;" runat="server"></asp:TextBox></div></td>
</tr>
<tr>
<td>ADDRESS:</td><td><div class="input text"> <asp:TextBox ID="TextBox6" style="width:450px;" runat="server"></asp:TextBox></div></td>
</tr>
<tr>
<td> CITY:</td><td><div class="input text"> <asp:TextBox ID="TextBox7" style="width:150px;" runat="server"></asp:TextBox></div></td><td> STATE:</td><td><div class="input select">
<asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="True">
<asp:ListItem Value="" Selected="False"></asp:ListItem>
</asp:DropDownList>
</div></td><td> ZIP:</td><td><div class="input text"> <asp:TextBox ID="TextBox9" style="width:50px;" runat="server"></asp:TextBox></div></td>
</tr>
</table></div>
I understand about using wildcards when dealing with controls inside a Repeater.
My issue is the DIV is outside the Repeater control while the RadioButtonList is inside the Repeater control.
The following script is not enabling or disabling the DIV when Used option is selected.
Any ideas how to get this to work?
script type="text/javascript">
$(document).ready(function() {
$('#rblPurchaseType input').change(function () {
if ($(this).val() == "New") {
$("#purchaseNewUsed").prop("disabled", true);
}
else {
$("#purchaseNewUsed").prop("disabled", false);
}
});
});
</script>
Thanks in advance
|
|
|
|
|
First thing you need to appreciate is that jQuery runs on the client, it does not run from your aspx file, the aspx file is simply a guide to what html the client will eventually get. This code
$('#rblPurchaseType input').change(function () {
looks at any "input" element inside something with an id of rblPurchaseType. View the page source (what jQuery is running from), and do you see any elements with an id of rblPurchaseType?
The id you specify in your aspx page is *not* the id used in the html. You can either use fairly complex code to get the proper ids, or use a simpler way of identifying the elements you want.
<asp:Repeater ID="repeaterItems" runat="server">
<ItemTemplate>
Purchased:<asp:radiobuttonlist ID="rblPurchaseType" runat="server" RepeatDirection="Horizontal" TextAlign="Right" data-id="rblPurchaseType" style="display:inline;">
<asp:ListItem Text="New" />
<asp:ListItem Text="Used" />
</asp:RadioButtonList>
</ItemTemplate>
</asp:Repeater>
<script>
$(document).ready(function () {
$("[data-id='rblPurchaseType'] input").change(function () {
});
});
</script>
This code attaches a "data-id" attribute to the outer table that will wrap your components and that attribute is used rather than the element's id. You are going to have a similar problem with your purchaseNewUsed div.
|
|
|
|
|
Assuming you want the controls enabled if any item from the repeater has "used" selected, something like this should work:
$(document).on("click", "input:radio[name$='rblPurchaseType']", function(){
var selectedItems = $("input:radio[name$='rblPurchaseType'][value='Used']:checked");
$("#purchaseNewUsed").prop("disabled", selectedItems.length === 0);
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
F-ES Sitecore,
Well explained. I appreciate it very much.
I did try your solution though but it didn't work. Maybe, I did something wrong.
Richard, as usual, your code worked like a charm.
Thank you very much.
|
|
|
|
|
Until now I used dreamweaver and asp and now I'm starting in Asp.Net with visual studio 2017. The design view is very bad, it does not look like anything to the actual view of the page in the browser. In Dreamweaver it usually seems quite, although sometimes not.
How can I work in Visual Studio if the view does not look like? How can you improve visualization?
|
|
|
|
|
I have a table in sql database and I am accessing that table through a model in MVC now if I add few more column and their data the table structure is getting disturbed on a browser. Does anyone have a solution for this?
|
|
|
|
|
I got the solution for this. I just added
@Html.DisplayNameFor(model => model.abc.FirstOrDefault().Name)
this increased the size of the column.
|
|
|
|
|
I have this problem where I change code in a Asp.Net 4.5.1 Webforms program, the users downstairs don't see the code changes, but all my devices upstairs work fine.
So I experimented with Response.Cache, put the code in the Page Load of the Master Page, and it worked fine.
But some programs like my shopping cart went haywire after the weekend. All of a sudden the Shopping Cart page was coming up empty.
Some of the symptoms where I walking the code, using SQL Linq, and the Linq says there are no items, yet I'm looking at the items in a DB Manager.
So I took the Response.Cache out and I have stability now.
I searched, but all I see are code examples, like the proper location is just assumed.
I suspect my wrong placement is sending out headers at the wrong time.
By the way, I have no knowledge on this subject.
Response.Cache.SetExpires(DateTime.Now.AddMinutes(1))
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate)
Response.Cache.SetValidUntilExpires(True)
Response.Cache.VaryByParams.IgnoreParams = true;
If it ain't broke don't fix it
|
|
|
|
|
Based on the description, I suspect you're caching the page output for all users. So if a user with nothing in their cart is the first to visit your page when the cache is empty, the server caches the output for an empty cart, and returns that for all users. Conversely, if the first visit is from a user with something in their cart, that user's cart will be returned for all users who visit within the next minute.
If your site displays any profile information, that's a potential data-protection issue. One customer's name, address, and contact details could end up being displayed to any other user who visits before the cached output expires.
You'll either need to turn off server caching for pages which vary by user, or use "doughnut caching" to ensure that the user-specific parts of the page don't get cached:
ScottGu's Blog - Tip/Trick: Implement "Donut Caching" with the ASP.NET 2.0 Output Cache Substitution Feature[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hmm,
Sorry for the late reply, I was refactoring that program.
I'll turn server caching off now and then read the article.
I just checked the website on the server, I'm only caching .jpg, .png and .css files.
Maybe It's located someplace else, I'll keep looking.
<caching>
<profiles>
<add extension=".png" policy="CacheUntilChange" kernelCachePolicy="DontCache" />
<add extension=".jpg" policy="CacheUntilChange" kernelCachePolicy="DontCache" />
<add extension=".css" policy="CacheUntilChange" kernelCachePolicy="CacheUntilChange" />
</profiles>
</caching>
Thanks Richard
If it ain't broke don't fix it
modified 18-Jul-17 13:46pm.
|
|
|
|
|
I m trying to make use of the code provided in:
Walkthrough: Creating a Synchronous HTTP Handler[^]
I am fine with the concepts of the code, but I cannot understand how to implement such a project in Visual Studio Community 2015. I want to understand how (if it is possible) to debug the code in Visual Studio and then how to deploy it. The article mentions IIS 6 and IIS 7 whereas on my Windows 10 environment I think I get an Express version of IIE (that came with VS) and the Windows 10 version of IIS, which says in its IIS about box, that it is version 10.0.15063.0.
I have read a lot of material on the topic and often people talk about using VS to Open a Web site from the file menu, but I am not really quite sure what that does or how it helps in this situation. The following article provides a solution close to what I want to achieve, though in my final solution the image will be pulled from a VARBINARY SQL Server database column.
Generic Image Handler Using IHttpHandler[^]
If you down load the source code for this project you get exactly what I would expect. A client web application that writes references to its web page at run time AND a separate iHTTPHandler project that serves up the image requested in the calling parameter.
So I am expecting that there is a need to install the iHTTPHandler either in IIS Express or IIS, and that once installed you should be able to enter a URL that will cause the browser to refresh with the requested image? Visual studio provides no deployment / publishing options for the iHTTPHandler project (that I can see). I presume I just need to copy the BIN DLL into the required folder over seen by IIS? Do I need additional IIS settings for the handler to be recognised?
Finally, there is the part which allows the client application to recognise the fact the handler exists, which I believe is a line in web.config.
<add type="ImageHandlerLib.ImageHandler, ImageHandlerLib" path="ImageHandler.aspx" verb="*" />
There is not much explanation as to the "why" this is needed (i.e. its purpose).
An ideal answer would "in the context of visual studio" provide a step by step explanation of how to get this working in the IDE as a simple handler that returns "hello world" in text. It should describe any limitations in terms of debugging. I am not sure how, for example, I can set a break point and see the return string assigned in the handler. Then any notes regarding deployment for production.
Many thanks.
|
|
|
|
|
Hi,
What is current default concurrent requests settings in IIS 8.5.
How to increase the concurrent requests settings in IIS 8.5.
Thanks in advance
a
|
|
|
|
|
|
Hello,
The strangest thing is happening and I can't track down the source of the issue. I have a form where users can edit their profile. On the form there is a password field. Here is the code:
<asp:textbox id="txtPassword" textmode="Password" runat="server" size="30">
In the SQL database I store the password as a binary, so the UPDATE statement looks as follows:
UPDATE Account SET Password=CONVERT(BINARY,'" & Replace(txtPassword.Text, "'", "''") & "') WHERE AccountID=15
When I retrieve the data, the SQL code looks like this:
SELECT CONVERT(VARCHAR,Password) FROM Account WHERE AccountID=15
Finally, when I pass the password to the text field, the code looks like:
txtPassword.Attributes.Add("value", dsResults.Tables(0).Rows(iRowLoop).Item(5))
I have used this code hundreds of times without any issues, however, for some reason the password in the form is being converted to the password plus a bunch of question marks to fill the remaining space. My password field is size 30, so if your password is "ketchup" then this gets placed in the password field:
ketchup???????????????????????
I looked at the value in the database and there is nothing padded on the end of the value. It seems that something really weird is happening on this line:
txtPassword.Attributes.Add("value", dsResults.Tables(0).Rows(iRowLoop).Item(5))
I am at a loss and am sure I am just overlooking something very simple. I even looked at another site of mine where I have this same pattern and everything looks identical...no clue where I am going wrong.
Thanks in advance for your help!
Frank
|
|
|
|
|
Converting a 30 byte binary value to characters will have the result you see. However, you do realise that any schoolboy hacker could get all your passwords with ease. This is absolutely not the way to store passwords, you should use a proper salted hash algorithm.
|
|
|
|
|
Is there a solution in your response? If you only point out issues and not solutions, you are of no help to the situation.
|
|
|
|
|