Proper Unit Test for ASP.NET MVC5 - c#

I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.
Thank you in advance for ANY clue!
[AllowAnonymous]
public ActionResult ForgotPassword(string id)
{
var model = new ForgotPasswordViewModel();
if (!string.IsNullOrEmpty(id))
{
#region Process Reset Password Key
try
{
var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id);
if (forgotPasswordEvent != null)
{
var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(),
forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString());
var readyHash = SecurityHelper.GetHashString(stringToHash);
if (id == readyHash)
{
var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString();
var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId);
if (realUser != null)
{
var resetPasswordViewModel = new ResetPasswordViewModel();
resetPasswordViewModel.ResetPasswordData = id;
resetPasswordViewModel.UserName = realUser.UserName;
return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel);
}
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception)
{
}
#endregion
}
#region Check if the user is logged in and fill out fileds for him.
var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager");
if (sessionManager != null)
{
var clientId = sessionManager.AppUser.ClientId;
if (clientId != null)
{
model.Email = sessionManager.AppUser.EmailID;
model.UserName = sessionManager.AppUser.UserName;
model.IsLoggedInUser = true;
}
}
#endregion
return View(model);
}
[HttpPost]
[AllowAnonymous]
public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection)
{
if (ModelState.IsValid)
{
try
{
#region Check user input
var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName);
var areErrors = false;
if (user == null)
{
ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist);
areErrors = true;
}
if (user.EmailID != model.Email)
{
ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong);
areErrors = true;
}
if (areErrors)
return View(model);
#endregion
#region Send Email and inform user
try
{
var forgotPasswordEvent = new ForgotPasswordEvent();
var resetPasswordEmailUserState = new ResetPasswordEmailUserState();
resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid();
resetPasswordEmailUserState.UserId = Guid.Parse(user.Id);
resetPasswordEmailUserState.Created = DateTime.Now;
forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId;
forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId;
forgotPasswordEvent.IsSent = false;
forgotPasswordEvent.Created = resetPasswordEmailUserState.Created;
var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(),
resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString());
forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash);
AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent);
AppModel.SaveChanges();
var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
// Set the MailerModel properties that will be passed to the MvcMailer object.
var m = new MailerModel();
m.UserName = user.UserName;
m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash);
m.FromEmail = smtp.From;
m.Subject = AppConfiguration.ResetEmailSubject;
m.ToEmail = model.Email;
var client = new SmtpClientWrapper();
client.SendCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
// Handle Error
}
else
{
try
{
var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId);
if (forgotPasswordEventsToUpdate != null)
{
forgotPasswordEventsToUpdate.IsSent = true;
AppModel.SaveChanges();
}
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
};
Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client);
model.IsResetEMailSent = true;
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
#endregion
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
return View(model);
}

As your code looks ltl messed up with more than one responsibility.
For Starter what you can do here is:
Refactor your code into small code snippets and move those dependencies into another classes.
when you will be done with first step you will be able to mock those classes using MOQ or NMock or another framework.
Let me know if you have any doubt in above points.

Related

Xamarin google Native Ads IOS

