Required Validation based on condition - asp.net-mvc-3

public string InsuredName
{
get;
set;
}
public string Card_No
{
get { return this.card_No; }
set { this.card_No = value; }
}
here i have two properites, CardNo will be required only for some InsuredNames.when User types InsuredName then i want to go to database and check wheather it has Card_No validation if yes then i want to validate it as required other wise not, i tried remote validation but it is not working

private string insuredName;
private bool cardNoRequiresValidation;
public string InsuredName
{
get {return insuredName;}
set { cardNoRequiresValidation = DoesCardNoRequiresValidation(Value); insuredName = value;}
}
public string Card_No
{
get { return this.card_No; }
set { cardNoRequiresValidation ? ValidateCardNo(value) : card_No = value; }
}
private bool DoesCardNoRequiresValidation(string insuredName)
{ //if requires validation
// return true;
//else
//return false;
}
private void ValidateCardNo(string cardNo)
{
//execute validation logic
}

Related

Dynamic DataGridViewComboBox Column

I am trying to make a DataGridViewComboBox Column that will accept new data and add it to it's list items.
I am building this for a quoting system I sort of did this another way but I just couldn't get it to function reliably.
I keep getting a System.NullReferenceException on the OnSelectedIndexChanged.
I want to be able to type a value into the the ComboBox cell have it added to the list items in order.
Can someone help me out on this?
#region DataGridViewVariableComboBoxColumn
public class DataGridViewVariableComboBoxColumn : DataGridViewComboBoxColumn
{
[Browsable(true)]
[Category("Behavior")]
[DefaultValue(false)]
public bool AddNewItems { get; set; }
private System.Windows.Forms.AutoCompleteMode comboxAutoCompleteMode;
[Browsable(true)]
[Category("Behavior")]
[DefaultValue(false)]
public System.Windows.Forms.AutoCompleteMode ComboBoxAutoCompleteMode
{
get { return comboxAutoCompleteMode; }
set
{
comboxAutoCompleteMode = value;
}
}
public DataGridViewVariableComboBoxColumn()
{
this.CellTemplate = new DataGridViewVariableComboBoxCell();
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
if (value != null &&
!value.GetType().IsAssignableFrom(typeof(DataGridViewVariableComboBoxCell)))
{
throw new InvalidCastException("Must be a DataGridViewVariableComboBoxCell");
}
base.CellTemplate = value;
}
}
public override object Clone()
{
var c = (DataGridViewVariableComboBoxColumn)base.Clone();
if (c != null)
{
c.AddNewItems = this.AddNewItems;
c.ComboBoxAutoCompleteMode = this.ComboBoxAutoCompleteMode;
c.DisplayStyle = this.DisplayStyle;
c.FlatStyle = this.FlatStyle;
}
return c;
}
}
public class DataGridViewVariableComboBoxCell : DataGridViewComboBoxCell
{
public DataGridViewVariableComboBoxCell() : base()
{
}
public override object Clone()
{
DataGridViewVariableComboBoxCell cell = base.Clone() as DataGridViewVariableComboBoxCell;
return cell;
}
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
try
{
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
DataGridViewVariableComboBoxEditingControl TheControl = (DataGridViewVariableComboBoxEditingControl)DataGridView.EditingControl;
var c = (DataGridViewVariableComboBoxColumn)this.OwningColumn;
TheControl.OwningColumn = this.OwningColumn;
TheControl.AddNewItems = c.AddNewItems;
TheControl.EditingComboBoxAutoCompleteMode = c.ComboBoxAutoCompleteMode;
TheControl.EditingAutoCompleteSource = AutoCompleteSource.ListItems;
TheControl.EditingComboBoxStyle = ComboBoxStyle.DropDown;
if (TheControl != null)
{
TheControl.SelectedIndex = 0;
}
}
catch { }
}
public override Type EditType
{
get
{
return typeof(DataGridViewVariableComboBoxEditingControl);
}
}
public override Type ValueType
{
get
{
// Return the type of the value that DataGridViewVariableComboBoxCell contains.
return typeof(string);
}
}
}
internal class DataGridViewVariableComboBoxEditingControl : DataGridViewComboBoxEditingControl, IDataGridViewEditingControl
{
private DataGridView dataGridViewControl;
private int rowIndex;
private bool valueChanged = false;
public System.Windows.Forms.AutoCompleteMode EditingComboBoxAutoCompleteMode
{
get
{return this.AutoCompleteMode; }
set
{
this.AutoCompleteMode = value;
}
}
public ComboBoxStyle EditingComboBoxStyle
{
get
{ return this.DropDownStyle; }
set
{
this.DropDownStyle = value;
}
}
public AutoCompleteSource EditingAutoCompleteSource
{
get
{ return this.AutoCompleteSource; }
set
{
this.AutoCompleteSource = value;
}
}
public DataGridViewVariableComboBoxEditingControl() : base()
{
}
public bool AddNewItems { get; set; }
public DataGridViewColumn OwningColumn { get; set; }
private string editingControlFormattedValue;
public string EditingControlFormattedValue
{
get
{
return editingControlFormattedValue;
}
set
{
editingControlFormattedValue = value;
}
}
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
{
editingControlFormattedValue = this.Text;
if (this.SelectedIndex == -1 && this.AddNewItems && editingControlFormattedValue != "")
{
List<string> list = new List<string>();
if (this.Items.Count > 0)
{
list = this.Items.Cast<string>()
.Select(x => x)
.ToList();
}
else
{
list = new List<string>();
}
if (!list.Contains(editingControlFormattedValue) && editingControlFormattedValue != "")
{
list.Add(editingControlFormattedValue);
list = list.Distinct().OrderBy(o => o).ToList();
}
((DataGridViewVariableComboBoxColumn)OwningColumn).Items.Clear();
((DataGridViewVariableComboBoxColumn)OwningColumn).Items.AddRange(list.ToArray());
this.Items.Clear();
this.Items.AddRange(list.ToArray());
int index = ((DataGridViewVariableComboBoxColumn)OwningColumn).Items.IndexOf(editingControlFormattedValue);
EditingControlValueChanged = true;
//base.SelectedIndex = index;
//this.Text = text;
// EditingControlDataGridView.NotifyCurrentCellDirty(true);
}
return editingControlFormattedValue;
}
public DataGridView EditingControlDataGridView
{
get
{
return dataGridViewControl;
}
set
{
dataGridViewControl = value;
}
}
public int EditingControlRowIndex
{
get
{
return rowIndex;
}
set
{
rowIndex = value;
}
}
public bool EditingControlWantsInputKey(
Keys key, bool dataGridViewWantsInputKey)
{
// Let the DateTimePicker handle the keys listed.
switch (key & Keys.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Home:
case Keys.End:
case Keys.PageDown:
case Keys.PageUp:
return true;
default:
return false;
}
}
// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit
// method.
public void PrepareEditingControlForEdit(bool selectAll)
{
// No preparation needs to be done.
}
// Implements the IDataGridViewEditingControl
// .RepositionEditingControlOnValueChange property.
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}
// Implements the IDataGridViewEditingControl
// .EditingControlValueChanged property.
public bool EditingControlValueChanged
{
get
{
return valueChanged;
}
set
{
valueChanged = value;
}
}
// Implements the IDataGridViewEditingControl
// .EditingPanelCursor property.
public Cursor EditingPanelCursor
{
get
{
return base.Cursor;
}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedIndexChanged(e);
}
}
protected override void OnSelectedValueChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedValueChanged(e);
}
}
protected override void OnSelectedItemChanged(EventArgs e)
{
if (valueChanged)
{
base.OnSelectedItemChanged(e);
}
}
}
#endregion

