Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to complete my assignment, but I don't know how to create a linked list with multiple branches. I have extracted my data, narrowed it down and then stored it in a List.
List<Route> routes = new List<Route>();
Route contains two string variables: city1Name and city2Name.
Route route = new Route("FirstCity", "SecondCity");
This means that there's a route between FirstCity and SecondCity. Each city can have multiple routes to other cities.
Could someone show me how to store the this data in a linked list?
I understand what a linked list is and I think I could fetch the multiple possible route data using foreach afterwards, but I was not able to write an algorithm for that. :(
You can use List<T>.Add to append any item of type T while T can be any .NET compliant data type. In your case T is Route. So, you can append any value that can be implicitly convertible to Route
routes.Add(route);
Further, In .NET List<T> is not a link list. List<T> is implemented using Array internally. Link List implementation in .NET is LinkList<T>
EDIT
Here is a very simple implementation to find path form one city to other.
static bool TryFindPath(List<Route> routes, string from, string to, int maxDepth) {
if (maxDepth <= 0) // To prevent StackOverFlowException
return false;
// Find all the routes with starting point == `from`
var startingPoints = Routes.Where(r => r.From == from).ToArray();
if (startingPoints.Length == 0) // No such route exists
return false;
// See if any of route directly leads to `to`
var matchingRoute = startingPoints.Where(r => r.To == to).FirstOrDefault();
if (matchingRoute != null) {
routes.Add(matchingRoute); // If so, we found that
return true;
}
// We are stepping into next level, decrease maxDepth by one
maxDepth -= 1;
// Otherwise iterate through all starting points and find path from
// that specific city refered by to our destination
foreach (var route in startingPoints) {
// Clone `routes`
var thisRoutes = new List<Route>(routes);
thisRoutes.Add(route);
if (TryFindPath(thisRoutes, route.To, to, maxDepth)) {
// Copy all newly added routes in `thisRoutes` to original `routes`
for (var i = routes.Count; i < thisRoutes.Count; i++) {
routes.Add(thisRoutes[i]);
}
return true;
}
}
return false;
}
I'm supposing following definition of Route class
class Route {
public string From { get; set; }
public string To { get; set; }
public Route(string from, string to) {
From = from;
To = to;
}
}
You can find working demo here
List<Route> routes = new List<Route>();
Route route = new Route("FirstCity", "SecondCity");
routes.Add(route);
foreach (oneRoute in routes)
{
// The other work you're interested in doing
// oneRoute represents each single route one at a time.
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've got some routing with parameters set-up in ASP.NET MVC 4 + Razor.
I am passing a parameter of {id} to the controller... and then on the controller I want to check the following:
A. if the id exists in the database, return view
B. if the id was not provided, redirect to Index
I've no idea how to go about doing those - and searching around doesn't really provide any information.
Could someone show me how to do an if / else statement to check if {id} has been provided?
The controller:
public ActionResult View(int id)
{
return View();
}
You can make your method parameter a nullable int so that it will work for the request urls such as
yourDomainName/yourController/view and yourDomainName/yourController/view/25
public ActionResult View(int? id)
{
if(id!=null) // id came in the request
{
int postId= id.Value;
var postViewModel = new PostViewModel { Id=postId};
// Use postId to get your entity/View model from db and then return view
// The below is the code to get data from Db.
// Read further if your data access method is different.
var db = new MyDbContext()
var post=db.Posts.FirstOrDefault(x=>x.Id==postId);
if(post!=null)
{
postViewModel.Title = post.Title;
return View(postViewModel);
}
return View("PostNotFound"); // Make sure you have this view.
}
//If code reaches here, that means no id value came in request.
return RedirectToAction("Index");
}
Assuming MyDbContext is your DbContext class and you are using Entity framework for data access. If your data access method is different ( ADO.NET/NHibernate etc..), You may update that part of code with your data access code.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.
Help please.
Here is my code:
public int PostHomeLead(string _lead)
{
try
{
int result = 0;
Lead lead = new Lead();
lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);
//check if lead exist with same session id, if so update it other wise add new.
Lead existingLead = new Lead();
existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);
if (existingLead == null)
{
db2.HomeLoanCustRepo.Insert(lead);
db2.Save();
result = 1;
}
else
{
db2.HomeLoanCustRepo.Update(lead);
db2.Save();
result = 1;
}
return result;
}
catch(Exception ex)
{
throw ex;
}
}
Either map the properties manually:
existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;
Or use a library that does this, like AutoMapper.
As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.
I am using a few methods and interfaces in this one. What i need is for the method I'm making to just simply remove 1 value in an array of attributes. All of the stuff here was previously created by someone else, and I'm just creating the removal part for the attribute to be removed. At any rate, the method that does the profile attribute work and sets the value does some work on the back end. I have a method for a UserProfileAttributeSetRequest that looks like this:
public UserProfileAttributeSetRequest()
{
}
public UserProfileAttributeSetRequest(Guid userIdentifier, Dictionary<string, string> profileAttributes)
{
UserIdentifier = userIdentifier;
ProfileAttributes = profileAttributes;
}
This fires a method on the back end that will take in the information being passed to it and change whatever needs to be changed. The method I'm building in the controller probably needs some work, I'm still fairly new to MVC, but here's what I've got:
public ActionResult RemoveEmployeeID(UserInfo userInfo)
{
User usr = UserManager.GetUser(userInfo.UserGuid);
var empID = usr.ProfileAttributes.FirstOrDefault(e => e.ProfileAttributeID == 3);
usr.ProfileAttributes.Remove(empID);
UserProfileAttributeSetRequest upd = new UserProfileAttributeSetRequest();
}
I'm grabbing the complete user, and isolating the single attribute I want to be changed, but the Request complains when I put any parameters in it. What am I doing wrong?
try like this
var emp = usr.ProfileAttributes.Where(e => e.ProfileAttributeID == 3).FirstOrDefault();
usr.ProfileAttributes.Remove(emp);
you have to update the database after removing the item.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
So, it's pretty well known that the infamous NullReferenceException is the most common exception in software products. I've been reading some articles, and found myself with the Optional approach.
Its aim is to create some kind of encapsulation around a nullable value
public sealed class Optional<T> where T : class {
private T value;
private Optional(T value) {
this.value = value;
}
//Used to create an empty container
public static Optional<T> Empty() {
return new Optional(null);
}
//Used to create a container with a non-null value
public static Optional<T> For(T value) {
return new Optional(value);
}
//Used to check if the container holds a non-null value
public bool IsPresent {
get { return value != null; }
}
//Retrieves the non-null value
public T Value {
get { return value; }
}
}
Afterwards, the now optional value can be returned like this:
public Optional<ICustomer> FindCustomerByName(string name)
{
ICustomer customer = null;
// Code to find the customer in database
if(customer != null) {
return Optional.Of(customer);
} else {
return Optional.Empty();
}
}
And handled like this:
Optional<ICustomer> optionalCustomer = repository.FindCustomerByName("Matt");
if(optionalCustomer.IsPresent) {
ICustomer foundCustomer = optionalCustomer.Value;
Console.WriteLine("Customer found: " + customer.ToString());
} else {
Console.WriteLine("Customer not found");
}
I don't see any improvement, just shifted complexity.
The programmer must remember to check if a value IsPresent, in the same way he must remember to check if a value != null.
And if he forgets, he would get a NullReferenceException on both approaches.
What am I missing? What advantages (if any) does the Optional pattern provide over something like Nullable<T> and the null coalescing operator?
Free your mind
If you think of Option as Nullable by a different name then you are absolutely correct - Option is simply Nullable for reference types.
The Option pattern makes more sense if you view it as a monad or as a specialized collection that contain either one or zero values.
Option as a collection
Consider a simple foreach loop with a list that cannot be null:
public void DoWork<T>(List<T> someList) {
foreach (var el in someList) {
Console.WriteLine(el);
}
}
If you pass an empty list to DoWork, nothing happens:
DoWork(new List<int>());
If you pass a list with one or more elements in it, work happens:
DoWork(new List<int>(1));
// 1
Let's alias the empty list to None and the list with one entry in it to Some:
var None = new List<int>();
var Some = new List(1);
We can pass these variables to DoWork and we get the same behavior as before:
DoWork(None);
DoWork(Some);
// 1
Of course, we can also use LINQ extension methods:
Some.Where(x => x > 0).Select(x => x * 2);
// List(2)
// Some -> Transform Function(s) -> another Some
None.Where(x => x > 0).Select(x => x * 2);
// List()
// None -> None
Some.Where(x => x > 100).Select(x => x * 2);
// List() aka None
// Some -> A Transform that eliminates the element -> None
Interesting side note: LINQ is monadic.
Wait, what just happened?
By wrapping the value that we want inside a list we were suddenly able to only apply an operation to the value if we actually had a value in the first place!
Extending Optional
With that consideration in mind, let's add a few methods to Optional to let us work with it as if it were a collection (alternately, we could make it a specialized version of IEnumerable that only allows one entry):
// map makes it easy to work with pure functions
public Optional<TOut> Map<TIn, TOut>(Func<TIn, TOut> f) where TIn : T {
return IsPresent ? Optional.For(f(value)) : Empty();
}
// foreach is for side-effects
public Optional<T> Foreach(Action<T> f) {
if (IsPresent) f(value);
return this;
}
// getOrElse for defaults
public T GetOrElse(Func<T> f) {
return IsPresent ? value : f();
}
public T GetOrElse(T defaultValue) { return IsPresent ? value: defaultValue; }
// orElse for taking actions when dealing with `None`
public void OrElse(Action<T> f) { if (!IsPresent) f(); }
Then your code becomes:
Optional<ICustomer> optionalCustomer = repository.FindCustomerByName("Matt");
optionalCustomer
.Foreach(customer =>
Console.WriteLine("Customer found: " + customer.ToString()))
.OrElse(() => Console.WriteLine("Customer not found"));
Not much savings there, right? And two more anonymous functions - so why would we do this? Because, just like LINQ, it enables us to set up a chain of behavior that only executes as long as we have the input that we need. For example:
optionalCustomer
.Map(predictCustomerBehavior)
.Map(chooseIncentiveBasedOnPredictedBehavior)
.Foreach(scheduleIncentiveMessage);
Each of these actions (predictCustomerBehavior, chooseIncentiveBasedOnPredictedBehavior, scheduleIncentiveMessage) is expensive - but they will only happen if we have a customer to begin with!
It gets better though - after some study we realize that we cannot always predict customer behavior. So we change the signature of predictCustomerBehavior to return an Optional<CustomerBehaviorPrediction> and change our second Map call in the chain to FlatMap:
optionalCustomer
.FlatMap(predictCustomerBehavior)
.Map(chooseIncentiveBasedOnPredictedBehavior)
.Foreach(scheduleIncentiveMessage);
which is defined as:
public Optional<TOut> FlatMap<TIn, TOut>(Func<TIn, Optional<TOut>> f) where TIn : T {
var Optional<Optional<TOut>> result = Map(f)
return result.IsPresent ? result.value : Empty();
}
This starts to look a lot like LINQ (FlatMap -> Flatten, for example).
Further possible refinements
In order to get more utility out of Optional we should really make it implement IEnumerable. Additionally, we can take advantage of polymorphism and create two sub-types of Optional, Some and None to represent the full list and the empty list case. Then our methods can drop the IsPresent checks, making them easier to read.
TL;DR
The advantages of LINQ for expensive operations are obvious:
someList
.Where(cheapOp1)
.SkipWhile(cheapOp2)
.GroupBy(expensiveOp)
.Select(expensiveProjection);
Optional, when viewed as a collection of one or zero values provides a similar benefit (and there's no reason it couldn't implement IEnumerable so that LINQ methods would work on it as well):
someOptional
.FlatMap(expensiveOp1)
.Filter(expensiveOp2)
.GetOrElse(generateDefaultValue);
Further suggested reading
Option (F#)
When null is not enough (C#)
The neophytes guide to Scala Part 5: The Option type
The Marvel of Monads (C#)
Eric Lippert's series on LINQ and monads
it would probally make more sense if you used something like this
interface ICustomer {
String name { get; }
}
public class OptionalCustomer : ICustomer {
public OptionalCustomer (ICustomer value) {
this.value = value;
}
public static OptionalCustomer Empty() {
return new OptionalCustomer(null);
}
ICustomer value;
public String name { get {
if (value == null ) {
return "No customer found";
}
return value.Name;
}
}
}
now if your pass an "empty" optional customer object you can still call the .Name property (without getting nullpointers)
The advantage of Optional is you know if something may not exist.
The problem with many types of queries that return a null is that that could mean 2 things:
The query didn't return a result
The query returned a result whose value was null.
I know you're asking specifically about C# but Java just introduced Optionals in Java 8 so there are a lot of articles about it so I'll use Java as an example. but it's completely the same idea as in C#:
Consider the Java Map.get(key) method
Object value = map.get(key);
if(value ==null){
//is there an entry in the map key =>null or does key not exist?
}
to get around that you have to have an additional method containsKey( k)
With optional, you only need one method
Optional<Object> result = map.get(key);
if(result.isPresent()){
Object value = result.get();
//if value is null, then we know that key =>null
}
More info see this Java article : http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html
Did you mean: Null Object pattern
The article linked to me in the comments contains a conclusion section explained this programming tool.
... The purpose of Optional is not to replace every single null reference in your codebase but rather to help design better APIs in which—just by reading the signature of a method—users can tell whether to expect an optional value. .... deal with the absence of a value; as a result, you protect your code against unintended null pointer exceptions.
Anyway, let it crash and find the reason. If you do not want endlessly embedded if statements than use an implementation pattern Guard Clause pattern, which says the following:
While programs have a main flow, some situations require deviations from the
main flow. The guard clause is a way to express simple and local exceptional
situations with purely local consequences.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
The following code snippet is from our ASP.NET MVC 4 application that builds a menu based on the user. We're also using EF 6
MenuBarController
public ActionResult GetMenuList()
{
using (spc_aspEntities db = new spc_aspEntities())
{
ProgramMenuDAL programMenuDAL = new ProgramMenuDAL(db);
List<ProgramMenuDTO> programMenuList = programMenuDAL.GetMenuListForUser("1");
return View(programMenuList);
}
}
ProgramMenuDAL
public class ProgramMenuDAL : BaseDAL
{
private const string TOP_MENU_TYPE = "Menu";
private const string SUB_MENU_TYPE = "Submenu";
public ProgramMenuDAL(spc_aspEntities dbContext)
: base(dbContext)
{
}
public List<ProgramMenuDTO> GetMenuListForUser(string userLoginId)
{
//Get user info first
var userInfo = _dbContext.USER_TB.First(x => x.USER_SABUN == userLoginId);
string userGroupId = userInfo.USER_LEVEL;
//Retrieve all top menu first
var topMenuList =
from program_tb in _dbContext.PROGRAM_TB
where program_tb.PROGRAM_GB == TOP_MENU_TYPE
orderby program_tb.PROGRAM_ORDER
select new { program_tb.PROGRAM_ID, program_tb.PROGRAM_NAME };
Debug.Assert(topMenuList.Any(), "Top Menu is Empty");
List<ProgramMenuDTO> programMenuList = new List<ProgramMenuDTO>();
//Retrieve all sub menus
foreach (var topMenu in topMenuList)
{
var subMenuList =
from program_tb in _dbContext.PROGRAM_TB
from group_auth_tb in _dbContext.GROUP_AUTH_TB
where program_tb.PROGRAM_ID == group_auth_tb.PROGRAM_ID
&& program_tb.PROGRAM_SYSTEM == topMenu.PROGRAM_NAME
&& program_tb.PROGRAM_GB == SUB_MENU_TYPE
&& group_auth_tb.GROUP_ID == userGroupId
&& group_auth_tb.OPEN_YN == "True"
orderby program_tb.PROGRAM_ORDER
select new { program_tb.PROGRAM_ID, program_tb.PROGRAM_NAME };
if (!subMenuList.Any())
continue;
List<ProgramSubMenuDTO> programSubMenuList = new List<ProgramSubMenuDTO>();
subMenuList.ToList().ForEach(x=>programSubMenuList.Add(new ProgramSubMenuDTO(x.PROGRAM_ID, x.PROGRAM_NAME)));
programMenuList.Add(new ProgramMenuDTO(topMenu.PROGRAM_ID,topMenu.PROGRAM_NAME,programSubMenuList));
}
return programMenuList;
}
}
BaseDAL
public abstract class BaseDAL
{
protected readonly spc_aspEntities _dbContext;
protected BaseDAL(spc_aspEntities dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("Database Context cannot be null");
_dbContext = dbContext;
}
}
The view corresponding to the controller is then loaded onto our shared layout using RenderAction.
#{Html.RenderAction("GetMenuList", "Menubar");}
Here are my question:
Does the code look sound architecturally? I've tried to separate business logic and data access layer (We've decided on not using the repository pattern). You can see that the query looks quite awkward, but given our initial database design, it seems like there's really no way around it.
This code is slowing down our website quite a bit. Before, each request to the main index would take about 50ms. Now it takes 500ms in debug mode, 200ms in release mode. What are some strategies I can use to tune the code?
--Edit--
One more question
We're wrapping all dbcontexts in using statement, requiring us to write the same code in every action. Would it be fine to just declare a private variable for the database and use it in the same class? What are some strategies around this?
I cringe when I see DAL and DTO combined with Entity Framework. EF is your DAL and provides DTO classes you can extend. You generally project the EF classes into Models in MVC.
Personally I would extend your DbContext with extra methods for specific tasks, and also avoid doing a query inside a for-each loop.
public partial class spc_aspEntities
{
public List<Models.ProgramMenu> GetMenuForUser(string userLoginId)
{
// existing code to get USER_LEVEL..
// create a single query to get your full menu structure
// your EF model should already include the relationship
// between PROGRAM_TB and GROUP_AUTH_TB
var query = this.PROGRAM_TB
.Where(p => p.PROGRAM_GB == TOP_MENU_TYPE)
.OrderBy(p => p.PROGRAM_ORDER)
.Select(p => new {
p.PROGRAM_ID,
p.PROGRAM_NAME,
// assuming there's also a relationship defined
// between PROGRAM_TB and itself on
// PROGRAM_SYSTEM == (parent).PROGRAM_NAME
SubMenus = p.ChildPrograms
.Where(cp => cp.PROGRAM_GB == SUB_MENU_TYPE)
.Where(cp => cp.GroupAuths
.Any(g => g.GROUP_ID == userGroupId
&& g.OPEN_YN == "True"
)
)
.Select(cp => new { cp.PROGRAM_ID, cp.PROGRAM_NAME })
});
// now project this into your model, ToList() forces the query to run so
// we can then perform non-sql manipulation (like newing up objects etc)
var programMenuList = query.ToList()
.Select(anon => new Models.ProgramMenu(
anon.PROGRAM_ID,
anon.PROGRAM_NAME,
anon.SubMenus.Select(sub => new Models.ProgramSubMenu(
sub.PROGRAM_ID,
sub.PROGRAM_NAME
).ToList()
)).ToList();
return programMenuList;
}
}
All this is created without any testing or deeper knowledge of your system. I see many issues with names and structure here, I've left most as-is but I would seriously consider code-readability as an important feature.
In my opinion you should add cache, because I am sure that menu doesn't change for user.
The second problem is that you don't get whole menu in one query instead you run query for each submenu.