I am new to Nunit and Moq framework and am totally stuck in testing for one of my controller as it fetches some of the values from Request.Form["Something"]. I am able to test for the other part of the controller method using nunit but the code is breaking wherever Request.form values are fetched in the same controller.
Below is the test controller code using nunit and Moq:
[Test]
public void SaveRequest()
{
TestController test = new TestController();
TestModel model = new TestModel();
model = PopulateRequestModel();
Mail = model.Mail;
HttpContext.Current = new HttpContext(new HttpRequest("", "https://localhost", ""), new HttpResponse(new System.IO.StringWriter()));
System.Web.SessionState.SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, new HttpSessionStateContainer("", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 20000, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false));
System.Web.HttpContext.Current.Session["__RequestVerificationTokenError"] = false;
var httpContext1 = (new Mock<HttpContextBase>());
var routeData = new RouteData();
httpContext1.Setup(c => c.Request.RequestContext.RouteData).Returns(routeData);
httpContext1.Setup(c => c.Request.Form).Returns(delegate()
{
var nv = new NameValueCollection();
nv.Add("Firstname", "Dave");
nv.Add("LastName", "Smith");
nv.Add("Email", "jsmith#host.com");
nv.Add("Comments", "Comments are here...");
nv.Add("ReceiveUpdates", "true");
return nv;
});
if (LoggedInEnterpriseId != null)
{
ViewResult result = test.SaveRequest(model, mail) as ViewResult;
Assert.IsNotNull(result);
}
}
PopulateRequestModel :
private RequestModel PopulateRequestModel ()
{
RequestModel model = new RequestModel ();
model.Firstname = "Dave";
model.LastName = "Smith";
model.Email = "jsmith#host.com";
model.Comments = "Comments are here...";
model.ReceiveUpdates = true;
return model;
}
Below is the actual controller method to be tested :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveRequest(TestModel model, HttpPostedFileBase Mail)
{
string Name = Request.Form["Firstname"].ToString();
model.Mail = Mail;
//Start Adding Request to DB
Logger.Write("Start: Adding new request..");
try
{
using (db = new DatabaseContext())
{
NewRequest newRequest = new NewRequest();
if (RequestNumber != 0)
{
newRequest.Name = Convert.ToInt16(Request.Form["Firstname"]);
newRequest.LastName = Request.Form["LastName"];
newRequest.Email = Request.Form["Email"];
newRequest.Comments = Request.Form["Comments"];
newRequest.ReceiveUpdates = Convert.ToBoolean(Request.Form["ReceiveUpdates"]);
}
else
{
newRequest.Name = model.Firstname;
newRequest.LastName = model.LastName;
newRequest.Email = model.Email;
newRequest.Comments = model.Comments;
newRequest.ReceiveUpdates = model.ReceiveUpdates;
}
db.NewRequests.Add(newRequest);
int save = db.SaveChanges();
}
The code is getting blocked wherever request.form is used.
I have an entry field at the bottom of the screen in one of my projects. However, on iOS, when you click the entry field, the keyboard is displayed over top the entry field and obscures the vision of it. Therefore, people can't see what they're typing.
How can I solve this problem? Is there a way that I can move the entry field so it is displayed above the keyboard when in focus?
//NOTE: the entry field that needs to be moved is userEntry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using CloudClubv1._2_;
using Backend;
using Xamarin.Forms;
using System.Collections.ObjectModel;
namespace FrontEnd
{
public class ClubChatPage : ContentPage
{
public static ObservableCollection<FrontComment> CurrentCommentsList;
ObservableCollection<FrontComment> commentsList;
ColorHandler ch;
Entry userEntry;
ParentFrontClub club;
bool isMember;
Image bBack, bSettings;
public static ListView listView;
TapGestureRecognizer settingsTgr, backButtonTgr;
public ClubChatPage(ParentFrontClub club, List<DBItem> chatList, List<Account> commentUsers, List<Account> requestUsersList, bool isMember)
{
this.isMember = isMember;
settingsTgr = new TapGestureRecognizer();
settingsTgr.Tapped += SettingsTgr_Tapped;
backButtonTgr = new TapGestureRecognizer();
backButtonTgr.Tapped += BackButtonTgr_Tapped;
this.club = club;
ch = new ColorHandler();
this.BackgroundColor = Color.Black;
this.Title = club.Title;
NavigationPage.SetHasNavigationBar(this, false);
this.commentsList = new ObservableCollection<FrontComment>();
int clubRequestCount = 0;
System.Diagnostics.Debug.WriteLine(chatList.Count.ToString());
chatList.Reverse();
for (int i = 0; i < chatList.Count; i++)
{
if (chatList[i].GetType() == typeof(Comment))
{
if (commentUsers[i] != null)
{
this.commentsList.Add(new FrontComment((Comment)chatList[i], commentUsers[i - clubRequestCount]));
}
}
else if (chatList[i].GetType() == typeof(ClubRequest))
{
this.commentsList.Add(new FrontComment((ClubRequest)chatList[i], requestUsersList[clubRequestCount], this.isMember));
clubRequestCount++;
}
}
CurrentCommentsList = this.commentsList;
updatePage();
}
private void updatePage()
{
bBack = new Image
{
Source = FileImageSource.FromFile("arrow_back.png"),
WidthRequest=30,
// Scale = ,
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 30,
Aspect = Aspect.AspectFill
};
bBack.GestureRecognizers.Add(backButtonTgr);
var actionBarLabel = new Label
{
Text = this.club.Title,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
TextColor = ch.fromStringToColor("white"),
FontSize = 22,
FontAttributes = FontAttributes.Bold
};
bSettings = new Image
{
Source = ImageSource.FromFile("settings.png"),
Scale = .8,
HorizontalOptions = LayoutOptions.EndAndExpand,
VerticalOptions = LayoutOptions.Center
};
bSettings.GestureRecognizers.Add(settingsTgr);
var actionBarLayout = new StackLayout
{
Children =
{
bBack,
actionBarLabel,
bSettings
},
HeightRequest= 30,
Orientation = StackOrientation.Horizontal,
BackgroundColor = ch.fromStringToColor(this.club.clubColor),
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(10,10,0,10)
};
listView = new ListView
{
ItemsSource = CurrentCommentsList,
ItemTemplate = new DataTemplate(typeof(CommentViewCell)),
HasUnevenRows = true,
SeparatorVisibility = SeparatorVisibility.None,
SeparatorColor = ch.fromStringToColor("white"),
BackgroundColor = ch.fromStringToColor("white")
};
if (CurrentCommentsList.Count != 0) {
listView.ScrollTo (CurrentCommentsList [CurrentCommentsList.Count () - 1], ScrollToPosition.End, false);
}
listView.ItemTapped += ListView_ItemTapped;
MessagingCenter.Subscribe<CommentViewCell, FrontComment>(this, "hi", async (sender, args) =>
{
var comment = (FrontComment)args;
var answer = await DisplayAlert("Report User", "Do you really want to report " + comment.AuthorUsername + "?", "Yes", "No");
if (answer)
{
await App.dbWrapper.CreateBan(comment.AuthorId, comment.Id, App.dbWrapper.GetUser().Id);
comment.ShowReport = false;
comment.UpdateProperty("ShowReport");
}
else
{
}
//updatePage();
});
userEntry = new Entry
{
BackgroundColor = ch.fromStringToColor("white"),
TextColor = ch.fromStringToColor("black"),
VerticalOptions = LayoutOptions.End,
IsEnabled = isMember,
Placeholder = "Tap to chat"
};
userEntry.Completed += UserEntry_Completed;
userEntry.Focused += UserEntry_Focused;
Label lEmptyChat = new Label
{
Text = "There are no messages. Type below!",
FontSize = 38,
TextColor = ch.fromStringToColor("black"),
XAlign = TextAlignment.Center,
YAlign = TextAlignment.Center,
VerticalOptions = LayoutOptions.FillAndExpand
};
if (CurrentCommentsList.Count != 0)
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
listView,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
else
{
Content = new StackLayout
{
Children =
{
actionBarLayout,
lEmptyChat,
userEntry
},
BackgroundColor = ch.fromStringToColor("lightGray"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
}
private void UserEntry_Focused(object sender, FocusEventArgs e)
{
}
private void ListView_ItemTapped(object sender, ItemTappedEventArgs e)
{
var item = (FrontComment)e.Item;
for(int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].ShowReport==true)
{
CurrentCommentsList[i].ShowReport = false;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
for (int i = 0; i < CurrentCommentsList.Count; i++)
{
if (CurrentCommentsList[i].Id == item.Id && CurrentCommentsList[i].ClubRequestBool == false)
{
CurrentCommentsList[i].ShowReport = true;
CurrentCommentsList[i].UpdateProperty("ShowReport");
}
}
// updatePage();
}
private async void UserEntry_Completed(object sender, EventArgs e)
{
if (userEntry.Text != "")
{
// var joinClub = await App.dbWrapper.JoinClub(club.Id);
var commentOutput = await App.dbWrapper.CreateComment(userEntry.Text, club.Id);
//System.Diagnostics.Debug.WriteLine("OUTPUT: "+joinClub);
userEntry.Text = "";
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
// updatePage();
}
}
private async void BackButtonTgr_Tapped(object sender, EventArgs e)
{
await App.dbWrapper.RemoveCurrentClubId();
var btn = sender as Image;
btn.IsEnabled = false;
await Navigation.PopAsync();
btn.IsEnabled = true;
}
private async void SettingsTgr_Tapped(object sender, EventArgs e)
{
//var btn = sender as TapGestureRecognizer;
//btn.Tapped -= SettingsTgr_Tapped;
// bSettings.GestureRecognizers.Remove(settingsTgr);
var tagsList = await App.dbWrapper.GetTags(club.Id);
var usersList = await App.dbWrapper.GetClubMembers(club.Id);
var frontClubMemberList = new List<FrontClubMember>();
var isMember = await App.dbWrapper.IsMember(club.Id);
var founderAccount = await App.dbWrapper.GetAccount(club.founderId);
var prevRating = await App.dbWrapper.GetUserRating(club.Id);
var myFriendRequests = await App.dbWrapper.GetFriendRequests();
for (int i = 0; i < usersList.Count; i++)
{
var storedFriendship = await App.dbWrapper.GetFriendship(usersList[i].Id);
if(storedFriendship == 1) //Indicates request was sent from either user
{
// var accReq = App.dbWrapper.GetAccountFriendRequests(usersList[i].Id);
storedFriendship = 3;
var accReq = new List<FriendRequest>();
for (int j = 0; j < myFriendRequests.Count; j++)
{
if (myFriendRequests[j].AuthorId == usersList[i].Id)
{
storedFriendship = 1;//indicates request was sent by other acc
}
}
}
if (usersList[i].Id == App.dbWrapper.GetUser().Id) storedFriendship= 4;
frontClubMemberList.Add(new FrontClubMember(usersList[i], storedFriendship));
}
var btn = sender as Image;
btn.GestureRecognizers.Remove(settingsTgr);
btn.InputTransparent = true;
await Navigation.PushAsync(new ChatInfoPage(tagsList, club, frontClubMemberList, isMember, founderAccount.Username, prevRating));
btn.GestureRecognizers.Add(settingsTgr);
btn.InputTransparent = false;
}
//used by backend push notifications to scroll to new comments
public static void ScrollToCurrent(){
listView.ScrollTo(CurrentCommentsList[CurrentCommentsList.Count() - 1], ScrollToPosition.End, false);
}
}
}
Simply wrap the content in a ScrollView - this will allow the Entry fields to be moved when the Keyboard appears.
I encountered a problem with popup control inside modal edit form of the gridview.
the problem is: popup control won't hide when i click on modal form context area! it just reordered.
please see attached movie first then read the code.
thanks.
here is my code:
MODEL:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public int Avg { get; set; }
}
CONTROLLER:
public class HomeController : Controller
{
public ActionResult Index()
{
Session["Students"] = new List<Student>()
{
new Student { Id = 1, Name = "N1", Family = "f1", Avg = 1 } ,
new Student { Id = 2, Name = "N2", Family = "f2", Avg = 2 } ,
new Student { Id = 3, Name = "N3", Family = "f3", Avg = 3 } ,
new Student { Id = 4, Name = "N4", Family = "f4", Avg = 4 } ,
};
return View(Session["Students"]);
}
public ActionResult PartialGridView(Student student)
{
return PartialView("Index", Session["Students"]);
}
}
View
#model List<Test.Models.Student>
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GvStudent";
settings.KeyFieldName = "Id";
settings.CallbackRouteValues = new { Controller = "Home", Action = "PartialGridView" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddStudentPartialGridView" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateStudentPartialGridView" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteStudentPartialGridView" };
settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm;
settings.SettingsPopup.EditForm.Modal = true;
settings.SettingsPopup.EditForm.HorizontalAlign = PopupHorizontalAlign.WindowCenter;
settings.SettingsPopup.EditForm.VerticalAlign = PopupVerticalAlign.WindowCenter;
settings.SettingsPopup.EditForm.Width = 400;
settings.SettingsPopup.EditForm.Height = 200;
settings.SettingsText.PopupEditFormCaption = "Student";
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.Columns.Add(Name =>
{
Name.FieldName = "Name";
});
settings.Columns.Add(Family =>
{
Family.FieldName = "Family";
});
settings.Columns.Add(Avg =>
{
Avg.FieldName = "Avg";
});
settings.SetEditFormTemplateContent(content =>
{
Html.DevExpress().Button(btnShow =>
{
btnShow.Name="btnShow";
btnShow.ClientSideEvents.Click = "function(s, e){popupControl.ShowAtElement(document.getElementById(s.name));}";
}).Render();
});
}).Bind(Model).GetHtml()
#{
#Html.DevExpress().PopupControl(settings =>
{
settings.Name = "popupControl";
settings.CloseAction = CloseAction.OuterMouseClick;
settings.PopupVerticalAlign = PopupVerticalAlign.Below;
settings.PopupHorizontalAlign = PopupHorizontalAlign.LeftSides;
settings.ShowHeader = false;
settings.ShowFooter = false;
settings.AllowDragging = false;
settings.AutoUpdatePosition = true;
settings.Width = 320;
settings.SetContent(() =>
{
ViewContext.Writer.Write("hello world!");
});
}).GetHtml();
}
I am trying to set the width of a DevExpress grid in percentage but the property is not available for me like it is in every example I see. I am using a MasterDetail grid Devexpress version 12.1
settings.Width = Unit.Percentage(100);
How can I set the width property for the whole grid to 100% and then also how would I set the same property for the colums. Here is my grid
#Html.DevExpress().GridView(
settings => {
settings.Name = "masterGrid";
settings.CallbackRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterAddNewPartial" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterUpdatePartial" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterDeletePartial" };
settings.KeyFieldName = "InwardsGoodsID";
settings.Columns.Add(column =>
{
column.FieldName = "CustomerID";
column.Caption = "Customer";
column.ColumnType = MVCxGridViewColumnType.ComboBox;
var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
comboBoxProperties.DataSource = Model.CustomersList;
comboBoxProperties.TextField = "CustomerName";
comboBoxProperties.ValueField = "CustomerID";
comboBoxProperties.ValueType = typeof(int);
});
settings.Columns.Add(column =>
{
column.FieldName = "CustomerReference";
column.Caption = "Customer Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "TimberShadeReference";
column.Caption = "TimberShade Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "DateReceived";
column.Caption = "Date Received";
column.PropertiesEdit.DisplayFormatString = "d";
});
settings.Columns.Add(column =>
{
column.FieldName = "Comment";
column.Caption = "Comment";
});
settings.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
settings.SettingsDetail.ShowDetailRow = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.SetDetailRowTemplateContent(c =>
{
Html.RenderAction("GridViewDetailPartial", new { inwardsgoodsID = DataBinder.Eval(c.DataItem, "InwardsGoodsID") });
});
//TO OPEN THE FIRST EDITABLE ROW
//settings.PreRender = (sender, e) =>
//{
// ((MVCxGridView)sender).DetailRows.ExpandRow(0);
//};
}).Bind(Model.InwardsGoods).GetHtml()
Ok so I found the answer. What I did to solve this was at the top of the cshtml page I added this using statement.
#using System.Web.UI.WebControls;
my code is too long so sorry :)
#model IEnumerable<Osos11.Models.Customers>
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvEditing";
settings.KeyFieldName = "sno";
settings.CallbackRouteValues = new { Controller = "Customer", Action = "EditingPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Columns.Add(column =>
{
column.Caption = "#";
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("Edit", "EditingEdit", new { sno = DataBinder.Eval(c.DataItem, "sno") }) + " " +
Html.ActionLink("Delete", "EditingDelete", new { sno = DataBinder.Eval(c.DataItem, "sno") },
new { onclick = "return confirm('Do you really want to delete this record?')" })
);
});
column.SetHeaderTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("New", "EditingEdit", new { sno = -1 }).ToHtmlString()
);
});
column.Settings.AllowDragDrop = DefaultBoolean.False;
column.Settings.AllowSort = DefaultBoolean.False;
column.Width = 70;
});
settings.Columns.Add("Name");
//settings.Columns.Add(column =>
//{
// column.FieldName = "CategoryID";
// column.Caption = "Category";
// column.ColumnType = MVCxGridViewColumnType.ComboBox;
// var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
// comboBoxProperties.DataSource = NorthwindDataProvider.GetCategories();
// comboBoxProperties.TextField = "CategoryName";
// comboBoxProperties.ValueField = "CategoryID";
// comboBoxProperties.ValueType = typeof(int);
//});
settings.Columns.Add("CustomerNumber");
//settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
//settings.Columns.Add("UnitsInStock");
//settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox);
settings.ClientLayout = (s, e) =>
{
if (e.LayoutMode == ClientLayoutMode.Loading)
{
if (Session["GridState"] != null)
e.LayoutData = (string)Session["GridState"];
}
else
Session["GridState"] = e.LayoutData;
};
settings.PreRender = (s, e) =>
{
if (ViewData["VisibleID"] == null) return;
ASPxGridView grid = (ASPxGridView)s;
grid.MakeRowVisible(ViewData["VisibleID"]);
};
}).Bind(Model).GetHtml()
I got this error
Compiler Error Message: CS1660: Cannot convert lambda expression to type 'DevExpress.Web.Mvc.GridViewSettings' because it is not a delegate type
It seems that this issue is caused by the fact that any expression in the GridView's definition is not valid.
As a result, the entire GridView's definition (lambda expression) cannot be recognized by the View Engine.