c#,asp.net,asp.net-mvc,asp.net-mvc-3,entity-frameworkRelated issues-Collection of common programming errors


  • Afnan Bashir
    c# proxy
    Is it possible to detect which proxy is active which is dead? using c# and a combo box containing list of proxies with port number is there any way we take every proxy one by one and determine as if it was dead or active?Microsoft.Win32.RegistryKey registry = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(“Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings”, true);registry.SetValue(“ProxyEnable”, 1);registry.SetValue(“ProxyServer”, comboBox1.Text);

  • Ian Nelson
    c# asp.net winforms using-statement
    I’m trying to use the System.Drawing.Color namespace. I’m not able to define it at the top of the class:However, I can reference it within the class. That is, I can use this line of code, and it works:txtBox.BackColor = System.Drawing.Color.LightPink;… but I’d rather just be able to do this:txtBox.BackColor = Color.LightPink;If it’s a matter of a missing reference/dll, why am I able to make reference to System.Drawing.Color in my code?

  • Misha Zaslavsky
    c# null
    I was on the IBM page looking for some filenet example code for .NET and I found this:namespace CESample {// Represents the connection with the Content Engine.public class CEConnection{private IDomain domain;private IObjectStoreSet ost;private ArrayList osNames;private String domainName;private bool isCredentialsEstablished;// Constructorpublic CEConnection(){domain = null;ost = null;osNames = new ArrayList();domainName = null;isCredentialsEstablished = false;}//… other methodsIts this alright

  • John Saunders
    c# .net dynamic .net-4.0 generic-type-argument
    I suspect the short answer to this question is “no” but I’m interested in the ability to detect the use of the dynamic keyword at runtime in C# 4.0, specifically as a generic type parameter for a method.To give some background, we have a RestClient class in a library shared among a number of our projects which takes a type parameter to specify a type that should be used when de-serializing the response, e.g.:public IRestResponse<TResource> Get<TResource>(Uri uri, IDictionary<strin

  • Mark Canlas
    c# sql linq linq-to-sql
    This is an in-depth continuation of my question from earlier this morning, which I’m still stumped about. I’m using a strongly typed DataContext for my application and although it emits a warning, it magically works. How does it do this?Here’s the code one would typically use to connect to a database using LINQ-to-SQL.class MyDatabase : DataContext {public Table<Widget> Widgets;public Table<Car> Cars;public MyDatabase (string connection) : base(connection) { } }Even though it emits

  • Ben Voigt

  • skaffman
    c# datetime
    For our support software in C#, I need to determine the time span between two DateTimes, but I only want opening hours counted (i.e. weekdays from 09:00 to 17:00).So, for instance, if the first DateTime is 15/02/2011 16:00 and the second is 16/02/2011 10:00, the method shall return 2 hours.Any help is greatly appreciated!

  • QmunkE
    c# web-services exception-handling webmethod
    I have a set of web services generated using the [WebMethod] attribute. Is it considered “good practice” to throw ArgumentException from such a method if its arguments aren’t properly specified (and no sensible defaults could be used)? If so, should this exception be caught and re-thrown in order to log it both on the server and the client?

  • Simon
    c# winforms repaint
    I’ve come across a problem that I’m hoping one of you fine thinkers can overcome…For some reason, once I have loaded up my Windows Form, if the user presses the ALT key, the form redraws causing a flash.This only happens the first time, so any subsequent presses of the ALT key do nothing.I don’t have any menu strips or events that handle the key press, so I can only assume it’s either a setting I haven’t set, or one that I have unknowingly set.FYI, the form does the following in the constructo

  • Brian Rasmussen
    c# constructor dependency-injection
    I’ve long considered it a bad practice to call out to a classes dependencies from within the constructor but wasn’t able to articulate why to a colleague yesterday. Can anyone provide a good reason for NOT doing this?

  • Yair Nevet
    asp.net vb.net file
    In my application i am creating a XML file for every 15secs at admin side. For creating the XML i have used the string builder to XML.File.WriteAllText(“D:\\FE_Display.xml”, StringBuilder.ToString())The same file i used to display in Grid on Front end for every 15 secs. This file minimum 10memebrs using at same time at Front end.The below code is used for front end.Dim ds As New DataSet() ds.ReadXml(“d://FE_Display.xml”) TryIf ds.Tables(0).Rows.Count > 0 ThenGrid1.DataSource = ds.Tables(0)G

  • Ian Nelson
    c# asp.net winforms using-statement
    I’m trying to use the System.Drawing.Color namespace. I’m not able to define it at the top of the class:However, I can reference it within the class. That is, I can use this line of code, and it works:txtBox.BackColor = System.Drawing.Color.LightPink;… but I’d rather just be able to do this:txtBox.BackColor = Color.LightPink;If it’s a matter of a missing reference/dll, why am I able to make reference to System.Drawing.Color in my code?

  • David
    javascript asp.net postback
    I’ve just added some JavaScript to the onclick of a Button in ASP.NET to disable the button (in order to prevent the user submitting the form twice).When I click this button, the page posts back fine but no control event handler runs – ASP.NET seems unable to determine which control posted the page back.I’m a bit stumped by this unexpected behaviour. Can anyone explain it and suggest an alternative way of doing this?

  • 123Developer
    c# asp.net
    I am into an ASP.Net project now (of course, it’s my first project ASP.Net 🙂 ). We are using Dependency Injection and the solution is designed to use MVC pattern. Here is the question now.I could see the events for different ASP.Net intrinsic controls which is used as part of custom controls is being registered in OnInit event method of the Custom control instead registering them in constructor of the custom control. Is this a good practice?? I wonder..Thanks in advance 123Developer

  • uhu
    .net asp.net iis
    How can I achieve in an ASP.NET application, that a set of URLs/ASPX pages (parts of the application) cannot be called directly from the user in the Browser? These urls/pages may only be referenced in the application itself.

  • barneytron
    asp.net visual-studio onload pageload
    When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool. So for years, I have always put code for doing things like set properties of controls in Page_Load. Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event). So I started to wonder, where is the best place really to set the properties of cont

  • Msonic
    c# asp.net mysql
    I’m building very simple search engine for a job site. It has 3 optional input fields, term, category and employer. Term and employer fields are text input and category is dropdown list. Search logic is very stupid, complicated and not scalable but this search is meant to be used just one time and all i need from it is that it works on a few cases and since i have more important things to do at the time i didn’t tried to make it any better. This is the method that returns a DataSet with results

  • AspDevel
    c# javascript asp.net updatepanel
    I have a autocomplete dropdown which works fine, it however does a postback everytime an item is addded to the list box. To rectify this I have wrapped the content in an update panel. The autocomplete functions as expected until you click add. Where the postback would usaully be, after the item has been added the autocomplete does not work.Below is the code:aspx:<asp:ScriptManager ID=”ScriptManager1″ runat=”server” /> <asp:UpdatePanel runat=”server” ID=”UpdatePanel” UpdateMode=”Conditio

  • SNA
    .net asp.net
    I am a .net web devoloper.I always face problems while deploying applications in the client server on IIS virtual directory settings.Locally everything works fine but in the client server i always faced unexpected errors.Mosty because of windows permissions etc.Only while facing the problems we google it and find the solution and sometimes the deployment process delays long because of unexpected error.Most of the time its traial and error method.Can anyone suggest a good book, articles,guideline

  • Chris Nicholson
    asp.net css bundling-and-minification asp.net-optimization
    For a while now I have adopted the practice of writing my CSS in an .aspx page and serving that page as CSS. Primarily this is because a project I was involved on had a development ‘CDN’ before images were finally hosted on the actual CDN, so when it came to background images I needed a way of changing the URL through the web.config. I also get a few other perks like variables. A small sample:#id {color: ‘<%= PrimaryColor %>’;background-image: url(‘<%= PrependCdnUrl(“myimage.jpg”) %>

  • Damien
    jquery asp.net-mvc ajax error-handling
    Does anyone have a elegant way of dealing with errors in ASP.Net MVC? I constantly run into issues when dealing with requests to controller actions where the Action can be used for both normal requests and AJAX requests. The problem I have is finding an elegant way of dealing with these issues.For example, how could I handle validation errors? Ideally I would like to submit the form to a server via AJAX and then return any errors the action threw and display them on the page, but for the same to

  • Vinko Vrsalovic
    asp.net-mvc encoding
    In my asp.net-mvc website I have a field that usually has a string (from database) but can from time to time contain nothing. Because IE doesn’t know how to handle the css “empty-cells” tag, empty table cells need to be filled with an &nbsp; I thought Html.Encode(” “);would fix this for me, but apparantly, it just returns ” “. I could implement this logic as followsHtml.Encode(theString).Equals(” “)?”&nbsp;”:Html.Encode(theString);Also a non-shorthand-if would be possible but frankly,

  • user636525
    asp.net-mvc bundling-and-minification
    I am using Asp.net MVC 4 bundler to bundle and minify my Css files.YSlow is showing this error below/* Minification failed. Returning unminified contents.(1442,26): run-time error CSS1019: Unexpected token, found ‘:'(1442,26): run-time error CSS1042: Expected function, found ‘:'(1442,26): run-time error CSS1062: Expected semicolon or closing curly-brace, found ‘:’*/This is my bundle code,bundles.Add(new StyleBundle(“~/Content/css”).Include(“~/Content/site.css”,”~/Content/fullcalendar.css”,”~/Con

  • learning
    asp.net-mvc mvc asp.net-mvc-3
    I am reading through a table in jquery and I am trying to pass the value to a method from a class. I am trying to write the following but can`t figure what is wrong. The error message is on the line if…: MvcUI\Views\Shared\employee.cshtml(170,81): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @MvcUI\Views\Shared\employee.cshtml(170,83): error CS1056: Unexpected character ‘$’MvcUI\Views\Shared\employee.cshtml(170,90): error CS1056: Unexpected character ‘$’Mvc

  • queen3
    asp.net-mvc reporting-services
    In my ASP.NET MVC application I sometimes get these errors when I try to open or generate LocalReport from Microsoft Reporting Services assembly:Microsoft.Reporting.WebForms.LocalProcessingException:An error occurred during local reportprocessing. —>Microsoft.Reporting.DefinitionInvalidException:The definition of the report’C:\Inetpub\wwwroot\orders\Reports\Reports\PendingRenewals.rdlc’ is invalid. —>Microsoft.ReportingServices.ReportProcessing.ReportProcessingException:An unexpected error o

  • DaveRandom
    asp.net-mvc timer
    I used System.Timers.timer in global.as in asp.net to set a timer for scheduling execute a function let’ say transferMoney(). But it seems that this timer might stop after several hours unexpected. And this cause that all the actions are pending. I want to know whether there are any better methods to set up a timer in asp.net, MVC 1.0? Thanks in advance!

  • Jaap
    javascript jquery asp.net-mvc razor
    I have a asp.net razor partial view which is used multiple times on one page. In that partial view I have javascript in the $(document).ready() which I want to do some jQuery stuff on the content of the partial view.<div class=”someclass”> </div> <script>$(document).ready(function() {$(‘.someclass’).dosomething();)); </script>So the problem is that $(‘.someclass’) returns to much elements when this partial view is use multiple times on one page. How can I achieve that $(‘

  • Maven
    c# .net asp.net-mvc
    I have following code in a model that I have made to work with all DB related activities so I don’t get to write the redundant piece of code every time I want to work with the Database, this model class looks like this:Shared.cs:private static string ConStr{get{Shared shrObj = new Shared();return shrObj.DecryptString(ConfigurationManager.ConnectionStrings[“constr”].ConnectionString);}}public static SqlConnection SqlCon = new SqlConnection(ConStr);public static SqlDataReader ORC(SqlCommand sqlCom

  • Akim
    asp.net-mvc repository unity ioc-container
    I am a lone developer and Pluralsight is my salvation in helping me understand things like Repository and IoC, which I am just learning. However I am finding the pattern awkward to use.So I am using Unity IoC, and following ModelContainer class;public static class ModelContainer {private static IUnityContainer instance;static ModelContainer(){instance = new UnityContainer();}public static IUnityContainer Instance{get{instance.RegisterType<ISCD_CallDiaryRepository, SCD_CallDiaryRepository>(

  • DavidB
    asp.net-mvc razor
    Im copied this ternary from another SO post:<td><input type=”button” value=”Delete” class=”DeleteButton” id=”@(“D” + param.QueueId)” @{ if(param.StatusId != 1) { @:disabled=”disabled” } } /></td>But it is causing compilation errors.End of file or an unexpected character was reached before the input tag could be parsed.

  • Ladislav Mrnka
    entity-framework caching asp.net-mvc-3 ef-code-first entity-framework-4.1
    We are using EF code first with the App Fabric cache on Windows Azure (although, I think the question is really more generic since we are using it as an ASP.net caching provider). Is there an easy way to enable caching of DBset objects? Our db is small and not updated very frequently, so ideally we could cache the entire database in memory, and use some ttl expiry to refresh object sets. Any advise from someone with experience caching using EF code first would be great.

  • learning
    asp.net-mvc mvc asp.net-mvc-3
    I am reading through a table in jquery and I am trying to pass the value to a method from a class. I am trying to write the following but can`t figure what is wrong. The error message is on the line if…: MvcUI\Views\Shared\employee.cshtml(170,81): error CS1646: Keyword, identifier, or string expected after verbatim specifier: @MvcUI\Views\Shared\employee.cshtml(170,83): error CS1056: Unexpected character ‘$’MvcUI\Views\Shared\employee.cshtml(170,90): error CS1056: Unexpected character ‘$’Mvc

  • Brian Mains
    c# asp.net-mvc-3 entity-framework-4 windows-services console-application
    I’m using the same model for multiple applications: MVC3 web app, Windows services, and a console application. When I start the MVC3 web app, it generates the database. I can restart it, and everything is fine. But when I start the console application I get an error:The model backing the ‘…Context’ context has changed since thedatabase was created. Consider using Code First Migrations to updatethe database (http://go.microsoft.com/fwlink/?LinkId=238269).Same occurs when I drop the database,

  • Buaziz
    asp.net-mvc-3
    i have a Photo Class with 2 inherited classes – PhotoBusiness and PhotoStore. how i can use one display template of ICollection Photo to display both types.as having a display template of ICollection Photo returns an error of unexpected type.

  • blueberryfields
    .net asp.net-mvc-3 visual-web-developer-2010
    My solution has multiple start-up projects in it. When publishing to production, the projects start up, but then begin to act in unexpected ways. I’m guessing I don’t understand the system well enough yet. What happens to a web solution with multiple start-up projects when it is published to the web-server?

  • Sanghoon
    asp.net-mvc-3 razor
    I’ve got an error when I tried to use if clause in razor like this:Unexpected “if” keyword after “@” character. @foreach (var item in Model) { @if (item.Country != “No Country”) {<li>@Html.ActionLink(item.CountryWithCount, “IndexByProv”, “EventInfo”, new { country = item.Country }, null)</li>Why I got this error?

  • SB2055
    asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 razor knockout.js
    In my view I have the following: <a data-bind=”click: saveAboutMe(@Html.Raw(Json.Encode(User.Identity.Name)))”>save</a>I’m trying to pass the @User.Identity.Name to the js function but I get “unexpected token”. What’s a clean way to achieve this?

  • usr
    .net asp.net-mvc-3 exception-handling
    I was just wondering if it’s a best practice to throw errors on validation and logic like the one below. I am catching these in my OnException method in my controller and sending it back to the client via Ajax as JSON. Is throwing exceptions like this ok?public void Update(EditTeacherModel model){var entity = _teachersRepository.FindBy(model.Id);if(entity == null)throw new NatGeoNotFoundException(“Teacher”);}

  • M05Pr1mty
    c# asp.net-mvc-3 wcf castle-windsor
    The reason I am asking this as a separate question to the multitude of others is that I am using Castle Windsor 3.0 as my DI framework and thus configuring my endpoints through the WCF Facility of CW. I am unable to find any resolution with this setup.:: Update ::Thanks for the comments. The project is a standard WCF Service Application, which feeds off a number of standard class libraries connecting to underlying funcitonality (SQl Server etc). The Web services that exist in the project are sta

  • Raj
    asp.net-mvc asp.net-mvc-3 mvc
    I am working on MVC 3, I am trying to delete a record from the table, but when I click on the delete button I am getting the following error at the “test.Savechanges();” from the below code.Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.This is my controller code:public ActionResult Delete(tblEmployee viwEmp) {test.Entry(viwEmp).State = System.Data.Entit

  • Ladislav Mrnka
    entity-framework caching asp.net-mvc-3 ef-code-first entity-framework-4.1
    We are using EF code first with the App Fabric cache on Windows Azure (although, I think the question is really more generic since we are using it as an ASP.net caching provider). Is there an easy way to enable caching of DBset objects? Our db is small and not updated very frequently, so ideally we could cache the entire database in memory, and use some ttl expiry to refresh object sets. Any advise from someone with experience caching using EF code first would be great.

  • PaulWaldman
    entity-framework triggers .net-4.0-beta-2 sql-server-2008-r2
    Using a SQL 2008 R2 November release database and a .net 4.0 Beta 2 Azure worker role application. The worker role collects data and inserts it into a single SQL table with one identity column. Because there will likely be multiple instances of this worker role running, I created an Insert Instead Of trigger on the SQL table. The trigger performs Upsert functionality using the SQL Merge function. Using T-SQL I was able to verify the insert instead of trigger functions correctly, new rows wer

  • svick
    entity-framework concurrency task-parallel-library
    I’m executing the code in their own contexts, but it’s causing data to be out of sync in the main threads context. So I need to refresh the entity after the other contexts finish their work before I can update it. Unfortunately, I’m getting a OptimisticConcurrencyException and can’t figure out which entity it is that is the issue and needs to be refreshed? Is there a way to find out which entity it is that is causing the OptimisticConcurrencyException? This message is not helpful at all.System

  • Gilad Naaman
    c# wpf entity-framework
    I’m writing a WPF application that uses EF5 as an ORM. The application is in use on a different machine than the development machine (installed using ClickOnce).I’ve created a migration in order to add a column to a table, and ran it on the development machine. How do I run the same migration on the client without loosing information?

  • DaveRandom
    jquery asp.net asp.net-mvc entity-framework objectcontext
    i’ve been creating a web application in mvc asp.net. I have three different project/solutions:One solution contains the model in EF (DAL) and all the methods to add, update, delete and query the objects in the model, the objectcontext is managed here in a per request basis. Other solution contains a content management system in wich authorized users insert, delete, update and access objects through the DAL mentioned before. And the last solution contains the web page that is accessed by all us

  • Cranialsurge
    entity-framework concurrency entity
    I have a windows service that runs every 10 seconds … each time it runs, it takes some test data, modifies it and persists it to the database using the EntityFramework. However, on every second run, when I try to persist the change I get the following Optimistic Concurrency Exception:-Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entriesI know for a fact that

  • kraeg
    entity-framework lazy-loading navigational-properties
    I’m using EF4.3, POCOs, Lazy Loading and the IValidatableObject interface.I have a loan entity with a 1-1 relationship with a contract entity. Contract contains a bunch of data that is best left unloaded unless required.My problem is… When I make changes to my loan entity, it’s Validate method is meant to load the related contract entity to ensure it’s data is valid according to the state (or status) of the loan… but the contract navigational property remains null? If I quickwatch the loan

  • Maxim V. Pavlov
    .net entity-framework concurrency dbcontext
    I have an EF code-first generated database. Data manipulation is done using DbContext. An IoC container in Asp.net application generates a DbContext instance, that BL objects rely on on a per thread basis. The is a background task class that is loaded along with a web application.Every one in a while (like every 10 minutes), a background thread adds one item to a list of Incidents by calling myDbContext.Add within a transaction scope. Meanwhile, it seems like if one of the Incidents is changed b

  • punkouter
    entity-framework repository-pattern crud
    I could return nothing .. I could return true/false to show if there are any problems.. I could return an int being the primary key of what was inserted or updated.. I could create a custom object to return more information.. perhaps hold a collection of all the validation errors or something that may have occurred..So it is not something I am stuck with but I just seem to randomly pick different way so would like to hear a best practice for these common functions.. I am using C#/Entities/Reposi

  • paqogomez
    c# .net entity-framework linq-to-entities
    I have the following code. I’m getting error: “The cast to value type ‘Int32’ failed because the materialized value is null. Either the result type’s generic parameter or the query must use a nullable type.” when CreditHistory table has no records.var creditsSum = (from u in context.Userjoin ch in context.CreditHistory on u.ID equals ch.UserID where u.ID == userIDselect ch.Amount).Sum();How can I modify the query to accept null values?

Web site is in building