How custom remote validation errormessage in mvc 5?

[System.Web.Mvc.Remote("CheckIdCard", "Lockers", ErrorMessage = "This Id Card have been used, Locker id is {0}{1}{2}")]
[MaxLength(18)]
public string IdCard { get;set;}
IF id Card have been exist in database, then client will show this record's id.
which method i should override ???
public class CustomErrMsgRemoteAttribute : System.Web.Mvc.RemoteAttribute, IClientValidatable
{
public override string FormatErrorMessage(string name)
{
return base.FormatErrorMessage(name);
}
//public override
}
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public JsonResult CheckIdCard(string IdCard)
{
bool isValidate = false;
string val=string.empty;
var locker = db.Lockers.Where(l => l.IdCard == IdCard).FirstOrDefault();
if (locker==null)
{
isValidate = true;
}
else
{
string val=locker.Id;
}
// retrun this locker.id in errormessage;
return Json(isValidate, JsonRequestBehavior.AllowGet);
}
I don't know how to write these code, thanks.
Place this in your metadata file or model class
[RemoteAttribute("IsRegionCodeExists", "Region",ErrorMessage="Region Code exists,
public string RegionCode { get; set; }
NOW IN THE CONTROLLER
//
// GET: /Region/
public JsonResult IsRegionCodeExists(string RegionCode)
{
return IsExist(RegionCode) ? Json(true, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
}
public bool IsExist(string RegionCode)
{
var _model = (from s in db.Regions
where s.RegionCode == RegionCode
select s.RegionCode).FirstOrDefault();
if (string.IsNullOrEmpty(RegionCode)) return false;
else if (_model!=null)
return false;
else return true;
}

Setting session variables in a class is setting all of them, not just one

I have been researching a way to set session variables for my Web App to store the logged in user's info. I have made a lot of progress, being a novice, but I am stumped as to why setting the variables will set all of them and not just the one specified. Can someone point out my mistake(s), please? Thank you!!
using System;
using System.DirectoryServices;
using System.Security.Principal;
using System.Web;
using System.Web.UI;
namespace ITHD
{
public class Common : Page
{
public static void GetLoggedInUserProperties()
{
string gLoginId = ExtractUserName(WindowsIdentity.GetCurrent().Name);
SessionManager.LoginId = gLoginId;
VerifyInAD(gLoginId);
}
private static void VerifyInAD(string sUser)
{
try
{
string userName = ExtractUserName(sUser);
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(SAMAccountName={0})", userName);
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("MemberOf");
search.PropertiesToLoad.Add("givenname");
search.PropertiesToLoad.Add("sn");
search.PropertiesToLoad.Add("phone");
search.PropertiesToLoad.Add("title");
SearchResult result = search.FindOne();
//SessionManager.CanEdit = "False";
SessionManager.UserName = string.Empty;
if (result != null)
{
SessionManager.UserName = string.Format("{0}", result.Properties["cn"][0].ToString());
bool admin = checkGroup("Helpdesk Agents");
if (admin == true)
{
SessionManager.HDAgent = "True";
}
}
search.Dispose();
}
catch (Exception ex)
{
SessionManager.UserName = "Guest";
}
}
public static string ExtractUserName(string path)
{
string[] userPath = path.Split(new char[] { '\\' });
return userPath[userPath.Length - 1];
}
public static bool checkGroup(string group)
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(group);
}
}
public static class SessionManager
{
private const string sLoginId = "";
public static string LoginId
{
get
{
if (null != HttpContext.Current.Session[sLoginId])
return HttpContext.Current.Session[sLoginId] as string;
else
return "Guest";
}
set
{
HttpContext.Current.Session[sLoginId] = value;
}
}
private const string sUserName = "";
public static string UserName
{
get
{
if (null != HttpContext.Current.Session[sUserName])
return HttpContext.Current.Session[sUserName] as string;
else
return "Guest";
}
set
{
HttpContext.Current.Session[sUserName] = value;
}
}
private const string sHDAgent = "";
public static string HDAgent
{
get
{
if (null != HttpContext.Current.Session[sHDAgent])
return HttpContext.Current.Session[sHDAgent] as string;
else
return "False";
}
set
{
HttpContext.Current.Session[sHDAgent] = value;
}
}
}
}
I don't think you are setting your session keys correctly. In your static class you have a property setter that is essentially session Session[""]=Some Value for all members. You do not need to set the key to the name of the private member in .net 3.5 you do not even need the private member. You could also just stuff the whole session object in and not worry about each member.
Then just access a Current instantiator of the properties as in
MySession.Current.UserName="guest";
public class MySession
{
private const string _SessionName = "__MY_SESSION__";
//--------------------------------------------------------------------------------------------
private MySession(){}
//--------------------------------------------------------------------------------------------
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session[_SessionName];
if (session == null)
{
session = new MySession();
session.Property1 = new Property1();
session.Property2 = new Property2();
session.UserName = "";
HttpContext.Current.Session[_SessionName] = session;
}
return session;
}
}
public string UserName { get; set; }
public Property1 Property1 { get; set; }
public Property2 Property2 { get; set; }
}