I am trying to implement Native ads in xamarin it works fine with android but I have a problem with ios
Here is my code
public class AdMobNativeAdRenderer : ViewRenderer<Controls.NativeAdView, UnifiedNativeAdView>, IAdLoaderDelegate, IUnifiedNativeAdDelegate, IUnifiedNativeAdLoaderDelegate, IVideoControllerDelegate
{
public UnifiedNativeAdView nativeAdView = null;
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, UnifiedNativeAd nativeAd)
{
// A unified native ad has loaded, and can be displayed.
nativeAd.Delegate = this;
// The headline and mediaContent are guaranteed to be present in every native ad.
nativeAdView.NativeAd = nativeAd;
if (nativeAdView.HeadlineView==null)
{
nativeAdView.HeadlineView= new UILabel();
}
(nativeAdView.HeadlineView as UILabel).Text = nativeAd.Headline;
if (nativeAdView.MediaView == null) {
nativeAdView.MediaView = new MediaView();
}
if (nativeAdView.MediaView.MediaContent == null)
{
nativeAdView.MediaView.MediaContent = new MediaContent();
}
nativeAdView.MediaView.MediaContent = nativeAd.MediaContent;
nativeAdView.MediaView.ContentMode = UIViewContentMode.ScaleAspectFill;
if (nativeAdView.BodyView==null)
{
nativeAdView.BodyView = new UILabel();
}
(nativeAdView.BodyView as UILabel).Text = nativeAd.Body;
nativeAdView.BodyView.Hidden = nativeAd.Body == null;
if (nativeAdView.CallToActionView==null)
{
nativeAdView.CallToActionView = new UIButton();
}
(nativeAdView.CallToActionView as UIButton).SetTitle(nativeAd.CallToAction,UIControlState.Normal);
nativeAdView.CallToActionView.Hidden = nativeAd.CallToAction == null;
if (nativeAdView.IconView==null)
{
nativeAdView.IconView = new UIImageView();
}
(nativeAdView.IconView as UIImageView).Image = nativeAd.Icon.Image;
nativeAdView.IconView.Hidden = nativeAd.Icon == null;
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
nativeAdView.StoreView.Hidden = nativeAd.Store == null;
if (nativeAdView.PriceView==null)
{
nativeAdView.PriceView = new UILabel();
}
(nativeAdView.PriceView as UILabel).Text = nativeAd.Price;
nativeAdView.PriceView.Hidden = nativeAd.Price == null;
if (nativeAdView.AdvertiserView==null)
{
nativeAdView.AdvertiserView = new UILabel();
}
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
(nativeAdView.AdvertiserView as UILabel).Text = nativeAd.Advertiser;
nativeAdView.AdvertiserView.Hidden = nativeAd.Advertiser == null;
nativeAdView.CallToActionView.UserInteractionEnabled = false;
nativeAdView.NativeAd = nativeAd;
try
{
nativeAdView.BackgroundColor = UIColor.Green;
SetNativeControl(nativeAdView);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
[Export("adLoaderDidFinishLoading:")]
void DidFinishLoading(AdLoader adLoader)
{
// The adLoader has finished loading ads, and a new request can be sent.
}
public void DidFailToReceiveAd(AdLoader adLoader, RequestError error)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Controls.NativeAdView> e)
{
base.OnElementChanged(e);
try
{
if (e.OldElement != null)
{
try
{
e.OldElement.Content=null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
if (e.NewElement != null)
{
if (Control == null)
{
// Instantiate the native control and assign it to the Control property with
CreateAdView();
try
{
e.NewElement.Content = null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
AdLoader adLoader;
private void CreateAdView()
{
//if (Element == null) return;
var multipleAdsOptions = new MultipleAdsAdLoaderOptions { NumberOfAds = 1 };
adLoader = new AdLoader("ca-app-pub-3940256099942544/3986624511", GetVisibleViewController(), new[] { AdLoaderType.UnifiedNative }, new[] { multipleAdsOptions })
{
Delegate = this
};
var request = Request.GetDefaultRequest();
request.TestDevices = new string[] { Request.SimulatorId };
if (nativeAdView == null)
{
nativeAdView = new UnifiedNativeAdView();
};
try
{
adLoader.LoadRequest(request);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
Debug.WriteLine("Loading: " + adLoader.IsLoading);
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
Every thing is working as anticipated and I receive the ad and the event DidReceiveUnifiedNativeAd fires but I get an empty ad although when I debug the code I see that the content of the ad is not empty and the control color is green so the control is loaded but why it doesn't show the ad content
Please can anyone help is solving this

Deadlock in Xamarin.Forms

I've got a problem with my Xamarin App. The App uses a custom API to my website. I have not much experience in async/await methods.
The following code shows the App.xaml.cs:
public partial class App : Application
{
public static bool IsUserLoggedIn { get; set; }
public static UserModel currentLoggedInUser { get; set; }
public static List<ActionTypeModel> listTypes;
public static List<ActionSubTypeModel> listSubtypes;
public static List<UserModel> listFriends;
public static List<List<ActionModel>> listActiveActions;
public static List<ActionModel> listLastAction;
public App()
{
this.InitializeComponent();
APIHelper.InitializeClient();
StartApp().Wait();
}
private async Task StartApp()
{
//// DEBUG
//MyAccountStorage.Logout();
string username = await MyAccountStorage.GetUsername().ConfigureAwait(false);
string password = await MyAccountStorage.GetPassword().ConfigureAwait(false);
string user_id = await MyAccountStorage.GetId().ConfigureAwait(false);
if (username != null && password != null)
{
currentLoggedInUser = new UserModel();
if (user_id != null)
currentLoggedInUser.user_id = Convert.ToInt32(user_id);
currentLoggedInUser.username = username;
currentLoggedInUser.password = password;
bool isValid = false;
isValid = await AreCredentialsCorrect(0, currentLoggedInUser.username, currentLoggedInUser.password).ConfigureAwait(false);
if (isValid)
{
IsUserLoggedIn = true;
await FillLists().ConfigureAwait(false);
MainPage = new NavigationPage(await MyPage.BuildMyPage().ConfigureAwait(false));
}
else
{
IsUserLoggedIn = false;
MainPage = new NavigationPage(await LoginPage.BuildLoginPage().ConfigureAwait(false));
}
}
else
{
IsUserLoggedIn = false;
MainPage = new NavigationPage(await LoginPage.BuildLoginPage().ConfigureAwait(false));
}
}
private async Task FillLists()
{
listFriends = await DataControl.GetFriends(App.currentLoggedInUser.user_id, App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listFriends == null)
listFriends = new List<UserModel>();
listTypes = await DataControl.GetTypes(App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listTypes == null)
listTypes = new List<ActionTypeModel>();
listActiveActions = new List<List<ActionModel>>();
for (int i = 0; i < listTypes.Count; i++)
listActiveActions.Add(await DataControl.GetActiveActions(listTypes[i].action_type_id, currentLoggedInUser.user_id, currentLoggedInUser.username, currentLoggedInUser.password).ConfigureAwait(false));
listSubtypes = await DataControl.GetSubtypes(App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listSubtypes == null)
listSubtypes = new List<ActionSubTypeModel>();
listLastAction = await DataControl.GetLastAction(App.currentLoggedInUser.user_id, App.currentLoggedInUser.username, App.currentLoggedInUser.password).ConfigureAwait(false);
if (listLastAction == null)
listLastAction = new List<ActionModel>();
}
public static async Task<bool> AreCredentialsCorrect(int type, string user, string pass, string nick = "", string email = "")
{
List<UserModel> listUsers;
if (type == 1)
listUsers = await DataControl.CheckCredentials(1, user, pass, nick, email).ConfigureAwait(false);
else
listUsers = await DataControl.CheckCredentials(0, user, pass).ConfigureAwait(false);
if (listUsers != null)
if (listUsers.Any())
{
currentLoggedInUser = listUsers.First();
currentLoggedInUser.password = pass;
return true;
}
return false;
}
}
I have the API in DataControl.cs:
public static async Task<List<UserModel>> CheckCredentials(int type, string username, string pass, string email = "", string nickname = "")
{
string password = APIHelper.GetHashSha256(pass);
string url = string.Empty;
if (type == 0)
url = APIHelper.ApiClient.BaseAddress + "/account/login.php?username=" + username + "&password=" + password;
if (type == 1)
{
string nick = string.Empty;
if (string.IsNullOrEmpty(nickname) == false)
nick = "&nickname=" + nickname;
url = APIHelper.ApiClient.BaseAddress + "/account/signup.php?username=" + username + "&password=" + password + "&email=" + email + nick;
}
if (string.IsNullOrEmpty(url))
return null;
using (HttpResponseMessage response = await APIHelper.ApiClient.GetAsync(url).ConfigureAwait(false))
{
if (response.IsSuccessStatusCode)
{
List<UserModel> listUsers = JsonConvert.DeserializeObject<List<UserModel>>(await response.Content.ReadAsStringAsync().ConfigureAwait(false));
return listUsers;
}
else
return null;
}
}
That's one of the different async methods. When I leave out the ConfigureAwait(false), I run into a deadlock. When I add it to the code I run into an error.
Could you please help me.
As #GSerg already wrote, you have to restructure the code. The App constructor must set the MainPage to some page. That one can be empty saying something like "Loading data".
Then you can start a background Task which retrieves the data you need.
When the data has been loaded, then you can update your page with the newly loaded data. But UI updates always have to happen on the UI thread. This is the same on all platforms. So you have to switch back with Device.BeginInvokeOnMainThread(...).
public App()
{
InitializeComponent();
APIHelper.InitializeClient();
MainPage = new LoadingPage();
// start a background thread
Task.Run(async () =>
{
try
{
await StartApp(); // load the data
// go back to the main thread
Device.BeginInvokeOnMainThread(() =>
{
// replace the MainPage with one which shows the loaded data
MainPage = new DataPage();
});
}
catch (Exception ex)
{
// handle the exception
}
});
}
You can use Task.Run(
//call your async method here
);
So in your case:
Task.Run(Startup);

EF Core Insert Identity Issues

I'm using EF Core 2.2.4 and I'm trying to insert datas through an asp.net MVC page.
Here's my repository insert command:
public int InsertFatorMarkup(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
{
using (var transaction = _GFazContext.Database.BeginTransaction())
{
try
{
var preFamFatId = EtapaInsertFator(empId, gmPreFamFatMkp, usuId);
transaction.Commit();
return preFamFatId;
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
//Fernando Milanez 28/11/2019
private int EtapaInsertFator(int empId, GmPreFamFatMkp gmPreFamFatMkp, int usuId)
{
gmPreFamFatMkp = RecargaDeDependenciasFator(empId, gmPreFamFatMkp);
gmPreFamFatMkp.PreFamFatId = NextFatorMkpId(gmPreFamFatMkp.PreId, empId);
gmPreFamFatMkp.RegrasNegocio(usuId);
_GFazContext.GmPreFamFatMkp.Add(gmPreFamFatMkp);
_GFazContext.SaveChanges();
return gmPreFamFatMkp.PreFamFatId;
}
//Fernando Milanez 28/11/2019
private GmPreFamFatMkp RecargaDeDependenciasFator(int empId, GmPreFamFatMkp gmPreFamFatMkp)
{
gmPreFamFatMkp.GmPreTab = GetById(empId, gmPreFamFatMkp.PreId);
//gmPreFamFatMkp.GmPreTab = _GFazContext.GmPreTab
// .FirstOrDefault(r => r.EmpId == empId && r.PreId == gmPreFamFatMkp.PreId);
return gmPreFamFatMkp;
}
//Fernando Milanez 28/11/2019
private short NextFatorMkpId(int preId, int empId)
{
var max = _GFazContext.GmPreFamFatMkp
.Where(r => r.PreId == preId)
.Select(r => (int)r.PreFamFatId)
.DefaultIfEmpty(0)
.Max();
return Convert.ToInt16(max + 1);
}
Here's my controller Get and Post methods:
[HttpGet]
public IActionResult FamiliaMarkupInsert(int preId)
{
ViewBag.returnUrl = Request.Headers["Referer"].ToString();
var model = new PreFamFatMkpModel();
model.Form = new GmPreFamFatMkp() { PreId = preId };
model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, preId, false);
model.FamiliaModel = new FamiliaModel();
GetDataCombo(ref model);
return View(model);
}
//Fernando Milanez 29/11/2019
[HttpPost]
public IActionResult FamiliaMarkupInsert(PreFamFatMkpModel model)
{
ViewBag.returnUrl = Request.Headers["Referer"].ToString();
if (ModelState.IsValid)
{
try
{
int newPreFamFatId = _gmPreTabRepositorio.InsertFatorMarkup(_empId, model.Form, _usuId);
return RedirectToAction("TabelaPrecoTabs", new { id = model.Form.PreId, tabName= "Markup Por Família" });
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
if (ex.InnerException != null) ModelState.AddModelError("", ex.InnerException.Message);
}
}
GetDataCombo(ref model);
model.Form.GmPreTab = _gmPreTabRepositorio.GetById(_empId, model.Form.PreId);
return View(model);
}
Here's my configuration class:
public class GmPreFamFatMkpConfigurations : IEntityTypeConfiguration<GmPreFamFatMkp>
{
public void Configure(EntityTypeBuilder<GmPreFamFatMkp> builder)
{
builder.HasKey(r => new { r.PreFamFatId });
builder.Property(r => r.PreFamFatId).UseSqlServerIdentityColumn();
//Monta Relacionamento 1-N - Colocar somente as dependencias, nesse caso depende da tabela de preço e do produto
builder.HasOne(prepro => prepro.GmPreTab).WithMany(pretab => pretab.GmPreFamFatMkps).HasForeignKey(prepro => prepro.PreId);
builder.HasOne(prefamfatmkp => prefamfatmkp.GmPreTab).WithMany(famtab => famtab.GmPreFamFatMkps).HasForeignKey(prefamfatmkp => prefamfatmkp.PreId);
}
}
And finally, heres my error:
Unable to enter an explicit value for the identity column in table 'GmPreFamFatMkp' when IDENTITY_INSERT is set to OFF.
The error is pretty self explanatory. You've provided a value for the column 'GmPreFamFatMkp' and it is an Identity column (guessing auto-increment) and "Identity_Insert" is off. You probably want to leave it that way. You can't provide a value for this column. Give it null or zero value and let EF and the database figure out the correct value.

Converting Query Expression into Linq C#

I'm having trouble converting a Query Expression found here: http://www.oak3.org/crm/workflow-activity-checking-duplicate-instances/
into a linq query. To put it simply, the goal is if two workflows get triggered at the same time, only let one go through sorted by most recent. Currently my linq version will sometimes cancel a workflow even if it is the only one running. I know I need to utilize the input parameter somehow (to tell it what workflow to compare to), and I'm sure there could be more issues. Any help is greatly appreciated.
[Input("Current workflow")]
[ReferenceTarget("workflow")]
public InArgument<EntityReference> workflowReferenceInput { get; set; }
[Output("Is first workflow")]
public OutArgument<Boolean> isFirstWorkflow { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
ITracingService tracer = executionContext.GetExtension<ITracingService>();
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
try
{
Entity entity = (Entity)context.InputParameters["Target"];
isFirstWorkflow.Set(executionContext, false);
var wfReference = workflowReferenceInput.Get(executionContext);
var wfEntity = service.Retrieve("workflow", wfReference.Id, new ColumnSet ( "name" ));
ConditionExpression ce1 = new ConditionExpression();
ce1.AttributeName = "statuscode";
ce1.Operator = ConditionOperator.In;
ce1.Values.Add(0);
ce1.Values.Add(10);
ce1.Values.Add(20);
ce1.Values.Add(21);
ce1.Values.Add(22);
FilterExpression fe1 = new FilterExpression();
fe1.Conditions.Add(ce1);
QueryExpression qe = new QueryExpression();
qe.EntityName = AsyncOperation.EntityLogicalName;
qe.ColumnSet = new ColumnSet();
qe.Criteria = new FilterExpression();
qe.Criteria.AddFilter(fe1);
var childFilter = qe.Criteria.AddFilter(LogicalOperator.And);
childFilter.AddCondition("operationtype", ConditionOperator.Equal, 10);
childFilter.AddCondition("name", ConditionOperator.Equal, wfEntity["name"]);
LinkEntity link = new LinkEntity
{
LinkFromEntityName = AsyncOperation.EntityLogicalName,
LinkToEntityName = Quote.EntityLogicalName,
LinkFromAttributeName = "regardingobjectid",
LinkToAttributeName = "quoteid"
};
link.LinkCriteria.AddCondition("quoteid", ConditionOperator.Equal, context.PrimaryEntityId.ToString());
DataCollection<Entity> result = service.RetrieveMultiple(qe).Entities;
var list = result.ToList().OrderBy(c => c.Id);
for (var i = 0; i < list.Count(); i++)
{
var item = list.ElementAt(i);
if(item.Id == context.OperationId && i == 0)
{
isFirstWorkflow.Set(executionContext, true);
}
}
}
catch (Exception e)
{
throw new InvalidPluginExecutionException(e.Message);
}
}
into this:
public class WorkflowChecker: CodeActivity
{
[Input("Current workflow")]
[ReferenceTarget("workflow")]
public InArgument<EntityReference> workflowReferenceInput { get; set; }
[Output("Is first workflow")] public OutArgument<Boolean> isFirstWorkflow { get; set; }
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
try
{
var ok = WorkflowChecker(context.PrimaryEntityId, context.OperationId);
isFirstWorkflow.Set(executionContext, ok);
}
catch (Exception e)
{
throw new InvalidPluginExecutionException(e.Message);
}
}
}
which calls:
public static bool WorkflowChecker(Guid workflowContextId,
Guid asyncOperationId)
{
var someReturnValue = false;
var listOfWorkflowIds = new List<Guid>();
try
{
var query = from async in AsyncOperationSet
join b in BSet on async.RegardingObjectId.Id equals b.Id
where b.Id.Equals(workflowContextId)
&& (async.StateCode.Equals(0)
|| async.StateCode.Equals(1)
|| async.StateCode.Equals(2))
select new {async.AsyncOperationId};
foreach (var x in query)
{
if (x.AsyncOperationId != Guid.Empty)
{
listOfWorkflowIds.Add(x.AsyncOperationId.Value);
}
}
listOfWorkflowIds.Sort();
if (listOfWorkflowIds.First() == asyncOperationId)
{
someReturnValue = true;
}
}
catch (Exception e)
{
Console.WriteLine("Error in Workflow Checker: " + e);
}
return someReturnValue;
}
I've added the following lines to the workflow library then passed the parameter into the call to compare by name and so far it appears to be working successfully:
var wfReference = workflowReferenceInput.Get(executionContext);
var wfEntity = service.Retrieve("workflow", wfReference.Id, new ColumnSet("name"));
var test = wfEntity["name"];

capturing value of parameter

I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}

Categories

Resources