Calling Linq To SQL queries residing in classes from code behind. - c#

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

Related

Entity Framework ObjectContext.SaveChanges() and class methods

I have more of a theoretical question. If someone could provide me only a link to answer I will be happy as well I just have no idea how to look it up on the internet, so I haven't found an answer.
Lets say I have a class that should check if there is no corrupted data in database. So I have it in normal method etc, with
using (var databaseContext = new ExambleDBEntities())
Purpose of this method is to check if there is corrupt data - and if there is, to repair it. But it is not question about the code itself, so excuse me for not giving any. It is about... what can I do with data from database.
So I have connection to database, database context is set, query done, I have my first date in let's say "TableName dataSample".
Main question is:
Can I send this "dataSample" to other method inside the same function, where it will be changed and then save changes in main method?
Does the ObjectContext keep track of what was taken from database and remember what to save or it MUST be in the same method, under using directive?
I think what I wrote is not clear enough so maybe I'll write some example code:
void MainMethod()
{
using (var databaseContext = new ExambleDBEntities())
{
var DatabaseQuery = from... select... ;
TableName dataSample = DatabaseQuery.First();
dataSample = CorrectMistakes(dataSample);
databaseContext.SaveChanges();
}
}
TableName CorrectMistakes(TableName sample)
{
if (somethingWrong)
sample.money = 0;
return sample;
}
And should I return changed object or can I just edit inside other method?
Sorry for any mistakes, I had really hard time explaining that in English.
Thank you for any help and here is stuff I use in case anyone needs it: Visual Studio 2012, .NET Framework 4.5, MySQL Connector 6.9.4, MySQL for VS 1.2.3.
Yes, you can do that. Sorry, I don't have a link for you, but I just ran a test to be sure and it worked. It shouldn't be too difficult for you to also test this to confirm that it works.
Because you are calling CorrectMistake() inside the using directive, any changes it makes to the TableName object will stay within the current context and be saved when you call SaveChanges().
Can I send this "dataSample" to other method iside the same function, where it will be changed and then save changes in main method?
Yes, you can. Try it out!
Do ObjectContext keep track of what was taken from database and remember what to save or it MUST be in the same method, under using directive?
Yes and no. It "remembers" while you are in the using directive. It doesn't really matter about which method is doing the work, so long as the work is being done while in the using block.
And should I return changed object or can I just edit inside other method?
It doesn't matter, either will work. Do whatever is most appropriate for your situation. If you are just making a change to one of the object's properties, then it probably makes more sense to edit inside the method.
Consider this simple example:
private void ChangeObject(object obj)
{
if (something)
obj.Name = "New name";
}
using (var db = new Context())
{
var obj = db.Objects.First();
ChangeObject(obj);
db.SaveChanges();
}
this is equivalent to:
using (var db = new Context())
{
var obj = db.Objects.First();
if (something)
obj.Name = "New name";
db.SaveChanges();
}

System.Xml.Linq could not be referenced properly at WEALTHLAB editor

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).
...

accessing model from controller, is it a good way?

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.

C# Store values in static dictionary

I have this code , and i want to store values of parameters left, top in static dictionary. and after storing this values i want to access them in Jquery.Thanks For your Help.
my code
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication1.MoveShape
{
public class MoveShapeHub : Hub
{
public void calculate(string left, string top)
{
Clients.Others.updateshape(left, top);
}
}
}
jQuery operates client-side, so you can't talk to it directly. You have two options, then:
request the value via http (perhaps using SignalR as a messaging layer, since you are referencing that)
serialize the dictionary as JSON into the request
Fortunately, the latter is fairly trivial for most common types - here using Json.NET:
var data = new Dictionary<string, object>
{
{"foo", 123},
{"bar", "abc"},
{"blap", true}
};
var json = JsonConvert.SerializeObject(data);
which gives us the JSON:
{"foo":123,"bar":"abc","blap":true}
If you assign that into a variable in the <script>, then values can be referenced either as obj.bar or as obj['bar']. However: keep in mind that all values will be serialized if you do this - you may want to be more restrictive in terms of tracking which the client actually cares about (or should be allowed to know about).
Important point, though: if your "static dictionary" is actually a static dictionary, then please consider very carefully the impact of multiple users. static is a really good way to write a web-site that only scales to a single user.

Lambda expression error in MVC4

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.

Categories