Confused on how to code a Task in Viewmodel



I am trying to get a RingToneTask in my Viewmodel. But since, as far as I understand, a portion of the ringtonetask has to be put in the Constructor on the Mainpage.cs, I dont know how to go about coding the task into my viewmodel. View model is below. For testing purposes, I had the debug.writing portion in there. Now what I want to try to do is replace that debug.writing line with a code that will save the ringtone using the soundpath as a source. Right now, as is, the button used just plays the sound and does not give the option to save as RingTone. If it would help, I have my solution shared on Onedrive is someone is willing to take a look.
I went ahead and uploaded i

Related to : Confused on how to code a Task in Viewmodel
Confused on how to code a Task in Viewmodel
Mobile Programming
I am trying to get a RingToneTask in my Viewmodel. But since, as far as I understand, a portion of the ringtonetask has to be put in the Constructor on the Mainpage.cs, I dont know how to go about coding the task into my viewmodel. View model is below. For testing purposes, I had the debug.writing portion in there. Now what I want to try to do is replace that debug.writing line with a code that will save the ringtone using the soundpath as a source. Right now, as is, the button used just plays the sound and does not give the option to save as RingTone. If it would help, I have my solution shared on Onedrive is someone is willing to take a look.
I went ahead and uploaded i
Design: Task B to pause Task A temporarily to take care of work, and then restart Task A
Mobile Programming

I can't figure out how to do this in a good way.

Basically, I have a program with two key tasks that contain loops that it runs over and over until the user clicks the stop button.

Pseudo code:

  1. Task A is started: a while loop that does work continuously
  2. Task B is started: a System.Timers.Timer that checks continuously for a specific condition
  3. If Task B finds the condition to be true, it should temporarily stop Task A, and do a bunch of work
  4. Once Task B is done with that work it should allow Task A to start looping again, and go back to checking for the specific condition

This then all continues in perpetuity (until user clicks stop button and the program ends).

When I made the first iteration of the program I basically created two separate threads, and then just had bools in the loops that i used for cancellation. So, Task B just set the bool in Task A to be false and used a Thread.Join() to wait until Task A had completely finished before it started doing its work. Once Task B was done, it created Task A on a completely new thread again. This seemed highly inefficient, as there is no reason I should really have to end the thread, when all I want to do is just halt it until Task B is done.

I have been reading up on async ops through Task Parallel Library (async-await), and thought I could perhaps use cancellation tokens instead of the bools, but it looks like once a task is cancelled with cancellation token the token cannot be reset and task cannot be restarted.

In any case, how would you build this?


Should I move the code from code behind file to ViewModel
Mobile Programming

I have buttons and slider in the window. Also I have a button click event. The thing is I use the click event in code behind. However I also adopt MVVW pattern. So I guess that I may convert the code with ICommand etc. I am not sure if it is a right decision.

Please look at my code and advise me. I am new to ICommand and CanExecute.

MainViewModel _dataContext;
public MainWindow()
{
    InitializeComponent();
    _dataContext = new MainViewModel();
    this.DataContext = _dataContext;
    _dataContext.ServerString = "  Connected to Server " + 
ConfigurationManager.AppSettings["Server"]";
}

