SqlDataSource1_Selected not working - sqldatasource

I need to be able to change a Boolean variable if a datasource actually retrieves any data, so gridviews/detailsviews aren't displayed. I've placed all the data inside a PlaceHolder tag which is by default not visible.
But using the SqlDataSource1_Selected method, it doesn't actually change the boolean variable - why is this? Here is my code:
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
if (e.AffectedRows == 0)
{
displayData = false;
}
else
{
displayData = true;
}
}
And this is a snippet from my datasource in ASP to show it is indeed linking to the method:
onselected="SqlDataSource1_Selected"

I think you are going about this the wrong way
Can you try something like this
SqlDataSource DS = new SqlDataSource();
DataView DV = new DataView();
DS.ConnectionString = _Conn_String;
DS.SelectCommand = query_String;
DataView DV = new DataView();
DV = (DataView)DS.Select(DataSourceSelectArguments.Empty);
if (DV != null)
{
//display data
}
else
{
//do not display data
}

Related

EF modify entity in a function

// Inside an action result
tp = dbContext.tp.Single(x => ...);
foreach (Sample sample in tp.samples)
{
if (sample.SampleStatusId == 1)
changeSamplestatus(sample, 2, now); //change samples to on hold
}
dbContext.SaveChanges();
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
sample.SampleHistory.Add(new SampleHistory
{
OldStatus = sample.SampleStatusId,
NewStatus = sampleStatus,
});
sample.SampleStatusId = sampleStatus;
}
I have an entity (sample) that I would like to change it status.
I am calling a function to do so, but the entity doesn't get modified (but it is creating a new row in history table with the correct FK).
It doesn't throw any errors when SaveChanges is called. It just doesn't modify the entity.
You can try:
//INSIDE AN ACTION RESULT
var tp = dbContext.tp.SingleOrDefault(x => ...);
if (tp != null)
{
foreach (Sample sample in tp.samples)
{
if (sample.SampleStatusId == 1)
changeSamplestatus(sample, 2, DateTime.Now);
}
int flag = dbContext.SaveChanges();
if (flag > 0)
{
// update successful
}
}
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
//sample.SampleHistory.Add(new SampleHistory
//{
// OldStatus = sample.SampleStatusId,
// NewStatus = sampleStatus,
//});
sample.SampleStatusId = sampleStatus;
}
Don't use Single for this case, because it would throw exception if no result was found or there were more than 1 result. Use SingleOrDefault or FirstOrDefault instead.
You can try this . I hope thiw will work . The Idea is to get the history records first in the context and then update the propterties and set state to mofifed . Please try I didnt tested it but it should work.
public void changeSamplestatus(Sample sample, int sampleStatus, DateTime now)
{
var historyRecordToUpdate = db.SampleHistory.FirstOrDefault(h=>h.id == sampleHistoryId )
if(historyRecordToUpdate !=null )
{
db.Entry(sample).State= EntityState.Modified;
sample.SampleStatusId = sampleStatus;
}
}

Add text to bound values in Xamarin.forms

