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).
...
Related
Im trying to read a csv file using CSVTools library the code that I have to use to get the csv file in to a data table is,
var dt = DataTable.New.ReadLazy(filename);
But the problem is there is no ".New" keyword. When I write DataTable.New it shows an error. Can someone help me ?
You need to include using statement on top of c# file as below
using DataAccess;
or use
var dt = DataAccess.DataTable.New.ReadLazy(filename);
Which means the DataTable that you are using is not belongs to the
expected namespace, use fully qualified name to get the correct
class.
You may have both using DataAccess; as well as System.Data in your using section, so by declaring DataTable alone will made compiler to assumes that it belongs to System.Data. By specifying the DataTable as DataAccess.DataTable you can help the compiler to find the exact class that you are looking for. This kind of specification is called fully qualified names. Make use of them and come out from that specified error. Your declaration will be like the following:
var dt = DataAccess.DataTable.New.ReadLazy(filename);
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 using visual studio 2012 premium update 4 with Entity Framework 6.1.2 using Database first modelling. I need to change Code Generation Strategy None to Default in order to customise connection string within the code
but when I switch from None to Default I get loads of errors like
The best overloaded method match for 'System.Data.Entity.DbContext.DbContext(string, System.Data.Entity.Infrastructure.DbCompiledModel)' has some invalid arguments
Error 3 'ClassLibrary3.PHEntities' does not contain a definition for 'ContextOptions' and no extension method 'ContextOptions' accepting a first argument of type 'ClassLibrary3.PHEntities' could be found (are you missing a using directive or an assembly reference?) C:\Users\demo\Documents\Visual Studio 2012\Projects\ClassLibrary1\ClassLibrary3\Model1.Designer.cs 36 18 ClassLibrary3
so by deleting Model1.Context.tt and Model1.tt the errors disappeared and I can pass my customised connection string.
string connection = PMCommon.PMSettings.GetEFPHConnectionString(Common.Settings.ConnectionString);
using (var context = new PMEntities(connection))
{
var tests = from c in context.tblTags select c;
}
I need to know are there any hidden dangers associated with this approach that could bite me in the future because I am adding a new module to a large data driven ASP.NET web application that uses loosely typed and strongly typed dataset extensively and I want to implement new stuff with Entity Framework
Don't do this. All you have to do is this. Create a new file called PMEntities2.cs, in there do this:
public partial class PMEntities
{
public PMEntities(string connnectionString) : base(connectionString){}
}
That's it. You don't need to change the code generation strategy.
I've been attempting to set up FizzlerEx, found at http://fizzlerex.codeplex.com/. After adding the references to my project, I've attempted to run the example code given on the website- the entirety of my code is listed below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
namespace Fizzler_Test
{
class Program
{
static void Main(string[] args)
{
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;
foreach (var item in page.QuerySelectorAll("div.item"))
{
var title = item.QuerySelector("h3:not(.share)").InnerText;
var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
var description = item.QuerySelector("span:has(b)").InnerHtml;
}
}
}
However, this yields build errors, claiming that:
Error 1 'HtmlAgilityPack.HtmlNode' does not contain a definition for 'QuerySelectorAll' and no extension method 'QuerySelectorAll' accepting a first argument of type 'HtmlAgilityPack.HtmlNode' could be found (are you missing a using directive or an assembly reference?)
It would seem that QuerySelectorAll is not actually a part of HtmlNode, but given that this is the official example code taken verbatim from the website, I'd expect the creators understand how their library works. I'm at a loss as to what the actual issue could be.
A related problem seems to have been found here, but no suitable answer was ever found: Fizzler and QuerySelectorAll
It would seem that QuerySelectorAll is not actually a part of HtmlNode, but given that this is the official example code taken
verbatim from the website, I'd expect the creators understand how
their library works. I'm at a loss as to what the actual issue could
be.
You are correct about this part. Though you are not correct about the second part, since the author of HAP isn't the author of FizzlerEx. The problem is elsewhere.
Simply by looking at the error, you get the only clue you need to go to solve this .
Error 1 'HtmlAgilityPack.HtmlNode' does not contain a definition for 'QuerySelectorAll' and no extension method 'QuerySelectorAll' accepting a first argument of type 'HtmlAgilityPack.HtmlNode' could be found (are you missing a using directive or an assembly reference?)
So, what do we get; it tells us that there is no method called QuerySelectorAll in the class HtmlNode in the namespace HtmlAgilityPack. If we take a look at the source code of HAP, you can easily determine that the error message is indeed correct, since there is no method by that name in the class we are looking.
Source code for HtmlAgilityPack.HtmlNode - class
Where is this method that we want to use, but cannot find?
It's here, In the Fizzler.Systems.HtmlAgilityPack.HtmlNodeSelection-class.
After trying a few things, I get the code to work perfectly just as it is. The problem was the extensions in the reference between Fizzler and HAP source code.
If you download Fizzler you get HtmlAgilityPack at the same time. When you add the references in Visual Studio (assuming you use that), only add
Fizzler.Systems.HtmlAgilityPack.dll
HtmlAgilityPack.dll
Clean your solution and rebuild it and it should work!
You should add Fizzler by right clicking on references -> Manage Nuget Package, and search online for it, you will find it as Fizzler for HtmlAgilityPack, and then can download it.
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.