private async void buttonStart_Click(object sender, RoutedEventArgs e)
{
    try
    {
        cTokenSource = new buttonCancellationTokenSource();
        cToken = cTokenSource.Token;
        paymentTestNumber = count;
        buttonStart.IsEnabled = false;
        buttonStart.IsHitTestVisible = false;
        buttonStart.Background = Brushes.Red;
        buttonCancel.IsEnabled = true;
        buttonCancel.Background = Brushes.Green;
        buttonCancel.IsHitTestVisible = true;

        _dataContext.Items.Clear();
        _dataContext.PaymentTotal = PaymentTotal;
        _dataContext.TotalSuccess = string.Empty;
        _dataContext.TotalFail = string.Empty;
        m_Queue = new BufferBlock<AppointmentReminder>(new
DataflowBlockOptions { BoundedCapacity = 1000 }); // bufferBlock
        slider.IsEnabled = false;
        var producer = Producer(paymentTestNumber);
        var consumer = Consumer();

        await Task.WhenAll(producer, consumer);
        Summary();
        slider.IsEnabled = true;
        cTokenSource = null;
    }

For the View Model.

public class MainViewModel : NotifyUIBase
{
    private string serverString;
    public string ServerString
    {
        get { return serverString; }
        set
        {
            serverString = value;
            RaisePropertyChanged();
        }
    }

    public ObservableCollection<Calls> items = new
ObservableCollection<Calls>();
    public ObservableCollection<Calls> Items
    {
        get { return items; }
        set
        {
            items = value;
            RaisePropertyChanged();
        }
    }

It works well but it may be against the MVVM priciple. So my question is: Do I need convert the event buttonStart_Click to ICommand etc.?


Complex ViewModel. View returns an empty ViewModel. [HttpPost] Action
Mobile Programming

I have a problem with the action that recives a complex ViewModel by POST and all of its object components are null, even though I have initialized them in Action and have returned the whole ViewModel to the View using GET method.

Let me explain the situation. I have a complex model for a View that consists of three sections: Applicant details, Application details, and a list of Recordings. This View is complex to (1) let me see the details of Applicant I am creating application for, (2) have a list of recordings I would like to choose from which then I can add to Application. This is my ViewModel:

public class ApplicantApplicationRecordingsViewModel
{
    // Applicant
    public Applicant Applicant { get; set; }

    // Application
    public Application Application { get; set; }
    public SelectList UsageTypeSelectList { get; private set; }
    public SelectList UsageEndAppSelectList { get; private set; }

    // Recordings
    public IEnumerable<RecordingViewModelApp>
                                RecordingsViewModelApp { get; set; }

    public ApplicantApplicationRecordingsViewModel()
        : this(new MyDBContext())
    {
    }
    public ApplicantApplicationRecordingsViewModel(MyDBContext
dbContext)
    {
            PopulateUsageTypeSelectList(dbContext);
            PupulateUsageEndAppSelectList(dbContext);
    }

    private void PopulateUsageTypeSelectList(MyDBContext dbContext,
                                int? usageTypeSelected = null)
    {
        IEnumerable<UsageType> utQuery =
                dbContext.UsageTypes.OrderBy(
                ut => ut.UsageTypeName).ToList();
        this.UsageTypeSelectList =
                new SelectList(utQuery,
                    "UsageTypeID",
                    "UsageTypeName",
                    usageTypeSelected);
    }
    private void PupulateUsageEndAppSelectList(
                                MyDBContext dbContext,
                                int? usageEndAppSelected = null)
    {
        IEnumerable<UsageEndApp> ueaQuery =
                dbContext.UsageEndApps.OrderBy(uea =>
uea.UsageEndAppName).ToList();
        this.UsageEndAppSelectList =
                new SelectList(ueaQuery,
                    "UsageEndAppID",
                    "UsageEndAppName",
                    usageEndAppSelected);
    }
}

In the controller I simply populate a list of recordings for RecordingViewModelApp, put details of an applicant to Applicant and leave the Application object empty to be filled in a View.

    public ActionResult Create(int? ApplicantID)
    {
        if (ApplicantID == null)
        {
            // Error 400. Bad Request Exception
        }
        ApplicantApplicationRecordingsViewModel viewModel = null;
        using (MyDBContext dbContext = new MyDBContext())
        {
            Applicant applicant =
                    dbContext.Applicants.Find(ApplicantID);
            if (applicant == null)
            {
                // Error 404. Http not found
            }
            List<RecordingViewModelApp> recordings =
                    getViewModel(
                            dbContext.Recordings.ToList(),
                            dbContext);
            viewModel =
                    new
ApplicantApplicationRecordingsViewModel(dbContext);
            viewModel.Applicant = applicant;
            viewModel.RecordingsViewModelApp = recordings;
        }
        return View(viewModel);
    }

The problem is that when I return the ViewModel (ApplicantApplicationRecordingsViewModel) back to the [HttpPost] Create() Action, all the View Model's components are null, e.g. the list of RecordingViewModelApp is null. What Am I missing? I would need to understand what's going on behind the scene and why default model binding doesn't work.

[HttpPost]
[ActionName("Create")]
public ActionResult Create_post(
                    ApplicantApplicationRecordingsViewModel
viewModelToValidate)
{
    // Validation against Application only and TryToUpdate() etc.
}

CHeers!


EDIT:

The View

@model Project.ApplicantApplicationRecordingsViewModel

@{
    string applicantDetails = string.Format("{0} {1} {2}",
            Model.Applicant.title, Model.Applicant.firstName,
Model.Applicant.lastName);
    ViewBag.Title = "Create a new application for " +
applicantDetails;
}

<h2>@ViewBag.Title</h2>
<hr />
@using (Html.BeginForm())
{
    <h3>Details of the applicant</h3>
    @Html.HiddenFor(item => Model.Applicant.ApplicantID)
    @Html.HiddenFor(item => Model.Application.ApplicationID)
    <table>
        <tr>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.title)</th>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.firstName)</th>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.lastName)</th>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.telephone)</th>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.mobile)</th>
            <th>@Html.DisplayNameFor(item =>
Model.Applicant.email)</th>
        </tr>
        <tr>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.title)</td>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.firstName)</td>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.lastName)</td>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.telephone)</td>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.mobile)</td>
            <td class="display-field">@Html.DisplayFor(item
=> Model.Applicant.email)</td>
        </tr>
    </table>
    <hr /> //
