Firstly I would like to apologize to you all because I know that this question has been asked a whole bunch of times. But I dont know much about MVC or .NET or Lambda expressions per se. I am working on a small project and I am stuck at the Lambda expression error as below
EDIT
Below is the controller Code
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC4Trial.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace MVC4Trial.Controllers
{
public partial class CallTrackController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Remote_Data()
{
return View("AjaxBinding");
}
public ActionResult vwCallDetails([DataSourceRequest] DataSourceRequest request)
{
return Json(GetCallDetailsFn().ToDataSourceResult(request));
}
private static IEnumerable<CallDetails> GetCallDetailsFn()
{
var callData = new CallTrackClassDataContext();
return callData.CallDetails.Select(calldetail => new CallDetails
{
CCCID = calldetail.CCCID,
Mp3_Url = calldetail.Mp3_Url,
Index = calldetail.Index,
Target_Number = calldetail.Target_Number,
Duration = calldetail.Duration,
LocalTime = calldetail.LocalTime,
Site_Name___Address = calldetail.Site_Name___Address,
Ad_Source_Name = calldetail.Ad_Source_Name,
Tracking_Number = calldetail.Tracking_Number,
Caller_Number = calldetail.Caller_Number,
Available_Feature = calldetail.Available_Feature
});
}
}
}
I would like to learn how to fix this error. What am I missing here? Do I need to make any sort of changes on my Model/View/Any other file? Thanks for reading and helping.
There's something wrong with Duration. It's underlined in red, indicating that it doesn't exist on the class, or some other issue is causing it to not be recognized. Since there's an error here, the lambda expression doesn't process properly and it's only then that Visual Studio recognizes there error. Essentially, the reported error is masking the true problem. Fix Duration or remove it, and the lambda expression will be fine.
For what it's worth though, what you're doing doesn't make much sense. callData.CallDetails already returns an instance of CallDetails (or at least it should, or you should change the name), so using Select to return an instance of CallDetails populated from an instance of CallDetails is superfluous.
UPDATE
Sorry for not being more clear. My last comment really depends on what is exactly going on in code I can't see. So there's two possible scenarios:
1) callData.CallDetails is an instance of CallDetails. If this is the case, using Select is a waste of time and code because all you're doing is just converting one instance of CallDetails to another. Just doing return callData.CallDetails; would have the same effect.
2) callData.CallDetails is not an instance of CallDetails. If this is the case, then you should simply rename the CallDetails member of callData to avoid the sort of confusion that prompted my comment in the first place.
FWIW: If you really need to map some other type to an instance of CallDetails like this, you should look into AutoMapper. Writing this code is not only repetitive and time-consuming, but you also make yourself more prone to errors. For example, what if you later change the definition of CallDetails? You now got to track down every explicit mapping like this and change that as well, whereas with AutoMapper, you likely can just change the definition and be done.
Related
I am using Roslyn to create an analyzer that warns users if a particular class exposes its fields in an unsynchronized manner, to help prevent race conditions.
The Problem:
I currently have working code that checks to make sure a field is private. I’m having trouble with the last piece of the puzzle: figuring out a way to make sure that all fields are only accessed inside a lock block, so they’re (ostensibly) synchronized.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.FindSymbols;
namespace RaceConditions
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnsynchronizedMemberAccess : DiagnosticAnalyzer
{
public const string DiagnosticId = "UnsynchronizedMemberAccess";
internal static readonly LocalizableString Title = "UnsynchronizedMemberAccess Title";
private static readonly LocalizableString MessageFormat = "Unsychronized fields are not thread-safe";
private static readonly LocalizableString Description = "Accessing fields without a get/set methods synchronized with each other and the constructor may lead to race conditions";
internal const string Category = "Race Conditions";
private static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
//meant to stop other classes and itself from accessing members in an unsychronized fashion.
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.RegisterSemanticModelAction((context) =>
{
var model = context.SemanticModel;
var root = model.SyntaxTree.GetRoot();
var nodes = model.SyntaxTree.GetRoot().DescendantNodes();
var fields = nodes.OfType<VariableDeclaratorSyntax>()
.Where(v => v.Ancestors().OfType<FieldDeclarationSyntax>().Any());
//since (it appears) that you can't read/write to a an initialized field,
//I think it means you can only read/write inside a block
foreach (BlockSyntax b in nodes.OfType<BlockSyntax>())
{
//where I plan to put code to check references to the fields
}
});
}
}
}
More specifically, I’d like to be able to ensure everything highlighted by the reference highlighter (at least that’s what Microsoft seems to call it) is inside a lock block, while overloaded parameters do not have to.
using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using System.Data.SqlClient;
namespace Sandbox
{
partial class Program
{
private int xe = 0, y = 0;
public Program(int xe)
{
this.xe = xe;
}
void bleh()
{
if (xe == 0)
{
xe = xe + 1;
}
}
static void Main(string[] args)
{
Program p0 = new Program(5),
p1 = new Program(p0),
p2 = new Program(p0.xe);
Console.WriteLine(p1.xe);
Console.Read();
}
}
partial class Program
{
public Program(Program p) : this(p.xe) { }
}
}
The Research:
Here, Josh Varty [1] suggests I use SymbolFinder.FindReferencesAsync, which requires a Solution object. Jason Malinowski [2] says that I shouldn’t use do this in an analyzer, since making a MSBuildWorkspace to get a Solution object is too slow, while this person [3] offers an incomplete/missing workaround to the slowness issue (the link to ReferenceResolver seems to be broken).
I have also looked into DataFlowAnalysis (SemanticModel.AnalyzeDataFlow()), but I can’t find any particular methods there that obviously let me guarantee that I’m referencing the field xe, and not the local variable xe.
The Question:
I do feel like there is something monumentally obvious I’m missing. Is there some elegant way to implement this that I’ve overlooked? It’d be preferable if the answer uses the semantic model, since I expect I have to use it in other analyzers to figure out where data/references come from, but I realize there are limitations, so any answers without the semantic model are also fine.
Notes:
Apparently, this issue was also encountered at Github [4], but apparently it’s still being tracked there, and they don’t know if the analyzer should analyze on the project level or not. It still hasn’t been resolved. For the purposes of this analyzer, I will assume that the entire class contained in a single .cs file. Small steps first, eh?
I also searched through John Koerner's website [5] and Josh Varty's website [6], and couldn’t find anything relevant to both analyzers and DataFlowAnalysis.
The trick is to invert how you're asking the question. Go from:
How do I find all the references to this symbol that I want to ensure is synchronized?
but instead
How, upon looking at the use of a symbol, determine if this should be inside of a lock statement?
Because this offers a course of action: your analyzer should instead look at each identifier in a method body that's not in a lock statement, call SemanticModel.GetSymbolInfo(), get the symbol that's being referenced, and then check if that field is one that's "synchronized" via your logic (private, etc.). At that point, then since you're looking at the use, you can flag that particular use.
This inversion is how we expect analyzers to be written, and it's not an accident. The reason is largely performance. Imagine your analyzer is running inside Visual Studio, and you delete a line of code. If analyzers were written in the model of "look at a symbol, now ask for all uses", it means any and all analyzers that did that potentially have to rerun from scratch. That's not great for your CPU or battery life. When the question is inverted like this, it means we only have to reanalyze that specific file, since you're not expanding to "give me everything".
I am trying to write C# code that does basically the following:
The code connects to MySql table and reads data from one MySql table (with r rows and c columns) - no issues here, everything when fine;
The code then defines and loads one DataTable with the help MySqlDataReader - again, no issues at this stage. Code is fine;
Each column of this datatable is in fact one strategy parameter of the strategy (i.e. each row of this datatable thus becomes one parameter set of the strategy.
Having said that:
the code then loops across all of the rows of this datatable;
the code gets the column values of each row one by one, and changes the XML elements one by one to replace old strategy values with the new ones - THIS IS WHERE I GET THE ERROR!!! I CANT MODIFY THE XML FILE FROM WITHIN WEALTHLAB C# EDITOR!!
that way, the strategy becomes configured with a new set of parameters each time;
the code then calls runDonor and runs the strategy with given (new) set of parameters - no problem at calling runDonor as well!;
and finally, certain statistics are recorded and inserted into one MySql table - there is no problem here as well;
**
Considering that a large chunk of this code is not related to wealthlab namespace, I coded most of the parts in Visual Studio first, compiled there using Visual Studio compiler, and seen that the code works just fine there! (i.e.the Xelement edits went just fine. I could see that the XML file is being modified after each loop when this code is run at Visual Studio!)
Then, I copied/pasted this code onto wealthscript editor, but unfortunately, the code did not compile!!.
**
The problem is at the region where I begin modifying the XML document, using ElementAt method.
More specifically, the ElementAt statement works fine at Visual Studio Editor, whereas it doesnt at Wealthlab editor.
To repeat, DESPITE THE FACT THAT I GIVE REFERENCE TO SAME DLLS AND USE THE SAME USING... STATEMENTS ON TOP OF THE CODE, Visual Studio returns no errors and runs thoroughly whereas Wealthlab returns this error:
'System.Collections.Generic.IEnumerable' <System.Xml.Linq> does not contain a definition for 'ElementAt'
and no extension method 'ElementAt' accepting a first argument of type
'System.Collections.Generic.IEnumerable' <System.Xml.Linq> could be found (are you
missing a using directive or an assembly reference?)"
I have been googling for ages, and could not come up with any decent solution yet.
And since I dont have a programming background, I really cant figure out why the same code, that uses the same references, and the same using directives, works at Visual Studio but yield errors at Wealthlab.
At this link, one solution alternative is vowed, but frankly, it is not english to me:
System.Xml.Linq.XElement>' does not contain a definition for 'First' and no extension method 'First' accepting a first argument of
**
So, my question would be two fold:
1- How can I overcome this interesting error that is related to proper refererencing to System.Xml.Linq? Obviously, this is where the problem lies.
2- Or, lets throw this out and start from the scratch: How do you guys modify your xmls? It would be splendid If I was provided a link of example codes that reads from xml files, or modifies them, saves them.
(Please, help...)
For you guys to repeat the same error I also attach here the whole of the code; copy this to your editors and see if the code runs ok:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using WealthLab;
using WealthLab.Indicators;
using Community.Components;
using System.Collections;
using System.Xml;
using System.Xml.XPath;
using System.Linq;
using System.IO;
using System.Data;
using System.Xml.Linq; // THIS IS WHERE THE PROBLEM IS THIS REFERENCE COULD NOT BE SET PROPERLY!! WHY?!!
using MySql.Data.MySqlClient;
namespace WealthLab.Strategies
{
public class MyStrategy : WealthScript
{
// public DateTime now;
public static XElement SourceXml;
public static XElement DonorStrategyXml;
public static string SourceXmlName;
public static string Ticker;
public static int nNames;
public string DonorStrategyXmlFolder;
public string DonorStrategyXmlName;
public string DonorStrategyXmlNameWithNoXml;
public string DonorStrategyXmlPathName;
protected override void Execute()
{
//....
//....
//....
DonorStrategyXmlFolder = #"C:\Users\Aykut\AppData\Roaming\Fidelity Investments\WealthLabDev\1.0.0.0\Data\Strategies\Customized\";
DonorStrategyXmlName = "sss.xml";
DonorStrategyXmlNameWithNoXml = "sss";
string DonorStrategyXmlPathName = DonorStrategyXmlFolder + DonorStrategyXmlName;
DonorStrategyXml = XElement.Load(DonorStrategyXmlPathName);
foreach (DataRow dbBandParameterRow in dbBandParameters.Rows) {
foreach (DataRow dbNNParameterRow in dbNNParameters.Rows) {
string ResultID = dbBandParameterRow["ResultID"].ToString();
int nE = 0;
//....
//....
//.THIS IS WHERE THE PROBLEM LIES AT!!...
DonorStrategyXml.Elements("ParameterValues").Descendants("double").ElementAt(nE).Value = dbBandParameterRow["RatioForUpper"].ToString();
nE++;
DonorStrategyXml.Elements("ParameterValues").Descendants("double").ElementAt(nE).Value = dbBandParameterRow["ADXPeriodForUpper"].ToString();
// output certain statistics of the strategy onto mysql // later!!!
//....
//....
PrintDebug("NetProfit:" + sp.Results.NetProfit.ToString());
}
}
}
} // class
} // nspace
The wealthlab support team returned with the following answer; and it worked.
Thanks.
...
the code won't compile in the current version 6.6 of Wealth-Lab's Editor.
To fix that, add references to System.Core.dll and System.Xml.Linq.dll from c:\windows\microsoft.net\framework64\v4.0.30319 (64-bit WLD, or c:\windows\microsoft.net\framework\v4.0.30319 for 32-bit WLD).
...
i came across few blogs and forums and found this way of interacting with MODEL class from controller using LINQ to SQL
is it a proper way to access ?
using System.Linq;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var dataContext = new MovieDataContext();
var movies = from m in dataContext.Movies
select m;
return View(movies);
}
}
}
For small-time projects and tutorials this is just fine and the recommended approach.
Small tip: You could wrap the MovieDataContext in a using statement which takes care of closing the connection and releasing resources:
using (var dataContext = new MovieDataContext())
{
// query...
}
Keep in mind when using this, you can't lazy-load properties in your view anymore since the data context is closed when the object is sent to the view. So a query like movie.Director.Name won't work, unless you eager-load it.
Yep, that should be the standard way of using the MVC pattern.
It is not necessarily bad, but you can improve on it by applying well known patterns and best-practices, i.e. layering, repositories, etc.
Ideally, it is good to keep the controller as thin as possible and delegate all database operations or whatever logic required on the lower levels, like a service layer for instance.
I am using ASP.NET Web Forms/C#.I am having a page Customer.aspx.I have created CustomerBLL class in which I plan to use Linq To SQL queries to perform all database related tasks.
Consider this example.Here is a method called GetDateFormat() in my CustomerBLL class which returns Date format from database.Here is the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
namespace CwizBankApp
{
public class CustomerBLL
{
public string GetDateFormat()
{
using (var db = new DataClasses1DataContext())
{
var format = db.CODEs.Where(code => code.NAME.Equals("dateformat")).SingleOrDefault();
return format.DRNAME;
}
}
}
}
From code behind I am calling this function inside of another function like this.
public void RetrieveDateFormat()
{
//In this function we retrieve the date format
//from the database to identify if it is british or american
var format = CustomerBLL.GetDateFormat();
//The global variable gDateFormat stores the format
if (format != null)
{
Global.DateFormat = format;
}
I am calling the function and storing the result first and then checking if it is null or not.Should I be doing this way or Should I check if it is null or not in the CustomerBLL.cs file itself?
What is better way to do this.Is my way of calling the function GetDateFormat() feasible.
Also is this approach of maintaining Linq queries in such class files and then calling them from code behind considered to be a good practice?
Can somebody tell me if I am heading in the right direction or not?
Any suggestions are welcome.
Your way of calling the function is ok. However, you should check for null within CustomerBLL.cs.
here are couple of good examples of how to use repository pastern with web-forms
http://msdn.microsoft.com/en-us/library/ff649690.aspx
http://forums.asp.net/t/1808905.aspx/1?Repository+Architecture+Using+WebForm+in+C+With+N+Tier+Architechure
http://code.google.com/p/nhibernate-repository-example/
http://www.expertbloggingon.net/post/2011/11/23/CSharp-Repository-Pattern-Design-Patterns-in-Action.aspx
I've been using T4MVC (FYI: v2.6.62) for quite some time, and I've been slowly moving over our code to this way of working (less reliance on magic strings).
But I've had to stop because, for some reason, T4MVC is unable to translate objects into urls, and only seems to be able to work on primitive types (int/string/etc).
Here is an example:
Route breakdown:
/MyController/MyAction/{Number}/{SomeText}
Class:
namespace MyNamespace
{
public class MyClass
{
public int Number { get; set; }
public string SomeText { get; set; }
}
}
Controller:
public class MyController
{
public virtual ActionResult MyAction(MyClass myClass)
{
return View();
}
}
View:
<%= Html.Action(
T4MVC.MyController.Actions.MyAction(
new MyClass()
{
Number = 1,
SomeText = "ABC"
}
) %>
The end result is this:
/MyController/MyAction?myClass=MyNamespace.MyClass
and not
/MyController/MyAction/1/ABC
Does anyone else have this problem? Are T4MVC urls like this available?
Question also asked at the ASP.NET Forum.
Update (10/11/2012): the recently added support for Model Unbinders (see section 3.1 in the doc) should hopefully cover a lot of these cases.
Original answer:
Copying my reply from the forum thread:
Hmmm, I don't think this has come up yet. Maybe in most cases that people have Action methods that take an object, the object's values come from posted form data, rather than being passed on the URL? In such scenario, the question doesn't arise.
I think in theory T4MVC could be changed to support this. It would just need to promote all the object's top level properties as route values rather than try to use the object itself (obviously, the current behavior is bogus, and is a result of just calling ToString() blindly).
Have others run into this and think it's worth addressing?
If I've understood the problem correctly then the following syntax should allow you to work around the problem.
<%= Html.ActionLink("test", MVC.MyController.MyAction().AddRouteValues(new MyClass() { Number = 5, SomeText = "Hello" })) %>
I think the answer to make the syntax nicer would be to wrap each non value type parameter in a RouteValueDictionary in each generated action result method
Edit: (Response to comment as not enough chars)
Ah ok I managed to recreate the simple example above using this method to give: /MyController/MyAction/5/Hello as the url.
I'm not quite sure how nested complex types would pan out in practice. You could use some recursion to dive down the into the top-level object and reflect over the values to add them but then you open up a new set of issues, such as how to cope with a child property name that is identical to the parent property name.
This seems like it could be a complex problem to solve, in a manner that would work for everyone.
Perhaps some kind of adapter pattern would be most useful to transform a complex object into route values. In the simplest case this might be to declare an extension method ToRouteDictionary that acts on your complex type and transforms it using your knowledge of how it should work. Just thinking out loud as I'm obviously not aware of your use cases