I have a problem with my MVC application. The application is about a tracklist where there is a function called create track.
I have created a dataprovider class which adds dummy data to a list. Then the list gets show on the page. The list itself works and it show the dummy data. Now i have created a create action in my controller like this:
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
int hours = int.Parse(collection["Hours"]);
int minutes = int.Parse(collection["Minutes"]);
int seconds = int.Parse(collection["Seconds"]);
Track track = new Track();
track.Name = collection["Name"];
track.Artist = collection["Artist"];
track.AlbumSource = collection["AlbumSource"];
track.length = new AudioDevices.Time(hours, minutes, seconds);
track.Style = (Category)Enum.Parse(typeof(Category), collection["style"]);
trackList.Add(track);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Now... When i start my application I click create. There i enter information for my track and click save. Now when it saves i go back to my list of tracks, but the track doesnt get added to my list.
My Visual Studio shows that the code has handled 2 requests without any errors. It just doesnt get added to the list.
I understand that i am not working with a database and i dont want to work with a database since its not needed in this excercise. I understand that the track will dissapear after restarting the program.
I have instantiaded the tracklist like this at the end of my trackcontroller.cs:
private static List<Track> trackList;
public TrackController()
{
if(trackList == null)
{
trackList = DataProvider.GenerateDefaultTracks();
}
}
If your code follows the standard pattern, every time your Create function is called in the controller, a new controller is created. If your object trackList is created in the constructor, then a fresh one will be created for each call to Create giving the impression that nothing has happened.
Your data is stored in a variable. This variable is not public so it is not obtainable for the view unless you pass it along.
I suggest you store the tracklist in the ViewBag. this way it's accessible from the view.
Now I do not know how you implemented the tracklist so I will just give an example.
define when the page is created.
ViewBag.tracklist = new List<Track>();
after creating the track you put it in the viewbag like this:
ViewBag.trackList.Add(track);
You can access this data in the view or pass it along in the action index parameters like:
return View(ViewBag.tracklist);
I have never actually closed this, but it turned out my visual studio was corrupt. Everything worked fine as i did not received any erros. Reinstalling visual studio worked out.
Related
I have a WCF service library, name ServerWCF, which contains a "AdminService" service. One of the methods of this service is List LoadStation() which should return a List of train stations from my database.
I also have a WPF Client, and I'm using a dropdown that should contain the Cities of the stations. When I added the Service Reference in the client, named AdminServiceReference, i noticed that the signature of the method is Station[] Load Station() instead on ListLoadStation(). I don't know if I can do anything about this as the code is generated automatically in the client, but whatever(I used the resharper refactoring suggestion, but didn't make any difference). The problem is that on the below code, the foreach line is never accessed. I placed a breakpoint on the line above, I stepped into and noticed that the list returned by the Server contains all of the station, which is a good thing, but after i step out and step over, the program is not going to the foreach that populates the dropdown, but returns to the second line, which is the reason why, obviously, my dropdown remains empty, lonely and sad :( Any tip on how can i sort this out? PS: that same code worked fine when my list was a ArrayList and was containing only Cities, but I need all the objects.
Client code:
private void fromStationCB_DropDownOpened(object sender, EventArgs e)
{
var adminProxy = new AdminServiceClient();
fromStationCB.Items.Clear();
var list = adminProxy.LoadStations();
foreach (var items in list)
fromStationCB.Items.Add(items.City);
label5.Content = "";
}
Server code:
public List<Station> LoadStations()
{
List<Station> list = new List<Station>();
using (var context = new RailwaySystemModelContainer())
{
/*foreach (var station in context.Stations)
list.Add(station);*/
list.AddRange(context.Stations);
return list;
}
}
I had some problems when using list as a return type. It was something different, but you can try change the return type of LoadStations to an array of Station. Also try delete your reference, build the server side code and then add the reference again. You can have some mismatch. Also Station should be marked as a DataContract and its properties as DataMember to successfully pass it via service.
I know that for me to create a data driven test that i need to use a datasource with the test method, and that the datasource had to have already existed.
My question is how about if you want to make a test method data driven but you don't have the datasource file at run time.
Edit
What i mean is I want to basically iterate over the same test X number of times. The reason I dont have the data is because i have to first fetch the data first and then iterate over it.
below i created a test that ran for each of my hyperlink but after the test pass i only get results Passed Once instead for each iteration of my hyperlink. I also tried to launch something in the "[TestInitialize()]" section and assign my data file to it but since the data file has to be constant(or already exist), i cant do it. Any help with this would be great
[TestMethod]
public void Verify_Rates_Links()
{
HomePage getLinks = new HomePage(GlobalVariable.Browser);
int PicCount = 0;
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
PageObjects.Shared.SharedBetweenPage StarTest = new PageObjects.Shared.SharedBetweenPage(GlobalVariable.Browser);
getLinks.GetAllHeaderLinks("Rates", "3", GlobalVariable.Rates_Links);
foreach ( HtmlHyperlink links in GlobalVariable.Rates_Links)
{
Assert.IsTrue(
StarTest.LetsGoToHomePage()
.LetsclickLink(links)
.VerifyLocationPage("Rates","Rates", "Rates", "VerifyRateslinkBreadcrumb" + PicCount.ToString() + ".jpg", "VerifyRatesHeader" + PicCount.ToString() + ".jpg"),
"There is an issue with Rates to create new membership APP one or more of the work flows is not work");
//Playback.Cleanup();
//testcl
PicCount++;
}
}
~Will
I follow the steps in this page http://blogs.msdn.com/b/visualstudio/archive/2009/12/09/building-and-publishing-an-extension-for-visual-studio-2010.aspx
I create a TextAdornment project and a search box. I wan to do some different in this page. I want to query a link , get a list in the WPF user control and then write the info into the editor back. so the question is I do not know how to write the text back into the editor in seachbox(WPF user control)?
I searched a lot, and get a way to use the code look like this:
IVsTextManager txtMgr = (IVsTextManager)GetService(typeof(SVsTextManager));
IVsTextView vTextView = null;
int mustHaveFocus = 1;
txtMgr.GetActiveView(mustHaveFocus, null, out vTextView);
IVsUserData userData = vTextView as IVsUserData;
if (userData == null)
{
return null;
}
else
{
IWpfTextViewHost viewHost;
object holder;
Guid guidViewHost = DefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidViewHost, out holder);
viewHost = (IWpfTextViewHost)holder;
return viewHost;
}
However, the method "GetService" also said not found. I think the reason is this method is for VSPackage. and it is not suitable for Adornment project.
Please help to point how the write the text back into the editor from WPF user control. Thanks!
======================================================================================
Solution:
when creating the SearchBox(WPF User Control), pass through the IWpfTextView to WPF control.and then,it is possible to use this in SearchBox.xaml.cs. Also need to be aware to use the Dispatcher function to keep the UI thread is the active one.
Dispatcher.Invoke(new Action(() =>
{
ITextEdit edit = _view.TextBuffer.CreateEdit();
ITextSnapshot snapshot = edit.Snapshot;
int position = snapshot.GetText().IndexOf("gist:");
edit.Delete(position, 5);
edit.Insert(position, "billmo");
edit.Apply();
}));
The code you have there is if you're in a package and you are trying to figure out what view is currently active...it's overkill for what you're trying to do.
Assuming you started from the TextAdornment template, the adornment object is given an IWpfTextView in the constructor. (If not, you probably have an implementation of IWpfTextCreationListener.TextViewCreated which got it and you need to thread it through.) The IWpfTextView derives ITextView which has a property ITextBuffer. From here, you can call CreateEdit() and edit text from there.
I originally thought this was a INotifyPropertyChanged/Binding issue because I'm not sure how to debug the silverlight part. So I had to put a messagebox in a foreach loop and view the values after the data returned that way. It turns out that I'm having trouble getting the updated data from the service. I use the service to do some updates to data on the server and when it gets back call to reload the data. This part of the service is returning the correct data (I verified using a breakpoint so I could look at the data result was holding). But the silverlight side is not getting the right data. Here is the relevant code.
public IQueryable<OurClass> GetItems(string condition)
{
var result = from items in context.OurClass
where item.value == condition
select item;
return result; //had my breakpoint here and the values were the correct updated values
}
/
Context.Load<OurClass>(Context.GetItemsQuery(condition)).Completed += new EventHandler(Context_LoadCompleted);
/
private void Context_LoadCompleted(object sender, EventArgs e)
{
IEnumerable<OurClass> result = ((LoadOperation<OurClass>)sender).Entities;
//This is where I put a MessageBox to view the returned results and the data was different
//than what was contained in the other result
}
Any ideas what could cause this? What should I look at next?
EDIT:
Some example data is OurClass.OurProperty will equal "Test" on the server side but once it is received on the client it will equal "Development" which was the old value. The IEnumerable will hold the newly added records and not have the deleted ones. Any that previously existed will contain the old property values and not the new values.
The solution was that I needed to add the parameter LoadBehavior.RefreshCurrent to the query call. So this:
Context.Load<OurClass>(Context.GetItemsQuery(condition)).Completed += new EventHandler(Context_LoadCompleted);
Needed to be this:
Context.Load<OurClass>(Context.GetItemsQuery(condition), LoadBehavior.RefreshCurrent, true).Completed += new EventHandler(Context_LoadCompleted);
How is the data different on each side of the service? can you show us some example data. You can have a look at data using something like wireshark (will need to be on the server, or on your client where you are running your silverlight applet from.)
Have you tried debugging your silverlight properly, ie attach to the process as shown here: http://www.michaelsnow.com/2010/04/22/silverlight-tip-of-the-day-2-attach-to-process-debugging/
I would also recommend turning on WCF tracing as detailed here: http://msdn.microsoft.com/en-us/library/ms733025.aspx
I'm currently trying to figure out what's wrong with my code:
Doesn't work
if(...){
...
}else{
someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
Works
if(...){
...
}else{
//someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
.. why and any solutions for this?
Because you are attempting to act on the INIT rather than the load, the data has not yet been attached at the server.
You should find this review of the life cycle of a web request in ASP.NET useful: MSDN ASP.NET Page Life Cycle
Here is the relevant extract:
Initialization
During page initialization, controls on the page are available and
each control's UniqueID property is
set. A master page and themes are also
applied to the page if applicable. If
the current request is a postback, the
postback data has not yet been loaded
and control property values have not
been restored to the values from view
state.
Load
During load, if the current request is a postback, control
properties are loaded with information
recovered from view state and control
state.
Move the code you are trying to execute into (or after) the page load handler (remember to test for IsPostBack) and see if that doesn't get what you want.
Something New to try:
try changing your doesn't work to:
if(...){
...
}else{
string someVariableAsString = "myValue123";
MultiView1.SetActiveView(My3thView_ID_In_MultiViewControl);
}
It sounds like someVariableAsString is possibly throwing an exception to cause the code not to reach the next line. Check your variable type.
I was able to get a solution to my case:
I changed someVariableAsString to a Property as View.
Created a session variable to Gobal.asax and now I get correct result (one page load later). :-)
but in my case this will do.
Problem solved.
onInit{
m_myVariable;
myFunction();
...
}
void myFunction(){
// if clause described up
}
public View myVariable
{
get { return m_myVariable = Session["myVariableAtSession"] as View; }
set { m_myVariable = value;
Session["myVariableAtSession"] = m_myVariable;
}
}