----------------------------------------------------------------------------------------------
    <h3>Details of the application</h3>
    <table id="main">
        <tr>
            <td>
                <table>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.ApplicationNo)</td>
                        <td class="editor-field">
                            @Html.EditorFor(item =>
Model.Application.ApplicationNo) 
                            @Html.ValidationMessageFor(item =>
Model.Application.ApplicationNo)
                        </td>
                    </tr>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.StartDate)</td>
                        <td class="editor-field">
                            @Html.EditorFor(item =>
Model.Application.StartDate) 
                            @Html.ValidationMessageFor(item =>
Model.Application.StartDate)
                        </td>
                    </tr>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.EndDate)</td>
                        <td class="editor-field">
                            @Html.EditorFor(item =>
Model.Application.EndDate) 
                            @Html.ValidationMessageFor(item =>
Model.Application.EndDate)
                        </td>
                    </tr>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.UsageTypeID)</td>
                        <td class="editor-field">
                            @Html.DropDownListFor(item =>
Model.Application.UsageTypeID, Model.UsageTypeSelectList, "-- Select
Usage --")
                            @Html.ValidationMessageFor(item =>
Model.Application.UsageTypeID)
                        </td>
                    </tr>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.UsageEndAppID)</td>
                        <td class="editor-field">
                            @Html.DropDownListFor(item =>
Model.Application.UsageEndAppID, Model.UsageEndAppSelectList, "--
Select Type --")
                            @Html.ValidationMessageFor(item =>
Model.Application.UsageEndAppID)
                        </td>
                    </tr>
                    <tr>
                        <td class="editor-label
first-label">@Html.DisplayNameFor(item =>
Model.Application.linkToPaperVer)</td>
                        <td class="editor-field">
                            @Html.EditorFor(item =>
Model.Application.linkToPaperVer) 
                            @Html.ValidationMessageFor(item =>
Model.Application.linkToPaperVer)
                        </td>
                    </tr>
                </table>
            </td>
            <td  class="editor-label">
                @Html.DisplayNameFor(item =>
Model.Application.Info)
            </td>
            <td class="editor-field">
                @Html.EditorFor(item => Model.Application.Info) 
                @Html.ValidationMessageFor(item =>
Model.Application.Info)
            </td>
        </tr>
    </table>
    <hr /> //
----------------------------------------------------------------------------------------------
    <h3>List of recordings</h3>
    Html.RenderPartial("~/Views/Recordings/_List_App.cshtml",
Model.RecordingsViewModelApp);
    <hr /> //
----------------------------------------------------------------------------------------------
    <p>
        <input type="submit" value="Create" />
    </p>
}
<div>
    @Html.ActionLink("Back to List", "Index", "Applicants")
</div>


EDIT 2

PartialView:

@model
IEnumerable<Project.ViewModels.RecordingViewModelApp>

@if (Model != null)
{
    <div>
        <table class="data-in-table">
            <tr>
                <th>@Html.DisplayNameFor(model =>
model.IsSelected)</th>
                <th>@Html.DisplayNameFor(model =>
model.FileLocation)</th>
                <th>@Html.DisplayNameFor(model =>
model.EnteredDate)</th>
                <th>@Html.DisplayNameFor(model =>
model.Duration)</th>
                <th>@Html.DisplayNameFor(model =>
model.Status)</th>
            </tr>
            @foreach (var item in Model)
            {
                <tr>
                    <td
class="display-field">@Html.EditorFor(model =>
item.IsSelected)</td>
                    <td
class="display-field">@Html.DisplayFor(model =>
item.FileLocation)</td>
                    <td
class="display-field">@Html.DisplayFor(model =>
item.EnteredDate)</td>
                    <td
class="display-field">@Html.DisplayFor(model =>
item.Duration)</td>
                    <td
class="display-field">@Html.DisplayFor(model =>
item.Status)</td>
                </tr>
            }
        </table>
    </div>
}
else
{
    <h3>No recordings attached to this Patient</h3>
}

Task.ContinueWith() parent task doesn't wait for child task to finish
Mobile Programming

Since I was understanding the Task in context of nested task, I really don't understand that- Why the 3rd print before 2nd print?

Even though, I have used Task.WaitAll(t), it print 3rd line before 2nd line.

Code:

public static void Main()
        {

            Task t = new Task(
                () =>
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("1st print...");
                });
           t.ContinueWith(
                x =>
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("2nd print...");
                },
                TaskContinuationOptions.OnlyOnRanToCompletion);

            t.Start();
            Task.WaitAll(t);

            Console.WriteLine("3rd print...");
            Console.Read();

}

Output:

enter image
description here


Passing value from one viewmodel to sub viewmodel
Mobile Programming

I'm using .Net FW 4.5, VS 2013 and SQLITE. I've got a "MainWindow" that contains tab items. Each tab item has it's own view and each view has its own VM. I am running a query on my MainWindow that returns data to a datagrid. Depending on which "SelectedItem" is selected I need my query to return relevant sub data to my tab which contains my view/viewmodel... how do I get my main VM to pass a value to my Sub-VM... I've tried "FindVisualParent" but it does not work. I think it's loading up my value after everything is loaded and therefore not applying my filer on my sub-VM query... Hope this makes sense.

Best methods applicable to MVVM would be appreciated.



Privacy Policy - Copyrights Notice - Feedback - Report Violation - RSS 2017 © bighow.org All Rights Reserved .