My modelView:
public string Status {
get { return _status; }
set {
if (value == _status) {
return;
}
_status = value;
OnPropertyChanged ("Status");
}
My View:
Label labelStatus = new Label {
TextColor = Color.Green,
FontSize = 20d
};
labelStatus.SetBinding (Label.TextProperty, "Status");
Then I want to present the status using something like:
string presentStatus = string.Format("Your status is {0}...", labelStatus);
Label yourStatus = new Label{Text=presentStatus}
But that doesn't really work. Nor does using
string presentStatus = string.Format("Your status is {0}...", SetBinding(Label.TextProperty,"Status"));
So how should I do to add my bound values with more text before presenting them for the user in a view.
If using XAML (which i don't), it seems possible according to: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/data_binding_basics/
Xamarin Forms binding implementation doesn't currently allow complex binding scenarios like embedding bound text within static text.
There are two options
a. use multiple labels - one with the static text, one with the bound text
b. use a property on your ViewModel that concatenates the text for you
public string StatusText
{
get
{
return string.Format("Your status is {0}...", Status);
}
}
public string Status {
get { return _status; }
set {
if (value == _status) {
return;
}
_status = value;
OnPropertyChanged ("Status");
OnPropertyChanged ("StatusText");
}
You can do that in the BindingContextChanged-event:
labelStatus.BindingContextChanged += (sender, e) =>
{
// Here you can change the Text dynamically
// E.G. labelStatus.text = "Title: " + labelStatus.text
};

Xamarin iOS - Navigate to next text field with return key

I couldn't find anything in the Xamarin documentation about navigating to the next text field in a series of text fields on a form, only a small tutorial on removing the keyboard.
To keep things simple I am using a txtUsername(tag 1) text field and a txtPassword(tag 2) text field. When I implement the following code, it isn't transferring to Xamarin Studio. Does anyone know the way this can be done code in Xamarin Studio, or alternatively if I can transfer the code from XCode to Xamarin Studio.
I am using the following code:
- (BOOL)textFieldShouldReturn:(UITextField *)txtUsername{
NSLog(#"textFieldShouldReturn:");
if (txtUsername.tag == 1) {
UITextField *txtPassword= (UITextField *)[self.view viewWithTag:2];
[txtPassword becomeFirstResponder];
}
else {
[txtUsername resignFirstResponder];
}
return YES;
}
Thanks in advance
I think that the simplest way to do this is using the ShouldReturn method on your UITextFields with the BecomeFirstResponder method. For example, for a login form with Username and Password UITextFields, as follows (in your ViewDidLoad method):
Username = new UITextField();
Username.ReturnKeyType = UIReturnKeyType.Next;
Username.KeyboardType = UIKeyboardType.EmailAddress;
Username.ShouldReturn = (tf) =>
{
Password.BecomeFirstResponder();
return true;
};
View.Add(Username);
Password = new UITextField();
Password.SecureTextEntry = true;
Password.ReturnKeyType = UIReturnKeyType.Go;
Password.ShouldReturn = (tf) =>
{
// Do your login
return true;
};
View.Add(Password);
When you click next when the Username is active, it moves to the Password field. Clicking Go in the password field submits the form.
I wrote a generic solution for every form (not only those with 2 fields).
I´ve got a BaseViewController with these methods:
private UITextField[] formTextfields;
protected void EnableNextKeyForTextFields(UITextField[] fields)
{
formTextfields = fields;
foreach (var field in fields)
{
field.ShouldReturn += ShouldReturn;
}
}
private bool ShouldReturn(UITextField textField)
{
int index = Array.IndexOf(formTextfields, textField);
if (index > -1 && index < formTextfields.Length - 1)
{
formTextfields[index + 1].BecomeFirstResponder();
return true;
}
else if (index == formTextfields.Length - 1)
{
formTextfields[index].ResignFirstResponder();
FormFinished();
}
return false;
}
protected virtual void FormFinished()
{
// this should be implemented on viewControllers using "EnableNextKeyForTextFields"
}
Then, in your view implementation, you just need to pass all your textfields in a single array:
EnableNextKeyForTextFields(new UITextField[] { NameField, SurnameField, EmailField, PasswordField });
When the users clicks "return" when editing the last field of the array, the method "FormFinished" will be called, so you can override it in your implementation:
protected override void FormFinished()
{
(ViewModel as RegisterViewModel).Register(); // or whatever you need to do here
}
I hope this is useful for somebody
You could make use of these functions
http://iosapi.xamarin.com/?link=M%3aMonoTouch.UIKit.UIResponder.BecomeFirstResponder
BecomeFirstResponder()
and
http://iosapi.xamarin.com/?link=M%3aMonoTouch.UIKit.UIResponder.ResignFirstResponder
ResignFirstResponder()
According to the documentation you should add the textField Delegate method like this
public virtual bool ShouldReturn (UITextField textField)
{
if (txtUsername.tag == 1) {
UITextField txtPassword = (UITextField)this.view.ViewWithTag(2);
txtPassword.BecomeFirstResponder();
}
else {
txtUsername.ResignFirstResponder();
}
return true;
}
Here's a sample of how to implement in Xamarin.iOS. There may be other simpler ways to do this but I couldn't find any, and this works for me.
I subclassed UITextFieldDelegate to add a custom event handler, then created an instance of it in my view controller code, assigned a lambda expression to the custom event handler so I could access instance variables, and set this delegate instance as the Delegate on my 2 ext fields:
public class LoginTextFieldDelegate : UITextFieldDelegate
{
public EventHandler<UITextField> OnShouldReturn;
public override bool ShouldReturn(UITextField textField)
{
if (OnShouldReturn != null)
{
OnShouldReturn(this, textField);
}
return true;
}
}
Then in my view controller ViewDidLoad method:
var textDelegate = new LoginTextFieldDelegate
{
OnShouldReturn = (sender, textField) =>
{
if (textField.Tag == txtEmailAddress.Tag)
{
txtPassword.BecomeFirstResponder();
}
else if (textField.Tag == txtPassword.Tag)
{
txtPassword.ResignFirstResponder();
}
}
};
txtEmailAddress.Delegate = textDelegate;
txtPassword.Delegate = textDelegate;
Don't forget to set a distinct tag on each UITextField in code / Interface Builder!
Could be easier to use the class available here
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Manage keyboard and tab order
new [] {
usernameField, // Tab order = 0
passwordField, // Tab order = 1
emailField // Tab order = 2
}.InitializeNavigationOnFields();
}
Just call the method passing all the text fields in the order you want them to be navigated through the keyboard.
I recently implemented a solution on a Sign In Screen that handles the question in quite a simple and precise manner.
Not sure if these properties and events existed when the question was first asked but they will help out now for anyone else who needs it.
Entry emailEntry = new Entry()
{
Keyboard = Keyboard.Email,
ReturnType = ReturnType.Next //Changes Return Button on Keyboard to 'Next'
};
emailEntry.Completed += (s, e) => passwordEntry.Focus();
The Completed event fires when the Return Key is pressed. I then set the Focus to my passwordEntry field.
Entry passwordEntry = new Entry()
{
IsPassword = true,
ReturnType = ReturnType.Go //Changes Return Button on Keyboard to 'Next'
};
passwordEntry.Completed += (s, e) => SignInClick(s, e); //SignInClick method handles the sign in functionality
The Completed event for the password entry then initiates the SignInClick method which was previously only handled by a button on the screen.

Monotouch.Dialog Generate from db and retain values

I'm have a settings view where I'm using MT.D to build out my UI. I just got it to read elements from a database to populate the elements in a section.
What I don't know how to do is access each elements properties or values. I want to style the element with a different background color for each item based on it's value in the database. I also want to be able to get the selected value so that I can update it in the db. Here's the rendering of the code that does the UI stuff with MT.D. I can get the values to show up and slide out like their supposed to... but, styling or adding delegates to them to handle clicks I'm lost.
List<StyledStringElement> clientTypes = SettingsController.GetClientTypes ();
public SettingsiPhoneView () : base (new RootElement("Home"), true)
{
Root = new RootElement("Settings") {
new Section ("Types") {
new RootElement ("Types") {
new Section ("Client Types") {
from ct in clientTypes
select (Element) ct
}
},
new StringElement ("Other Types")
}
Here's how I handled it below. Basically you have to create the element in a foreach loop and then populate the delegate with whatever you want to do there. Like so:
public static List<StyledStringElement> GetClientTypesAsElement ()
{
List<ClientType> clientTypes = new List<ClientType> ();
List<StyledStringElement> ctStringElements = new List<StyledStringElement> ();
using (var db = new SQLite.SQLiteConnection(Database.db)) {
var query = db.Table<ClientType> ().Where (ct => ct.IsActive == true && ct.Description != "Default");
foreach (ClientType ct in query)
clientTypes.Add (ct);
}
foreach (ClientType ct in clientTypes) {
// Build RGB values from the hex stored in the db (Hex example : #0E40BF)
UIColor bgColor = UIColor.Clear.FromHexString(ct.Color, 1.0f);
var localRef = ct;
StyledStringElement element = new StyledStringElement(ct.Type, delegate {
ClientTypeView.EditClientTypeView(localRef.Type, localRef.ClientTypeId);
});
element.BackgroundColor = bgColor;
ctStringElements.Add (element);
}
return ctStringElements;
}

Unit testing a controller that depends on a session variable

I have a controller that depends on a Session variable. In order to unit test this controller, I came up with the following solution. It works but I'm wondering if there is a better/cleaner way. Thanks
Controller
public JsonResult UpdateStatus(ImageUpdateStatus imageUpdateStatus, SessionStateItemCollection sessionItems = null)
{
var data = new object();
string status = null;
ImageInfo imageInfo = new ImageInfo();
IImageInfoServices svcImageInfo = new ImageInfoServicesRepository();
imageInfo = svcImageInfo.GetImageByImageId(imageUpdateStatus.ImageId);
IDeviceControlServices svcDevice = new DeviceControlServicesRespository();
IPVSCommandServices svcPVSCmds = new PVSCommandServicesRespository();
if (imageUpdateStatus.Task == "prep")
{
List<UpdateReasonForm> updateReasonForms;
if (sessionItems != null)
{
updateReasonForms = sessionItems["UpdateReasonForms"] as List<UpdateReasonForm>;
}
else
{
updateReasonForms = Session["UpdateReasonForms"] as List<UpdateReasonForm>;
}
foreach (var item in updateReasonForms)
{
if (item.ImageId == imageInfo.ImageId)
{
status = svcPVSCmds.PrepImage(imageInfo, item.NewVersion);
}
}
data = new
{
status
};
}
if (imageUpdateStatus.Task == "boot")
{
status = svcDevice.Boot(imageInfo.ImageId);
data = new
{
status
};
}
return this.Json(data, JsonRequestBehavior.AllowGet);
}
Unit Test
[TestMethod()]
public void UpdateStatusTest()
{
BuildController target = new BuildController(); // TODO: Initialize to an appropriate value
ImageUpdateStatus imageUpdateStatus = new ImageUpdateStatus(); // TODO: Initialize to an appropriate value
imageUpdateStatus.ImageId = 3;
imageUpdateStatus.Task = "prep";
UpdateReasonForm updateReasonForm = new UpdateReasonForm();
updateReasonForm.ImageId = 3;
updateReasonForm.NewVersion = "TestThis";
List<UpdateReasonForm> updateReasonForms = new List<UpdateReasonForm>();
updateReasonForms.Add(updateReasonForm);
var sessionItems = new SessionStateItemCollection();
sessionItems["UpdateReasonForms"] = updateReasonForms;
JsonResult actual;
actual = target.UpdateStatus(imageUpdateStatus, sessionItems);
}
Instead of passing in the session values as a parameter you can mock the session state like here:
How do you mock the session object collection using Moq
You have a dependency on Session. You could move your code into a testable method where you inject the dependency at the method level. It looks like you are on this path I would just abstract the code into its own method allowing you to test the functionality regardless of the whether the data comes from session or not.
public JsonResult UpdateStatusDependencyInjection(ImageUpdateStatus imageUpdateStatus, Dictionary<string, object> sessionValues)
{
var data = new object();
string status = null;
ImageInfo imageInfo = new ImageInfo();
IImageInfoServices svcImageInfo = new ImageInfoServicesRepository();
imageInfo = svcImageInfo.GetImageByImageId(imageUpdateStatus.ImageId);
IDeviceControlServices svcDevice = new DeviceControlServicesRespository();
IPVSCommandServices svcPVSCmds = new PVSCommandServicesRespository();
if (imageUpdateStatus.Task == "prep")
{
List<UpdateReasonForm> updateReasonForms;
if (sessionItems != null)
{
updateReasonForms = sessionItems["UpdateReasonForms"] as List<UpdateReasonForm>;
}
else
{
updateReasonForms = Session["UpdateReasonForms"] as List<UpdateReasonForm>;
}
foreach (var item in updateReasonForms)
{
if (item.ImageId == imageInfo.ImageId)
{
status = svcPVSCmds.PrepImage(imageInfo, item.NewVersion);
}
}
data = new
{
status
};
}
if (imageUpdateStatus.Task == "boot")
{
status = svcDevice.Boot(imageInfo.ImageId);
data = new
{
status
};
}
return this.Json(data, JsonRequestBehavior.AllowGet);
}
http://codingsmith.co.za/a-better-way-of-working-with-httpcontext-session-in-mvc/
This is my implementation of an interface wrapper for Session.
Its currently in production and works fine, its injected into my controllers, but I can use one of the other implementations manually when testing

Resources