Files
2018-06-29 19:47:36 +00:00

2526 lines
66 KiB
C#

///////////////////////////////////////////////////////////
// Unit.cs
// Implementation of Class Unit
// CSLA type: Editable Root
// Created on: 07-Jun-2004 8:41:38 AM
// Object design: Joyce
// Coded: John 20-July-2004
///////////////////////////////////////////////////////////
using System;
using System.Data;
using CSLA.Data;
using GZTW.Data;
using CSLA;
using System.Threading;
using CSLA.Security;
namespace GZTW.AyaNova.BLL
{
/// <summary>
/// Unit - an item attributed to a specific client that is to be repaired or serviced
/// </summary>
[Serializable]
public class Unit : BusinessBase {
#region Attributes
private bool bReadOnly;
private Guid mID;
private SmartDate mCreated;
private SmartDate mModified;
private bool mActive;
private Guid mCreator;
private Guid mModifier;
private Address mGoToAddress;
private AssignedDocs mDocs;
private string mNotes="";
private string mSerial=null;
private Guid mUnitModelID;
private string mDescription="";
private Guid mClientID;
private bool mUnitHasOwnAddress;
private bool mBoughtHere;
private Guid mPurchasedFromID;
private string mReceipt="";
private SmartDate mPurchasedDate;
private Guid mReplacedByUnitID;
private bool mOverrideModelWarranty;
private string mWarrantyTerms="";
//ID of unit this unit is to be grouped as a child under
//can be null
private Guid mParentUnitID;
//Custom fields
private string mCustom1="";
private string mCustom2="";
private string mCustom3="";
private string mCustom4="";
private string mCustom5="";
private string mCustom6="";
private string mCustom7="";
private string mCustom8="";
private string mCustom9="";
private string mCustom0="";
private bool mUsesBanking;
private bool mMetered;
private int mWarrantyLength;
private bool mLifeTimeWarranty;
private string mText1 = "";
private string mText2 = "";
private string mText3 = "";
private string mText4 = "";
#endregion
#region Constructor
/// <summary>
/// Private constructor to prevent direct instantiation
/// </summary>
private Unit()
{
//Set to read / write initially so that properties
//can be set
bReadOnly=false;
//New ID
mID = Guid.NewGuid();
Active=true;
mPurchasedDate=new SmartDate();
//Set record history to defaults
mCreated = new SmartDate(DBUtil.CurrentWorkingDateTime);
mModified=new SmartDate();
mCreator=Guid.Empty;
mModifier=Guid.Empty;
mUsesBanking=false;
mMetered=false;
mOverrideModelWarranty=false;
mLifeTimeWarranty=false;
mWarrantyLength=0;
mDocs=AssignedDocs.NewItems();
//pre-break the client required rule
ClientID=Guid.NewGuid();
ClientID=Guid.Empty;
//pre-break the serial required rule
Serial = "";
}
#endregion
#region Business properties
/// <summary>
/// Get internal id number Read only property because it's set internally, not
/// externally
/// </summary>
public Guid ID
{
get
{
return mID;
}
}
/// <summary>
/// Get created date
///
///
/// </summary>
public string Created
{
get
{
return mCreated.ToString();
}
}
/// <summary>
/// Get modified date
///
///
/// </summary>
public string Modified
{
get
{
return mModified.ToString();
}
}
/// <summary>
/// Get user record ID of person who created this record
///
///
/// </summary>
public Guid Creator
{
get
{
return mCreator;
}
}
/// <summary>
/// Get user ID of person who modified this record
///
///
/// </summary>
public Guid Modifier
{
get
{
return mModifier;
}
}
/// <summary>
/// Get /set active status of Unit
/// If active = true then Unit is selectable for workorders etc
/// If active = false then Unit in not selectable, but history can be viewed
/// </summary>
public bool Active
{
get
{
return mActive;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mActive!=value)
{
mActive = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Get service address for this Unit
/// can be used to override client address
/// if unit is not at client's site
/// </summary>
public Address GoToAddress
{
get
{
return mGoToAddress;
}
}
/// <summary>
/// Notes about unit
/// </summary>
public string Notes
{
get
{
return mNotes;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mNotes!=value)
{
mNotes = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Assigned documents collection for unit
/// </summary>
public AssignedDocs Docs
{
get
{
return mDocs;
}
}
/// <summary>
/// Overrides any other warranty terms from unitmodel
/// </summary>
public bool OverrideModelWarranty
{
get
{
return mOverrideModelWarranty;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mOverrideModelWarranty!=value)
{
mOverrideModelWarranty = value;
//clear any override terms
if(value==false)
{
WarrantyTerms="";
LifeTimeWarranty=false;
WarrantyLength=0;
}
MarkDirty();
}
}
}
}
/// <summary>
/// Terms for the unit's warranty
/// </summary>
public string WarrantyTerms
{
get
{
return mWarrantyTerms;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mWarrantyTerms!=value)
{
mWarrantyTerms = value;
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="Client"/> unit assigned to
///
/// </summary>
public Guid ClientID
{
get
{
return mClientID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mClientID!=value)
{
mClientID = value;
BrokenRules.Assert("ClientIDRequired",
"Error.Object.RequiredFieldEmpty,O.Client",
"ClientID",value==Guid.Empty);
MarkDirty();
}
}
}
}
/// <summary>
/// <see cref="Vendor"/> where purchased from
/// </summary>
public Guid PurchasedFromID
{
get
{
return mPurchasedFromID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mPurchasedFromID!=value)
{
mPurchasedFromID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Optional <see cref="UnitModel"/> type for this unit
///
/// </summary>
public Guid UnitModelID
{
get
{
return mUnitModelID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mUnitModelID!=value)
{
mUnitModelID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// ID of unit this unit is to be grouped as a child under (null or empty id = no parent)
/// </summary>
public Guid ParentID
{
get
{
return mParentUnitID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mParentUnitID!=value)
{
mParentUnitID = value;
MarkDirty();
}
}
}
}
/// <summary>
/// default is false
/// if true, unit address is specified in GoToAddress
/// </summary>
public bool UnitHasOwnAddress
{
get
{
return mUnitHasOwnAddress;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mUnitHasOwnAddress!=value)
{
mUnitHasOwnAddress = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Serial number of unit. This is the primary identifier in AyaNova however duplicates are allowed.
/// The UI presents a warning on duplicate entry, calling directly does not so be careful calling this in code.
/// </summary>
public string Serial
{
get
{
return mSerial;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mSerial!=value)
{
mSerial = value;
BrokenRules.Assert("SerialRequired",
"Error.Object.RequiredFieldEmpty,Unit.Label.Serial",
"Serial",value.Length==0);
BrokenRules.Assert("SerialLength",
"Error.Object.FieldLengthExceeded255,Unit.Label.Serial",
"Serial",value.Length>255);
MarkDirty();
}
}
}
}
/// <summary>
/// Original sales receipt number
/// </summary>
public string Receipt
{
get
{
return mReceipt;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mReceipt!=value)
{
mReceipt = value;
MarkDirty();
}
}
}
}
/// <summary>
/// default is true
/// if false, than select PurchasedFrom vendor id
/// </summary>
public bool BoughtHere
{
get
{
return mBoughtHere;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mBoughtHere!=value)
{
mBoughtHere = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Date unit was purchased
/// Utilized to determine warranty info
/// </summary>
public object PurchasedDate
{
get
{
return mPurchasedDate.DBValue;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if (!AyaBizUtils.SmartDateEquals(mPurchasedDate, value)) //Case 298
{
mPurchasedDate.DBValue = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Description of unit to display if no model chosen
/// </summary>
public string Description
{
get
{
return mDescription;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mDescription!=value)
{
mDescription = value;
MarkDirty();
}
}
}
}
/// <summary>
/// If a unit is replaced while in warranty (WorkorderItemOutsideService) sets this
/// unit to inactive, and enters in new units serialnumber that replaced it
/// </summary>
public Guid ReplacedByUnitID
{
get
{
return mReplacedByUnitID;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mReplacedByUnitID!=value)
{
mReplacedByUnitID = value;
MarkDirty();
}
}
}
}
#region CUSTOM FIELDS
/// <summary>
/// Custom1
/// </summary>
public string Custom1
{
get
{
return mCustom1;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom1!=value)
{
mCustom1 = value;
BrokenRules.Assert("Custom1Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom1","Custom1",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom2
/// </summary>
public string Custom2
{
get
{
return mCustom2;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom2!=value)
{
mCustom2 = value;
BrokenRules.Assert("Custom2Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom2","Custom2",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom3
/// </summary>
public string Custom3
{
get
{
return mCustom3;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom3!=value)
{
mCustom3 = value;
BrokenRules.Assert("Custom3Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom3","Custom3",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom4
/// </summary>
public string Custom4
{
get
{
return mCustom4;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom4!=value)
{
mCustom4 = value;
BrokenRules.Assert("Custom4Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom4","Custom4",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom5
/// </summary>
public string Custom5
{
get
{
return mCustom5;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom5!=value)
{
mCustom5 = value;
BrokenRules.Assert("Custom5Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom5","Custom5",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom6
/// </summary>
public string Custom6
{
get
{
return mCustom6;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom6!=value)
{
mCustom6 = value;
BrokenRules.Assert("Custom6Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom6","Custom6",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom7
/// </summary>
public string Custom7
{
get
{
return mCustom7;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom7!=value)
{
mCustom7 = value;
BrokenRules.Assert("Custom7Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom7","Custom7",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom8
/// </summary>
public string Custom8
{
get
{
return mCustom8;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom8!=value)
{
mCustom8 = value;
BrokenRules.Assert("Custom8Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom8","Custom8",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom9
/// </summary>
public string Custom9
{
get
{
return mCustom9;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom9!=value)
{
mCustom9 = value;
BrokenRules.Assert("Custom9Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom9","Custom9",value.Length>500);
MarkDirty();
}
}
}
}
/// <summary>
/// Custom0
/// </summary>
public string Custom0
{
get
{
return mCustom0;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mCustom0!=value)
{
mCustom0 = value;
BrokenRules.Assert("Custom0Length",
"Error.Object.FieldLengthExceeded500,Unit.Label.Custom0","Custom0",value.Length>500);
MarkDirty();
}
}
}
}
#endregion custom fields
/// <summary>
/// If true then banked service is tracked
/// for this object (hours / money / incidents)
/// </summary>
public bool UsesBanking
{
get
{
return mUsesBanking;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mUsesBanking!=value)
{
mUsesBanking = value;
MarkDirty();
}
}
}
}
/// <summary>
/// If true then meter readings can be entered for this unit
/// </summary>
public bool Metered
{
get
{
return mMetered;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mMetered!=value)
{
mMetered = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Lifetime warranty which never expires
/// overrides all other warranty terms
///
/// </summary>
public bool LifeTimeWarranty
{
get
{
return mLifeTimeWarranty;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mLifeTimeWarranty!=value)
{
mLifeTimeWarranty = value;
MarkDirty();
}
}
}
}
/// <summary>
/// Warranty length in months
/// Ignored if LifeTimeWarranty selected
/// </summary>
public int WarrantyLength
{
get
{
return mWarrantyLength;
}
set
{
if(bReadOnly)
ThrowSetError();
else
{
if(mWarrantyLength!=value)
{
mWarrantyLength = value;
MarkDirty();
}
}
}
}
//========= Resolved warranty ===================
/// <summary>
/// Returns <see cref="WarrantyStatus"/> of this unit based on all possible influences on warranty
/// such as lifetime, purchase date vs length of warranty for this unit or model of unit etc.
/// </summary>
public WarrantyStatus WarrantyStatusResolved
{
get
{
//First possible warranty is the override warranty for this unit...
if(mOverrideModelWarranty)
{
//Does it have a lifetime warranty?
if(mLifeTimeWarranty) return WarrantyStatus.Active;
//Ok, at this point the only possible UNIT warranty left is the
//unit warranty length in months, so this depends upon age of unit
//which requires a purchase date to Process
if(mPurchasedDate.IsEmpty) return WarrantyStatus.None;
//Do we have a unit warranty length greater than zero?
if(mWarrantyLength<1) return WarrantyStatus.None;
//Ok, we have a purchase date and we have a Unit warranty length so
//see if it's still under warranty
//If the purchase date plus the months in the warranty is a date
//greater than right now, then it's still under warranty...
if (mPurchasedDate.Date.AddMonths(mWarrantyLength) > DBUtil.CurrentWorkingDateTime)
return WarrantyStatus.Active;
else
return WarrantyStatus.Expired;
}
//Ok, it doesn't have it's own specific warranty, only
//other possibility is a unit model warranty...
//Is there a unit model for this unit?
if(this.UnitModelID==Guid.Empty) return WarrantyStatus.None;
//Get it...
UnitModel m=UnitModel.GetItem(this.UnitModelID);
//Is it a lifetime warranty?
if(m.LifeTimeWarranty) return WarrantyStatus.Active;
//Ok, at this point the only possible warranty left is the
//unit model warranty length in months, so this depends upon age of unit
if(mPurchasedDate.IsEmpty) return WarrantyStatus.None;
//Do we have a unit model warranty length greater than zero?
if(m.WarrantyLength<1) return WarrantyStatus.None;
//Ok, we have a purchase date and we have a unitmodel warranty length so
//see if it's still under warranty
//If the purchase date plus the months in the warranty is a date
//greater than right now, then it's still under warranty...
if (mPurchasedDate.Date.AddMonths(m.WarrantyLength) > DBUtil.CurrentWorkingDateTime)
return WarrantyStatus.Active;
else
return WarrantyStatus.Expired;
}
}
/// <summary>
/// Resolved warranty expiry date
/// (definitive date from either unit model or
/// this unit's overriden properties)
/// If there is a lifetime warranty it returns DateTime.MaxValue
/// If there is no warranty expiry date determineable then it returns null.
/// Otherwise it returns a DateTime set to warranty expiry date.
/// </summary>
public object WarrantyExpiryDateResolved
{
get
{
//First possible warranty date is the override warranty for this unit...
if(mOverrideModelWarranty)
{
if(mLifeTimeWarranty) return System.DateTime.MaxValue;
//Ok, at this point the only possible warranty left is the
//unit warranty length in months, so this depends upon age of unit
if(mPurchasedDate.IsEmpty) return null;
//Do we have a unit warranty length greater than zero?
if(mWarrantyLength<1) return null;
//Ok, we have a purchase date and we have a unit warranty length so
//calculate and return expiry date
return mPurchasedDate.Date.AddMonths(mWarrantyLength);
}
//Ok, it doesn't have a custom warranty, only
//other possibility is a unit model warranty...
//Is there a unit model for this unit?
if(this.UnitModelID==Guid.Empty) return null;
//Get it...
UnitModel m=UnitModel.GetItem(this.UnitModelID);
//Is it a lifetime warranty?
if(m.LifeTimeWarranty) return System.DateTime.MaxValue;
//Ok, at this point the only possible warranty left is the
//unit model warranty length in months, so this depends upon age of unit
if(mPurchasedDate.IsEmpty) return null;
//Do we have a unit model warranty length greater than zero?
if(m.WarrantyLength<1) return null;
//Ok, we have a purchase date and we have a unitmodel warranty length so
//calculate and return expiry date
return mPurchasedDate.Date.AddMonths(m.WarrantyLength);
}
}
/// <summary>
/// Warranty terms resolved
/// (either from unit model or this units
/// overriden warranty properties as required)
/// Returns text of warranty terms or an empty string if none found
/// or no warranty applicb
/// </summary>
public string WarrantyTermsResolved
{
get
{
//First possible warranty is the override warranty for this unit...
if(mOverrideModelWarranty)
{
return mWarrantyTerms;
}
//Ok, it doesn't have a custom warranty, only
//other possibility is a unit model warranty...
//Is there a unit model for this unit?
if(this.UnitModelID==Guid.Empty) return "";
//Get it...
UnitModel m=UnitModel.GetItem(this.UnitModelID);
return m.WarrantyTerms;
}
}
/// <summary>
/// Brief unit history for display on work orders
/// Includes last closed service workorder number and date
/// and
/// Purchase Date:
/// Purchased From:
/// Receipt Number:
/// (localized)
///
/// </summary>
public string History
{
get
{
UnitLastServiceWorkorderInfoFetcher f = UnitLastServiceWorkorderInfoFetcher.LastServiceInfo(mID);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(LocalizedTextTable.GetLocalizedTextDirect("UI.Label.LastServiceDate"));
sb.Append(": ");
if (f.LastServiceWorkorderNumber != -1)
sb.Append(f.LastServiceDate.ToString());
else
sb.Append("-");
sb.Append("\r\n");
sb.Append(LocalizedTextTable.GetLocalizedTextDirect("UI.Label.LastWorkorder"));
sb.Append(": ");
if (f.LastServiceWorkorderNumber != -1)
sb.Append(f.LastServiceWorkorderNumber.ToString());
else
sb.Append("-");
sb.Append("\r\n");
if (!mPurchasedDate.IsEmpty)
{
sb.Append(LocalizedTextTable.GetLocalizedTextDirect("Unit.Label.PurchasedDate"));
sb.Append(": ");
sb.Append(mPurchasedDate.ToString());
sb.Append("\r\n");
}
if (mPurchasedFromID!=Guid.Empty)
{
if (VendorExistanceChecker.VendorExists(mPurchasedFromID, ""))
{
sb.Append(LocalizedTextTable.GetLocalizedTextDirect("Unit.Label.PurchaseFromID"));
sb.Append(": ");
sb.Append(NameFetcher.GetItem("VENDOR","NAME",mPurchasedFromID).RecordName);
sb.Append("\r\n");
}
}
if (!string.IsNullOrEmpty(mReceipt))
{
sb.Append(LocalizedTextTable.GetLocalizedTextDirect("Unit.Label.Receipt"));
sb.Append(": ");
sb.Append(mReceipt);
sb.Append("\r\n");
}
return sb.ToString();
}
}
/// <summary>
/// Flag - indicates if current user can open the wiki page for this object
///
/// This is cached for the lifetime of this object
/// </summary>
public bool CanWiki//case 73
{
get
{
if (!bCanWiki.HasValue)
bCanWiki = WikiPage.ShowWikiLink(RootObjectTypes.Unit, mID);
return bCanWiki.Value;
}
}
//cache the result in case the UI calls this repeatedly
private bool? bCanWiki = null;
/// <summary>
/// Optional first extra text field
/// </summary>
public string Text1
{
get
{return mText1;}
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mText1 != value)
{
mText1 = value;
BrokenRules.Assert("Text1Length",
"Error.Object.FieldLengthExceeded255,Unit.Label.Text1",
"Text1", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Optional second extra text field
/// </summary>
public string Text2
{
get
{ return mText2; }
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mText2 != value)
{
mText2 = value;
BrokenRules.Assert("Text2Length",
"Error.Object.FieldLengthExceeded255,Unit.Label.Text2",
"Text2", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Optional third extra text field
/// </summary>
public string Text3
{
get
{ return mText3; }
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mText3 != value)
{
mText3 = value;
BrokenRules.Assert("Text3Length",
"Error.Object.FieldLengthExceeded255,Unit.Label.Text3",
"Text3", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Optional fourth extra text field
/// </summary>
public string Text4
{
get
{ return mText4; }
set
{
if (bReadOnly)
ThrowSetError();
else
{
if (mText4 != value)
{
mText4 = value;
BrokenRules.Assert("Text4Length",
"Error.Object.FieldLengthExceeded255,Unit.Label.Text4",
"Text4", value.Length > 255);
MarkDirty();
}
}
}
}
/// <summary>
/// Indicates if item can be duplicated or not
/// Item can be duplicated if the current user
/// has write rights to this type of object and this item
/// is not dirty or new and IsValid
/// </summary>
public bool CanDuplicate
{
get
{
if (!AyaBizUtils.CanWrite(RootObjectTypes.Unit)) return false;
if (IsDirty || IsNew || (!IsValid)) return false;
return true;
}
}
/// <summary>
/// Generates a duplicate of this item
/// and returns it.
///
/// Warning: Serial number is also duplicated to facilitate a user entering multiple items where the serial number only deviates slightly
/// to save editing. If calling this through code be aware of this potential for duplication of a critical identification field.
/// </summary>
/// <returns>A duplicated Unit</returns>
public Unit Duplicate()
{//case 839
Unit dest = Unit.NewItem();
dest.BoughtHere = BoughtHere;
dest.ClientID = ClientID;
dest.Custom0 = Custom0;
dest.Custom1 = Custom1;
dest.Custom2 = Custom2;
dest.Custom3 = Custom3;
dest.Custom4 = Custom4;
dest.Custom5 = Custom5;
dest.Custom6 = Custom6;
dest.Custom7 = Custom7;
dest.Custom8 = Custom8;
dest.Custom9 = Custom9;
dest.Description = Description;
dest.GoToAddress.City = GoToAddress.City;
dest.GoToAddress.Country = GoToAddress.Country;
dest.GoToAddress.CountryCode = GoToAddress.CountryCode;
dest.GoToAddress.DeliveryAddress = GoToAddress.DeliveryAddress;
dest.GoToAddress.LatHemisphere = GoToAddress.LatHemisphere;
dest.GoToAddress.Latitude = GoToAddress.Latitude;
dest.GoToAddress.LongHemisphere = GoToAddress.LongHemisphere;
dest.GoToAddress.Longitude = GoToAddress.Longitude;
dest.GoToAddress.Postal = GoToAddress.Postal;
dest.GoToAddress.StateProv = GoToAddress.StateProv;
dest.LifeTimeWarranty = LifeTimeWarranty;
dest.Metered = Metered;
dest.Notes = Notes;
dest.OverrideModelWarranty = OverrideModelWarranty;
dest.ParentID = ParentID;
dest.PurchasedDate = PurchasedDate;
dest.PurchasedFromID = PurchasedFromID;
dest.Receipt = Receipt;
dest.ReplacedByUnitID = ReplacedByUnitID;
dest.Serial = Serial;
dest.Text1 = Text1;
dest.Text2 = Text2;
dest.Text3 = Text3;
dest.Text4 = Text4;
dest.UnitHasOwnAddress = UnitHasOwnAddress;
dest.UnitModelID = UnitModelID;
dest.UsesBanking = UsesBanking;
dest.WarrantyLength = WarrantyLength;
dest.WarrantyTerms = WarrantyTerms;
return dest;
}
/// <summary>
/// Throw an error when a read only user
/// tries to set a property
/// (this should normally never be called unless someone is using the developer api since the UI
/// should prevent it from happening initially)
/// </summary>
private void ThrowSetError()
{
throw new System.Security.SecurityException
(
string.Format
(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToChange"),
LocalizedTextTable.GetLocalizedTextDirect("O.Unit")
)
);
}
#endregion
#region System.object overrides
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return "Unit" + mID.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(Object obj)
{
if ( obj == null || GetType ( ) != obj.GetType ( ) ) return false;
Unit c=(Unit)obj;
return mID==c.mID;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return ("Unit"+mID).GetHashCode();
}
#endregion
#region Searching
/// <summary>
/// Returns a search result object based on search terms
/// for the ID specified
/// </summary>
/// <param name="ID"></param>
/// <param name="searchTerms"></param>
/// <returns></returns>
public static SearchResult GetSearchResult(Guid ID, string[]searchTerms)
{
if(AyaBizUtils.Right("Object.Unit")<(int)SecurityLevelTypes.ReadOnly)
return new SearchResult();
SearchResult sr=new SearchResult();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
SafeDataReader dr = null;
try
{
dr=DBUtil.GetReaderFromSQLString(
"SELECT aClientID, aCreated, aModified, aCreator, aModifier, aSerial, " +
" aNotes, aReceipt, aDescription, aWarrantyTerms, aCustom2, " +
" aCustom3, aCustom4, aCustom5, aCustom6, aCustom7, " +
"aCustom8, aCustom9, aCustom0, aCustom1, aText1, aText2, aText3, aText4 FROM aUnit WHERE " +
"(aID = @ID)"
,ID);
if(!dr.Read())
return new SearchResult();//DBUtil.ThrowFetchError("SearchResult for UnitID: " + ID.ToString());
if (
!AyaBizUtils.InYourRegion(
ObjectRegionIDFetcher.ObjectRegion(
new TypeAndID(
RootObjectTypes.Client, dr.GetGuid("aClientID")
)
)
)
) return new SearchResult();//case 58
sr.Description=dr.GetString("aSerial");
sb.Append(sr.Description);
sb.Append(" ");
sb.Append(dr.GetString("aDescription"));
sb.Append(" ");
sb.Append(dr.GetString("aNotes"));
sb.Append(" ");
sb.Append(dr.GetString("aReceipt"));
sb.Append(" ");
sb.Append(dr.GetString("aWarrantyTerms"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom0"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom1"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom2"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom3"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom4"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom5"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom6"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom7"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom8"));
sb.Append(" ");
sb.Append(dr.GetString("aCustom9"));
sb.Append(" ");
sb.Append(dr.GetString("aText1"));
sb.Append(" ");
sb.Append(dr.GetString("aText2"));
sb.Append(" ");
sb.Append(dr.GetString("aText3"));
sb.Append(" ");
sb.Append(dr.GetString("aText4"));
sr.Created=DBUtil.ToLocal(dr.GetSmartDate("aCreated"));
sr.Modified=DBUtil.ToLocal(dr.GetSmartDate("aModified"));
sr.Creator=dr.GetGuid("aCreator");
sr.Modifier=dr.GetGuid("aModifier");
}
finally
{
if(dr!=null) dr.Close();
}
//Added 02-Aug-2006 was not returning address search results :(
#region Address block
try
{
dr = DBUtil.GetReaderFromSQLString(
"SELECT adeliveryaddress, acity, astateprov, acountrycode, acountry, apostal " +
"from aaddress " +
"where " +
"arootobjectid=@ID "
, ID);
while (dr.Read())
{
sb.Append(" ");
sb.Append(dr.GetString("adeliveryaddress"));
sb.Append(" ");
sb.Append(dr.GetString("acity"));
sb.Append(" ");
sb.Append(dr.GetString("astateprov"));
sb.Append(" ");
sb.Append(dr.GetString("acountrycode"));
sb.Append(" ");
sb.Append(dr.GetString("acountry"));
sb.Append(" ");
sb.Append(dr.GetString("apostal"));
}
}
finally
{
if (dr != null) dr.Close();
}
#endregion
//Formulate results
ExtractAndRank er = new ExtractAndRank();
er.Process(sb.ToString().Trim(),searchTerms);
sr.Extract=er.Extract;
sr.Rank=er.Ranking;
sr.AncestorRootObjectID=ID;
sr.AncestorRootObjectType=RootObjectTypes.Unit;
return sr;
}
#endregion
#region Static methods
/// <summary>
/// Return unitname in selected format
/// based on passed in data
/// </summary>
/// <param name="ModelNumber"></param>
/// <param name="Model"></param>
/// <param name="Vendor"></param>
/// <param name="Serial"></param>
/// <param name="Description"></param>
/// <param name="Format"></param>
/// <returns></returns>
public static string UnitNameFormatter(string ModelNumber, string Model, string Vendor, string Serial, string Description, UnitNameDisplayFormats Format)
{
switch(Format)
{
case UnitNameDisplayFormats.ModelSerial:
return AyaBizUtils.SS("",Model," - ") + Serial;
case UnitNameDisplayFormats.SerialOnly:
return Serial;
case UnitNameDisplayFormats.VendorModelSerial:
return AyaBizUtils.SS("",Vendor,": ") + AyaBizUtils.SS("",Model," - ") + Serial ;
case UnitNameDisplayFormats.VendorSerial:
return AyaBizUtils.SS("",Vendor,": ") + Serial;
case UnitNameDisplayFormats.SerialModel:
return AyaBizUtils.SS("",Serial," - ") + Model;
case UnitNameDisplayFormats.SerialModelVendor:
return AyaBizUtils.SS("",Serial,": ") + AyaBizUtils.SS("",Model," - ") + Vendor ;
case UnitNameDisplayFormats.ModelNumberModelSerial:
return AyaBizUtils.SS("", ModelNumber, ": ") + AyaBizUtils.SS("", Model, " - ") + Serial;
case UnitNameDisplayFormats.ModelModelNumberSerial:
return AyaBizUtils.SS("", Model, ": ") + AyaBizUtils.SS("", ModelNumber, " - ") + Serial;
//case 1519
case UnitNameDisplayFormats.VendorModelModelNumberSerial:
return AyaBizUtils.SS("", Vendor, ": ") + AyaBizUtils.SS("", Model, ", ") + AyaBizUtils.SS("", ModelNumber, " - ") + Serial;
//case 3150
case UnitNameDisplayFormats.SerialDescription:
return AyaBizUtils.SS("", Serial, " - ") + Description;
case UnitNameDisplayFormats.VendorSerialDescription:
return AyaBizUtils.SS("", Vendor, ": ") + AyaBizUtils.SS("", Serial, " - ") + Description;
default:
return Serial;
}
}
/// <summary>
/// Return unitname in default (Global setting) format
/// based on passed in information
/// </summary>
/// <param name="Model"></param>
/// <param name="Vendor"></param>
/// <param name="Serial"></param>
/// <param name="Description"></param>
/// <param name="ModelName"></param>
/// <returns></returns>
public static string UnitNameFormatter(string ModelName, string Model, string Vendor, string Serial, string Description)
{
return UnitNameFormatter(ModelName,Model,Vendor,Serial, Description, AyaBizUtils.GlobalSettings.DefaultUnitNameDisplayFormat);
}
/// <summary>
/// Retrieves the name of the client that owns the passed in Unit ID
/// </summary>
/// <param name="UnitID"></param>
/// <returns></returns>
public static string GetOwnerNameForUnit(Guid UnitID)
{
Unit u=Unit.GetItemMRU(UnitID, false);
if(u.ClientID==Guid.Empty) return "";
return NameFetcher.GetItem("aClient","aName",u.ClientID).RecordName;
}
//case 1975
/// <summary>
/// Retrieves the ID of the client that owns the passed in Unit ID
/// </summary>
/// <param name="UnitID"></param>
/// <returns></returns>
public static Guid GetOwnerIDForUnit(Guid UnitID)
{
Unit u = Unit.GetItemMRU(UnitID, false);
return u.ClientID;
}
/// <summary>
/// Create new Unit
/// </summary>
/// <returns>Unit</returns>
public static Unit NewItem()
{
Unit c;
if(AyaBizUtils.Right("Object.Unit")>(int)SecurityLevelTypes.ReadOnly)
{
c = new Unit();
c.mGoToAddress=Address.NewItem();
c.mGoToAddress.RootObjectID=c.ID;
c.mGoToAddress.RootObjectType=RootObjectTypes.Unit;
c.mGoToAddress.AddressType=AddressTypes.Physical;
return c;
}
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToCreate"),
LocalizedTextTable.GetLocalizedTextDirect("O.Unit")));
}
/// <summary>
/// Fetch existing Unit
/// </summary>
/// <returns>Unit</returns>
/// <param name="_ID">Unit Guid</param>
public static Unit GetItem(Guid _ID)
{
return GetItemMRU(_ID, true);
}
/// <summary>
/// Get item with optional tracking of MRU
/// See <see cref="UserMRU"/>
/// </summary>
/// <param name="_ID"></param>
/// <param name="TrackMRU"></param>
/// <returns></returns>
public static Unit GetItemMRU(Guid _ID, bool TrackMRU)
{
if (_ID == AyaBizUtils.NewObjectGuid)
return NewItem();
if(AyaBizUtils.Right("Object.Unit")>(int)SecurityLevelTypes.NoAccess)
return (Unit)DataPortal.Fetch(new Criteria(_ID,TrackMRU));
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToRetrieve"),
LocalizedTextTable.GetLocalizedTextDirect("O.Unit")));
}
/// <summary>
/// Delete Unit
/// </summary>
/// <param name="_ID">Unit GUID</param>
public static void DeleteItem(Guid _ID)
{
if(AyaBizUtils.Right("Object.Unit")>(int)SecurityLevelTypes.ReadWrite)
DataPortal.Delete(new Criteria(_ID,true));
else
throw new System.Security.SecurityException(
string.Format(
LocalizedTextTable.GetLocalizedTextDirect("Error.Security.NotAuthorizedToDelete"),
LocalizedTextTable.GetLocalizedTextDirect("O.Unit")));
}
/// <summary>
/// Retrieves the last (most recent) meter reading of the passed in Unit
/// </summary>
/// <param name="_ID"></param>
/// <returns></returns>
public static long LastMeterReading(Guid _ID)
{
//Case 501
return UnitLastMeterReadingFetcher.LastMeterReading(_ID);
}
/// <summary>
/// Retrieves the metered status of a unit based on it's ID
/// </summary>
/// <param name="_ID"></param>
/// <returns>True=Unit is set to track meter readings, false=not metered</returns>
public static bool IsMetered(Guid _ID)
{
//Case 502
return UnitIsMeteredChecker.UnitIsMetered(_ID);
}
//Case 421:
/// <summary>
/// Check for the existance of a unit
/// in the database by ID OR by serialnumber
/// </summary>
/// <param name="ID">Guid of item</param>
/// <param name="SerialNumber">Serial number of item</param>
/// <returns></returns>
public static bool Exists(Guid ID, string SerialNumber)
{
//Case 503
return UnitExistanceChecker.UnitExists(ID, SerialNumber);
}
/// <summary>
/// Determine internal ID of Unit from a serial number.
/// </summary>
/// <param name="SerialNumber">Text value</param>
/// <returns>Unit's Guid ID value or Guid.Empty if no match</returns>
public static Guid GetIDFromSerialNumber(string SerialNumber)
{
return GuidFetcher.GetItem("AUNIT", "ASERIAL", SerialNumber);
}
#endregion
#region DAL DATA ACCESS
#region Fetch
///
/// <param name="Criteria"></param>
protected override void DataPortal_Fetch(object Criteria)
{
//set to false to load items initially
bReadOnly=false;
Criteria crit = (Criteria)Criteria;
SafeDataReader dr = null;
try
{
dr=DBUtil.GetReaderFromSQLString("SELECT * FROM aUnit WHERE aID=@ID;",crit.ID);
if(!dr.Read())
DBUtil.ThrowFetchError("Unit ID: " + crit.ID.ToString());
//Standard fields
mID=dr.GetGuid("aID");
mCreated=DBUtil.ToLocal(dr.GetSmartDate("aCreated"));
mModified=DBUtil.ToLocal(dr.GetSmartDate("aModified"));
mCreator=dr.GetGuid("aCreator");
mModifier=dr.GetGuid("aModifier");
//Custom fields
mCustom1=dr.GetString("aCustom1");
mCustom2=dr.GetString("aCustom2");
mCustom3=dr.GetString("aCustom3");
mCustom4=dr.GetString("aCustom4");
mCustom5=dr.GetString("aCustom5");
mCustom6=dr.GetString("aCustom6");
mCustom7=dr.GetString("aCustom7");
mCustom8=dr.GetString("aCustom8");
mCustom9=dr.GetString("aCustom9");
mCustom0=dr.GetString("aCustom0");
//Unit fields
Active=dr.GetBoolean("AACTIVE");
mBoughtHere=dr.GetBoolean("aBoughtHere");
//Unbreak the client id rule
ClientID=dr.GetGuid("aClientID");
mOverrideModelWarranty=dr.GetBoolean("aOverrideModelWarranty");
mWarrantyTerms=dr.GetString("aWarrantyTerms");
mDescription=dr.GetString("aDescription");
mNotes=dr.GetString("aNotes");
mPurchasedDate=DBUtil.ToLocal(dr.GetSmartDate("aPurchasedDate"));
mPurchasedFromID=dr.GetGuid("aPurchasedFromID");
mReceipt=dr.GetString("aReceipt");
mReplacedByUnitID=dr.GetGuid("aReplacedByUnitID");
//Unbreak the serial rule
Serial=dr.GetString("aSerial");
mUnitHasOwnAddress=dr.GetBoolean("aUnitHasOwnAddress");
mUnitModelID=dr.GetGuid("aUnitModelID");
mParentUnitID=dr.GetGuid("aParentUnitID");
mUsesBanking=dr.GetBoolean("aUsesBanking");
mMetered=dr.GetBoolean("aMetered");
mWarrantyLength=dr.GetInt32("aWarrantyLength");
mLifeTimeWarranty=dr.GetBoolean("aLifeTimeWarranty");
mText1 = dr.GetString("aText1");
mText2 = dr.GetString("aText2");
mText3 = dr.GetString("aText3");
mText4 = dr.GetString("aText4");
if(dr!=null) dr.Close();
/*
* Load child collection objects
*/
//GoToAddress
dr=DBUtil.GetReaderFromSQLString("SELECT * " +
"FROM AADDRESS WHERE aRootObjectID=@ID AND " +
"aRootObjectType=7 AND AADDRESSTYPE=2",crit.ID);
if(dr.Read())
mGoToAddress=Address.GetItem(dr);
if(dr!=null) dr.Close();
//Docs
dr=DBUtil.GetReaderFromSQLString("SELECT * FROM AASSIGNEDDOC WHERE (aRootObjectID=@ID and aRootObjectType=7);",crit.ID);
mDocs = AssignedDocs.GetItems(dr, RootObjectTypes.Unit, RootObjectTypes.Unit);
if(dr!=null) dr.Close();
}
finally
{
if(dr!=null) dr.Close();
}
MarkOld();
if(crit.TrackMRU)
if(AyaBizUtils.AllowAutomaticMRUOnUpdate) AyaBizUtils.MRU.Add(RootObjectTypes.Unit, mID);
//Get access rights level
bReadOnly=AyaBizUtils.Right("Object.Unit")<(int)SecurityLevelTypes.ReadWrite;
}
#endregion fetch
#region Update
/// <summary>
/// Called by DataPortal to delete/add/update data into the database
/// </summary>
protected override void DataPortal_Update()
{
// If not a new record, check if record was modified
//by another user since original retrieval:
if(!IsNew)
DBUtil.CheckSafeToUpdate(this.mModified.Date,this.mID,"aUnit");
#region Delete
if(IsDeleted)
{
if(!IsNew)
{
//Delete object and child objects
DBCommandWrapper cmDelete = DBUtil.GetCommandFromSQL("DELETE FROM aUnit WHERE aID = @ID;");
cmDelete.AddInParameter("@ID",DbType.Guid,this.mID);
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteAddress = DBUtil.GetCommandFromSQL("DELETE FROM AADDRESS WHERE aRootObjectID = @ID;");
cmDeleteAddress.AddInParameter("@ID",DbType.Guid,this.mID);
//case 3597
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteMeterReading = DBUtil.GetCommandFromSQL("DELETE FROM AUNITMETERREADING WHERE AUNITID = @ID;");
cmDeleteMeterReading.AddInParameter("@ID", DbType.Guid, this.mID);
//case 3605
DBCommandWrapper cmClearFromCSR = DBUtil.GetCommandFromSQL("UPDATE ACLIENTSERVICEREQUEST SET AUNITID = null WHERE AUNITID = @ID");
cmClearFromCSR.AddInParameter("@ID", DbType.Guid, this.mID);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
//case 3597
DBUtil.DB.ExecuteNonQuery(cmDeleteMeterReading, transaction);
//case 3605
DBUtil.DB.ExecuteNonQuery(cmClearFromCSR, transaction);
DBUtil.DB.ExecuteNonQuery(cmDelete, transaction);
DBUtil.DB.ExecuteNonQuery(cmDeleteAddress, transaction);
DBUtil.RemoveKeywords(transaction,RootObjectTypes.Unit,this.mID);
DBUtil.RemoveDocs(transaction,RootObjectTypes.Unit,this.mID);
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
//-----------------------------
}
MarkNew();
return;
}
#endregion
#region Add / Update
//ensure address is empty if set to not have own address
//otherwise it will linger if set to false
//after previously being entered
if(this.mUnitHasOwnAddress==false)
{
this.GoToAddress.City="";
this.GoToAddress.Country="";
this.GoToAddress.CountryCode="";
this.GoToAddress.DeliveryAddress="";
this.GoToAddress.Latitude=0;
this.GoToAddress.Longitude=0;
this.GoToAddress.Postal="";
this.GoToAddress.StateProv="";
}
if(this.mOverrideModelWarranty==false)
{
this.mWarrantyTerms="";
this.mLifeTimeWarranty=false;
this.mWarrantyLength=0;
}
if(this.mLifeTimeWarranty==true)
this.mWarrantyLength=0;
//get modification time temporarily, if update succeeds then
//set to this time
System.DateTime dtModified = DBUtil.CurrentWorkingDateTime;
DBCommandWrapper cm = null;
if(IsNew)//Add or update?
cm=DBUtil.GetCommandFromSQL(
"INSERT INTO aUnit (aID, AACTIVE, aSerial, aNotes, aClientID, " +
"aUnitModelID, aParentUnitID, aUnitHasOwnAddress, " +
"aOverrideModelWarranty, aBoughtHere, aPurchasedFromID, " +
"aReceipt, aPurchasedDate, aWarrantyTerms, aDescription, " +
"aReplacedByUnitID, aCreated,aModified,aCreator,aModifier, " +
"aCustom1, aCustom2, aCustom3, aCustom4, aCustom5, " +
"aCustom6, aCustom7, aCustom8, aCustom9, aCustom0, " +
"aUsesBanking, aMetered, aWarrantyLength, aLifeTimeWarranty,aText1, aText2, aText3, aText4) " +
"VALUES (@ID,@Active,@Serial,@Notes, " +
"@ClientID, " +
"@UnitModelID,@ParentUnitID,@UnitHasOwnAddress,@OverrideModelWarranty, " +
"@BoughtHere,@PurchasedFromID, " +
"@Receipt,@PurchasedDate,@WarrantyTerms, @Description, " +
"@ReplacedByUnitID,@Created,@Modified,@CurrentUserID,@CurrentUserID, " +
"@Custom1,@Custom2,@Custom3,@Custom4,@Custom5,@Custom6, " +
"@Custom7,@Custom8,@Custom9,@Custom0, @UsesBanking, " +
"@Metered,@WarrantyLength,@LifeTimeWarranty,@Text1,@Text2,@Text3,@Text4)"
);
else
cm=DBUtil.GetCommandFromSQL(
"UPDATE aUnit SET aID=@ID, AACTIVE=@Active, aSerial=@Serial, " +
"aNotes=@Notes, aClientID=@ClientID, " +
"aUnitModelID=@UnitModelID, " +
"aParentUnitID=@ParentUnitID, aUnitHasOwnAddress=@UnitHasOwnAddress, " +
"aOverrideModelWarranty=@OverrideModelWarranty, " +
"aWarrantyTerms=@WarrantyTerms, " +
"aBoughtHere=@BoughtHere, aPurchasedFromID=@PurchasedFromID, " +
"aReceipt=@Receipt, aPurchasedDate=@PurchasedDate, " +
"aDescription=@Description, aReplacedByUnitID=@ReplacedByUnitID, " +
"aModifier=@CurrentUserID, " +
"aModified=@Modified, " +
"aCustom1=@Custom1, " +
"aCustom2=@Custom2, aCustom3=@Custom3, aCustom4=@Custom4, " +
"aCustom5=@Custom5, aCustom6=@Custom6, " +
"aCustom7=@Custom7, aCustom8=@Custom8, aCustom9=@Custom9, " +
"aCustom0=@Custom0, aUsesBanking=@UsesBanking, " +
"aMetered=@Metered, aLifeTimeWarranty=@LifeTimeWarranty, " +
"aWarrantyLength=@WarrantyLength, " +
"aText1=@Text1, aText2=@Text2, aText3=@Text3, aText4=@Text4 " +
"WHERE aID=@ID"
);
//Unit specific fields
cm.AddInParameter("@ID",DbType.Guid,mID);
cm.AddInParameter("@Active",DbType.Boolean, mActive);
cm.AddLargeStringInParameter("@Notes", mNotes);
cm.AddInParameter("@Serial",DbType.String, mSerial);
cm.AddInParameter("@UsesBanking",DbType.Boolean, mUsesBanking);
cm.AddInParameter("@BoughtHere",DbType.Boolean,mBoughtHere);
cm.AddInParameter("@ClientID",DbType.Guid, mClientID);
cm.AddInParameter("@OverrideModelWarranty",DbType.Boolean,mOverrideModelWarranty);
cm.AddInParameter("@WarrantyTerms",DbType.String,mWarrantyTerms);
cm.AddInParameter("@Description",DbType.String,mDescription);
cm.AddInParameter("@PurchasedDate",DbType.DateTime,DBUtil.ToUTC(mPurchasedDate).DBValue);
cm.AddInParameter("@PurchasedFromID",DbType.Guid, mPurchasedFromID);
cm.AddInParameter("@Receipt",DbType.String,mReceipt);
cm.AddInParameter("@ReplacedByUnitID",DbType.Guid, mReplacedByUnitID);
cm.AddInParameter("@UnitHasOwnAddress",DbType.Boolean,mUnitHasOwnAddress);
cm.AddInParameter("@UnitModelID",DbType.Guid, mUnitModelID);
cm.AddInParameter("@ParentUnitID",DbType.Guid, mParentUnitID);
cm.AddInParameter("@Metered",DbType.Boolean,mMetered);
cm.AddInParameter("@WarrantyLength",DbType.Int32,mWarrantyLength);
cm.AddInParameter("@LifeTimeWarranty",DbType.Boolean,mLifeTimeWarranty);
//case 78
cm.AddInParameter("@Text1", DbType.String, mText1);
cm.AddInParameter("@Text2", DbType.String, mText2);
cm.AddInParameter("@Text3", DbType.String, mText3);
cm.AddInParameter("@Text4", DbType.String, mText4);
//Standard fields
//case 1687 need this to do a biz object update in the schema update
//because the user hasn't logged in yet and Unit table doesn't allow nulls in
//modified user id
Guid gCurrentUserId = CurrentUserID;
if (gCurrentUserId == Guid.Empty)
gCurrentUserId = User.AdministratorID;
cm.AddInParameter("@CurrentUserID", DbType.Guid, gCurrentUserId);
cm.AddInParameter("@Created",DbType.DateTime, DBUtil.ToUTC(mCreated).DBValue);
cm.AddInParameter("@Modified",DbType.DateTime, DBUtil.ToUTC(dtModified));
//Custom fields
cm.AddLargeStringInParameter("@Custom1", mCustom1);
cm.AddLargeStringInParameter("@Custom2", mCustom2);
cm.AddLargeStringInParameter("@Custom3", mCustom3);
cm.AddLargeStringInParameter("@Custom4", mCustom4);
cm.AddLargeStringInParameter("@Custom5", mCustom5);
cm.AddLargeStringInParameter("@Custom6", mCustom6);
cm.AddLargeStringInParameter("@Custom7", mCustom7);
cm.AddLargeStringInParameter("@Custom8", mCustom8);
cm.AddLargeStringInParameter("@Custom9", mCustom9);
cm.AddLargeStringInParameter("@Custom0", mCustom0);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
DBUtil.DB.ExecuteNonQuery(cm, transaction);
//Update child objects
//GoToAddress
mGoToAddress.Update(RootObjectTypes.Unit,mID,AddressTypes.Physical,transaction);
//Docs
mDocs.Update(transaction);
//Process keywords
DBUtil.ProcessKeywords(transaction,this.mID,RootObjectTypes.Unit,IsNew,AyaBizUtils.Break(false,
mGoToAddress.FullAddress,mNotes,mSerial,mDescription,mReceipt,mWarrantyTerms,
/*Custom fields*/
mCustom1,mCustom2,mCustom3,mCustom4,mCustom5,mCustom6,mCustom7,mCustom8,mCustom9,mCustom0, mText1, mText2, mText3, mText4));
MarkOld();//db is now synched with object
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
//Successful update so
//change modification time to match
this.mModified.Date=dtModified;
if(AyaBizUtils.AllowAutomaticMRUOnUpdate) AyaBizUtils.MRU.Add(RootObjectTypes.Unit, mID);
}
#endregion
}
#endregion update
#region Delete
/// <summary>
/// Remove a Unit record .
/// </summary>
/// <param name="Criteria"></param>
protected override void DataPortal_Delete(object Criteria)
{
Criteria crit = (Criteria)Criteria;
//Delete object and child objects
DBCommandWrapper cmDelete = DBUtil.GetCommandFromSQL("DELETE FROM aUnit WHERE aID = @ID;");
cmDelete.AddInParameter("@ID",DbType.Guid,crit.ID);
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteAddress = DBUtil.GetCommandFromSQL("DELETE FROM AADDRESS WHERE aRootObjectID = @ID;");
cmDeleteAddress.AddInParameter("@ID",DbType.Guid,crit.ID);
//case 3597
//Delete all address record types with matching root object ID
DBCommandWrapper cmDeleteMeterReading = DBUtil.GetCommandFromSQL("DELETE FROM AUNITMETERREADING WHERE AUNITID = @ID;");
cmDeleteMeterReading.AddInParameter("@ID", DbType.Guid, crit.ID);
//case 3605
DBCommandWrapper cmClearFromCSR = DBUtil.GetCommandFromSQL("UPDATE ACLIENTSERVICEREQUEST SET AUNITID = null WHERE AUNITID = @ID");
cmClearFromCSR.AddInParameter("@ID", DbType.Guid, crit.ID);
using (IDbConnection connection = DBUtil.DB.GetConnection())
{
connection.Open();
IDbTransaction transaction = connection.BeginTransaction();
try
{
//case 3597
DBUtil.DB.ExecuteNonQuery(cmDeleteMeterReading, transaction);
//case 3605
DBUtil.DB.ExecuteNonQuery(cmClearFromCSR, transaction);
DBUtil.DB.ExecuteNonQuery(cmDelete, transaction);
DBUtil.DB.ExecuteNonQuery(cmDeleteAddress, transaction);
DBUtil.RemoveKeywords(transaction,RootObjectTypes.Unit,crit.ID);
DBUtil.RemoveDocs(transaction,RootObjectTypes.Unit,crit.ID);
// Commit the transaction
transaction.Commit();
}
catch
{
// Rollback transaction
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
AyaBizUtils.MRU.Remove(RootObjectTypes.Unit, crit.ID);
}
}
#endregion delete
#endregion
#region Override IsValid / IsDirty
//Override base class version if there are child objects
/// <summary>
/// No broken rules
/// </summary>
public override bool IsValid
{
get
{
return base.IsValid && mGoToAddress.IsValid && mDocs.IsValid ;
}
}
/// <summary>
/// Has unsaved changes
/// </summary>
public override bool IsDirty
{
get
{
return base.IsDirty || mGoToAddress.IsDirty || mDocs.IsDirty ;
}
}
#endregion
#region criteria
/// <summary>
/// Criteria for identifying existing object
/// </summary>
[Serializable]
private class Criteria
{
public Guid ID;
public bool TrackMRU;
public Criteria(Guid _ID, bool _TrackMRU)
{
ID = _ID;
TrackMRU = _TrackMRU;
}
}
#endregion
#region Get current meter reading from unit id
//Case 501
//[Serializable(), System.ComponentModel.Browsable(false)]
// public class MeterHelper
//{
// long _Meter = 0;
// Guid _ID;
// public MeterHelper(Guid ID)
// {
// _ID=ID;
// }
// public static long GetMeter(Guid ID)
// { //todo fix for 425
// MeterHelper e=new MeterHelper(ID);
// DataPortal.Update(e);
// return e._Meter;
// }
// public void DataPortal_Update()
// {
// switch(DBUtil.DB.DBType)
// {
// case DataBaseType.FireBird:
// {
// this._Meter=DBUtil.ScalarToLong(
// DBUtil.GetScalarFromSQLString(
// "SELECT FIRST 1 aMeter FROM aUnitMeterReading WHERE " +
// "(aUnitMeterReading.aUnitID = @ID) " +
// "ORDER BY aCreated DESC ",_ID)
// );
// }
// break;
// case DataBaseType.MSSQL:
// {
// this._Meter=DBUtil.ScalarToLong(
// DBUtil.GetScalarFromSQLString(
// "SELECT TOP 1 aMeter FROM aUnitMeterReading WHERE " +
// "(aUnitMeterReading.aUnitID = @ID) " +
// "ORDER BY aCreated DESC ",_ID)
// );
// }
// break;
// default:
// throw new ApplicationException("UNKNOWN DB TYPE IN Unit.MeterHelper");
// }
// }
//}
#endregion
#region Get Unit metered status from unit id
//Case 502
////Added:25-Oct-2006 to support wbi
// [Serializable(), System.ComponentModel.Browsable(false)]
// public class MeteredHelper
// {
// bool _Metered = false;
// Guid _ID;
// public MeteredHelper(Guid ID)
// {
// _ID = ID;
// }
// public static bool GetMetered(Guid ID)
// { //todo fix for 425
// MeteredHelper e = new MeteredHelper(ID);
// DataPortal.Update(e);
// return e._Metered;
// }
// public void DataPortal_Update()
// {
// this._Metered = DBUtil.ScalarToBool(
// DBUtil.GetScalarFromSQLString(
// "SELECT aMetered FROM aUnit WHERE " +
// "(aUnit.aID = @ID) " , _ID)
// );
// }
// }
#endregion
#region Exists Case 421
//Case 503
//[Serializable(), System.ComponentModel.Browsable(false)]
//public class ExistsHelper
//{
// bool _Exists = false;
// Guid _ID;
// string _SerialNumber;
// public ExistsHelper(Guid ID, string SerialNumber)
// {
// _ID = ID;
// _SerialNumber = SerialNumber;
// }
// public static bool GetExists(Guid ID, string SerialNumber)
// { //todo fix for 425
// ExistsHelper e = new ExistsHelper(ID, SerialNumber);
// DataPortal.Update(e);
// return e._Exists;
// }
// public void DataPortal_Update()
// {
// if (!string.IsNullOrEmpty(_SerialNumber))
// {
// DBCommandWrapper dbCommandWrapper = DBUtil.DB.GetSqlStringCommandWrapper(
// "SELECT aID FROM aUnit WHERE " +
// "(aSerial = @SERIAL)"
// );
// dbCommandWrapper.AddInParameter("@SERIAL", DbType.String, _SerialNumber);
// if (DBUtil.ToGuid(DBUtil.DB.ExecuteScalar(dbCommandWrapper)) == Guid.Empty)
// this._Exists = false;
// else
// this._Exists = true;
// }
// else
// {
// if (DBUtil.ToGuid(DBUtil.GetScalarFromSQLString(
// "SELECT aID FROM aUnit WHERE " +
// "(aID = @ID)", _ID
// )) == Guid.Empty)
// this._Exists = false;
// else
// this._Exists = true;
// }
// }
//}
#endregion
}//end Unit
}//end namespace GZTW.AyaNova.BLL