Why am I getting duplicated row inserts?

I have windows phone 7 application and classes for database mapping.
A Poll class looks like that:
[Table]
public class Poll // :BaseModel
{
//private int _pid;
//private string _pdesc;
//private bool _pisopen;
//private string _pname;
//private bool _prandom;
//private string _qlastupdticks;
//private string _ticks;
[Column(DbType = "INT NOT NULL IDENTITY(1,1)", IsPrimaryKey = true, IsDbGenerated = true)]
public int id { get; set; }
[Column(DbType = "INT")]
public int pid { get; set; }
//{
// get { return _pid; }
// set { SetValue(ref _pid, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column]
public string pdesc { get; set; }
//{
// get { return _pdesc; }
// set { SetValue(ref _pdesc, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column]
public bool pisopen { get; set; }
//{
// get { return _pisopen; }
// set { SetValue(ref _pisopen, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column]
public string pname { get; set; }
//{
// get { return _pname; }
// set { SetValue(ref _pname, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column]
public bool prandom { get; set; }
//{
// get { return _prandom; }
// set { SetValue(ref _prandom, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column(DbType = "NVARCHAR(255)")]
public string qlastupdticks { get; set; }
//{
// get { return _qlastupdticks; }
// set { SetValue(ref _qlastupdticks, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
[Column(DbType = "NVARCHAR(255)")]
public string ticks { get; set; }
//{
// get { return _ticks; }
// set { SetValue(ref _ticks, value, GetPropertyName(MethodBase.GetCurrentMethod())); }
//}
public override bool Equals(object obj)
{
var item = obj as Poll;
if (item != null)
{
Equals(item);
}
return false;
}
public bool Equals(Poll other)
{
if (ReferenceEquals(null, other)) return false;
return (other.pid == pid);
}
public override string ToString()
{
return string.Format("{0}_{1}", GetType().Name, pid);
}
public override int GetHashCode()
{
return ToString().ToUpper().GetHashCode();
}
}
Save method looks like that:
public bool RowsSave<T>(IEnumerable<T> entities, out string error)
{
error = string.Empty;
bool res;
var type = typeof (T);
using (var ctx = new PpaDataContext(_connectionString))
{
try
{
var entitesInDb = ctx.GetTable(type).Cast<T>().ToList();
var entitesForSave = new List<T>();
foreach (var entity in entities)
{
if (!entitesInDb.Contains(entity))
{
entitesForSave.Add(entity);
}
else
{
var index = entitesInDb.IndexOf(entity);
foreach (var prop in PropertiesGet(entity))
{
prop.SetValue(entitesInDb[index], prop.GetValue(entity, null), null);
}
}
}
if(entitesForSave.Count > 0)
{
ctx.GetTable(type).InsertAllOnSubmit(entitesForSave);
}
ctx.SubmitChanges();
res = true;
}
catch (Exception ex)
{
error = string.Format("{0}", ex.Message);
res = false;
}
}
return res;
}
When I try insert, each object inserts twice. What incorrect in this code?
The RowsSave method calling one time only.
This is a bit after the fact, but I've run into the exact same problem. This has to do with an error in overridden equality operators. In this specific case, the problem appears because the code does not return the value of the Equals function in:
public override bool Equals(object obj)
{
var item = obj as Poll;
if (item != null)
{
Equals(item);
}
return false;
}
That code will always return false. The corrected code should be:
public override bool Equals(object obj)
{
var item = obj as Poll;
if (item != null)
{
return Equals(item);
}
return false;
}
LINQ-to-SQL uses the object equals comparison after insertions. I'm not sure in what context and for what reason this happens, but if the comparison returns false, it runs the insertion again. If you're experiencing the same behavior, check any overridden equality methods for your entity for correctness.
I don't think you need the line:
ctx.SubmitChanges();
as an insert is being done on the line:
ctx.GetTable(type).InsertAllOnSubmit(entitesForSave);

data mode : read write with c# local database in wp7

I created a local db with helper app project. and deployed it from isolate storage to installation folder,i added to project directory with content build action by add existing item. my problem is that i want to insert data, but i don't know how to move the db file to isolate storage to insert and data must add to my .sdf file that is locate in my project directory also.
Souphia,
While learning to use WP, I wrote a simple application that tracked tasks.
One version of that app stored all task data in Sql on the phone.
You can read the post and download all the code for the app here:
http://www.ritzcovan.com/2012/02/building-a-simple-windows-phone-app-part-3/
But, here is some of the code from that project:
First we have the model class decorated with the appropriate attributes:
[Table]
public class Task : INotifyPropertyChanged, INotifyPropertyChanging
{
[Column(IsDbGenerated = false, IsPrimaryKey = true, CanBeNull = false)]
public string Id
{
get { return _id; }
set
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanging("Id");
}
}
[Column]
public string Name
{
get { return _name; }
set
{
NotifyPropertyChanging("Name");
_name = value;
NotifyPropertyChanged("Name");
}
}
[Column]
public string Category
{
get { return _category; }
set
{
NotifyPropertyChanging("Category");
_category = value;
NotifyPropertyChanged("Category");
}
}
[Column]
public DateTime? DueDate
{
get { return _dueDate; }
set
{
NotifyPropertyChanging("DueDate");
_dueDate = value;
NotifyPropertyChanged("DueDate");
}
}
[Column]
public DateTime? CreateDate
{
get { return _createDate; }
set
{
NotifyPropertyChanging("CreateDate");
_createDate = value;
NotifyPropertyChanged("CreateDate");
}
}
[Column]
public bool IsComplete
{
get { return _isComplete; }
set
{
NotifyPropertyChanging("IsComplete");
_isComplete = value;
NotifyPropertyChanged("IsComplete");
}
}
[Column(IsVersion = true)] private Binary _version;
private string _id;
private bool _isComplete;
private DateTime? _createDate;
private DateTime? _dueDate;
private string _name;
private string _category;
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public void NotifyPropertyChanging(string property)
{
if (PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs(property));
}
}
In the constructor in app.xaml.cs, I have the following:
TaskMasterDataContext = new TaskMasterDataContext();
if (!TaskMasterDataContext.DatabaseExists())
{
TaskMasterDataContext.CreateDatabase();
DatabaseHelper.SetupDatabase(TaskMasterDataContext);
}
and here is the TaskMasterDataContext.cs code
public class TaskMasterDataContext : DataContext
{
public TaskMasterDataContext() : base("Data Source=isostore:/TaskMasterData.sdf")
{
}
public Table<Task> Tasks;
}
public static class DatabaseHelper
{
public static void SetupDatabase(TaskMasterDataContext dataContext)
{
string category = string.Empty;
var tasks = new List<Task>();
for (int i = 0; i < 20; i++)
{
tasks.Add(new Task()
{
Id = System.Guid.NewGuid().ToString(),
Category = GetCategoryString(i),
CreateDate = DateTime.Now,
DueDate = DateTime.Now.AddDays(new Random().Next(1, 30)),
IsComplete = false,
Name = String.Format("{0} Task # {1}", GetCategoryString(i), i)
});
}
dataContext.Tasks.InsertAllOnSubmit(tasks);
dataContext.SubmitChanges();
}
private static string GetCategoryString(int i)
{
if (i%2 == 0)
return "home";
if (i%3 == 0)
return "personal";
return "work";
}
}
The DatabaseHelper class is just there to populate the DB with some test data after its created.
I hope this helps.

Resources