code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
using System; using System.Collections.Generic; using System.Text; namespace Zzva.Common { public abstract class TProgress { protected TProgressBar mvarProgressBar; protected TProgressMen mvarFather; public TProgress(TProgressBar pProgressBar, TProgressMen pFather) { mvarProgressBar = pProgressBar; mvarFather = pFather; } public virtual void SetMess(string Mess) { } public virtual void SetPosition(string Mess) { } } public class TProgressMainControlNot : TProgress { public TProgressMainControlNot(TProgressBar pProgressBar, TProgressMen pFather) : base(pProgressBar, pFather) { } public override void SetMess(string Mess) { mvarProgressBar.lblMessMain.Text = Mess; } } public class TProgressMen { public static TProgressBar mvarProgressBar; public static void GetProgress() { } } }
zzvalib
trunk/Common/Zzva.Common/Progress.cs
C#
bsd
1,165
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObjectReg { public class TFilterValue { public string FieldObozn; public string FilterTemplate; public TFilterValue(string pFieldObozn, string pFilterTemplate) { FieldObozn = pFieldObozn; FilterTemplate = pFilterTemplate; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/TFilterValue.cs
C#
bsd
436
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObjectReg { public class TAliasForField { public string Obozn; public string Alias; public TAliasForField(string pObozn, string pAlias) { Obozn = pObozn; Alias = pAlias; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/TAliasForField.cs
C#
bsd
383
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObjectReg { public class TSortValue { public string FieldObozn; public ESortType SortType; public TSortValue(string pFieldObozn, ESortType pSortType) { FieldObozn = pFieldObozn; SortType = pSortType; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/TSortValue.cs
C#
bsd
413
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.DomainObjectReg")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.DomainObjectReg")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("58009b05-7726-464f-911e-2a4a7a7ca094")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Properties/AssemblyInfo.cs
C#
bsd
1,460
using System; namespace Zzva.DomainObjectReg { // Типы сортировки public enum ESortType { //Forward OrderForward = 0, // Backward OrderBackward = 1, } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/ESortType.cs
C#
bsd
243
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Zzva.DomainObject; using Zzva.Common; using Zzva.ESB; namespace Zzva.DomainObjectReg { public abstract class TRegDirBase { //protected Collection<TDirBase> mvarListDir; protected Collection<TDirBase> mvarFullListDir; protected TSortValue mvarSortValue; protected Collection<TFilterValue> mvarListFilter; protected TDirBase mvarCurItem; public event EventHandler EventFindDir; public event EventHandler EventUpdateList; //// //Флаг синхронизации текщего листа с текущим состоянием //рассинхронизация происходит при //добавлении, изменении, удалениии (именяются итемы) //изменению соритровке и фильтрации protected bool mvarFlgSinhroCurListAndCurState; private Collection<TDirBase> mvarCurListDir; //// //Возвращает текущее представление справочника с учетом фильта и сортировки //// protected Collection<TDirBase> GetCurList() //// { //// try //// { //// Collection<TDirBase> lCurList = new Collection<TDirBase>(); //// IEnumerable<TDirBase> hhh = null; //// //// //Sort //// hhh = OrderListBySetSort(hhh); //// //// //Filter //// hhh = SelectListBySetFilter(hhh); //// foreach (TDirBase h in hhh) { lCurList.Add(h); } //// return lCurList; //// } //// catch (Exception e) { throw e; } //// finally { } //// } //Возвращает текущее представление справочника с учетом фильта и сортировки protected Collection<TDirBase> GetCurList() { try { if (mvarFlgSinhroCurListAndCurState == false) { Collection<TDirBase> lCurList = new Collection<TDirBase>(); IEnumerable<TDirBase> hhh = null; //Sort hhh = OrderListBySetSort(hhh); //Filter hhh = SelectListBySetFilter(hhh); foreach (TDirBase h in hhh) { lCurList.Add(h); } mvarCurListDir = lCurList; mvarFlgSinhroCurListAndCurState = true; } return mvarCurListDir; } catch (Exception e) { throw e; } finally { } } #region Filter... public virtual void FilterDel() { try { mvarListFilter.Clear(); //// mvarFlgSinhroCurListAndCurState = false; Collection<TDirBase> lCurList; lCurList = GetCurList(); TDirBase lFirstItem; lFirstItem = GetFirstItem(lCurList); mvarCurItem = lFirstItem; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } public virtual void FilterAdd(TFilterValue pFilterValue) { try { if (pFilterValue.FilterTemplate.Trim() != "")//Фильтр с пустой строкой игнорируются { //Изменяем алиас на код поля TFilterValue lFilterValue; string lFieldObozn; lFieldObozn = GetColumnOboznByAlias(pFilterValue.FieldObozn); if (lFieldObozn == "") { throw (new CommonException("Нет обозначения по алиасу")); } lFilterValue = new TFilterValue(lFieldObozn, pFilterValue.FilterTemplate); mvarListFilter.Add(lFilterValue); //// mvarFlgSinhroCurListAndCurState = false; Collection<TDirBase> lCurList; lCurList = GetCurList(); TDirBase lFirstItem; lFirstItem = GetFirstItem(lCurList); mvarCurItem = lFirstItem; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } } catch (Exception e1) { throw e1; } finally { } } #endregion public virtual void Sort(TSortValue pSortValue) { try { //Изменяем алиас на код поля TSortValue lSortValue; string lFieldObozn; lFieldObozn = GetColumnOboznByAlias(pSortValue.FieldObozn); if (lFieldObozn == "") { throw (new CommonException("Нет обозначения по алиасу")); } lSortValue = new TSortValue(lFieldObozn, pSortValue.SortType); mvarSortValue = lSortValue; //// mvarFlgSinhroCurListAndCurState = false; Collection<TDirBase> lCurList; lCurList = GetCurList(); TDirBase lFirstItem; lFirstItem = GetFirstItem(lCurList); mvarCurItem = lFirstItem; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } #region Constructors.... protected TRegDirBase(Collection<TDirBase> pFullListDir) { try { mvarFullListDir = pFullListDir; //!!!!!!!!!!!!!!!!!!!!!! //Фильтр по умолчанию вернуть из усстановок а пока так mvarListFilter = new Collection<TFilterValue>(); //!!!!!!!!!!!!!!!!!!!!!! //Здесь сорт валуе по умолчанию вернуть надо и з установок а пока так mvarSortValue = new TSortValue("Obozn", ESortType.OrderForward); //// mvarFlgSinhroCurListAndCurState = false; //Вызывается список с учетом сртировки и фильтрации по умолчанию Collection<TDirBase> lCurList; lCurList = GetCurList(); //И устанавливается текущая запись по умолчанию TDirBase lFirstItem; lFirstItem = GetFirstItem(lCurList); mvarCurItem = lFirstItem; } catch (Exception e1) { throw e1; } finally { } } #endregion #region (Примеры использования делегата public delegate TResult Func<T, TResult>(T arg)) в операциях LINQ //1 метод - делегат внешняя функция //Func<TDirITCompany, string> lSelector = TestDelegateFuncGetSelector; //var hhh = mvarListDir.OrderBy(lSelector); //2 метод - делегат внешняя функция //Func<TDirITCompany, string> lSelector; //lSelector = TestDelegateFuncGetSelector; //var hhh = mvarListDir.OrderBy(lSelector); //3 метод с использованием анонимной фукнкции //Func<TDirITCompany, string> lSelector; //lSelector = delegate(TDirITCompany lDirITCompany) //{ // return lDirITCompany.Obozn; //}; // //var hhh = mvarListDir.OrderBy(lSelector); //4 метод с использованием анонимной фукнкции //Func<TDirITCompany, string> lSelector = delegate(TDirITCompany lDirITCompany) //{ // return lDirITCompany.Obozn; //}; // //var hhh = mvarListDir.OrderBy(lSelector); //5 метод с использованием лямбада выражения в описании функции //Func<TDirITCompany, string> lSelector = h => h.Obozn; //var hhh = mvarListDir.OrderBy(lSelector); //6 метод с использованием лямбада выражения в описании функции //Func<TDirITCompany, string> lSelector; //lSelector = h => h.Obozn; //var hhh = mvarListDir.OrderBy(lSelector); //7метод с использованием лямбада выражения в описании функции //Func<TDirITCompany, string> lSelector; //lSelector = h => //{ // string k = h.Obozn; // return k; //}; //var hhh = mvarListDir.OrderBy(lSelector); //8метод с использованием лямбада выражения в описании функции //var hhh = mvarListDir.OrderBy(h => h.Obozn); #endregion public string TitleFull { get { try { string lTitleFull; string lListFilterToString; lListFilterToString = ListFilterToString; if (lListFilterToString == "") { lTitleFull = Title; } else { lTitleFull = Title + ": " + lListFilterToString; } return lTitleFull; } catch (Exception e1) { throw e1; } finally { } } } protected string ListFilterToString { get { try { string lListFilterToString = ""; int lIndex = 0; if (mvarListFilter.Count != 0) { foreach (TFilterValue lFilterValue in mvarListFilter) { if (lIndex == 0){lListFilterToString = lFilterValue.FilterTemplate;} else{lListFilterToString = lListFilterToString + " + " + lFilterValue.FilterTemplate;} lIndex = lIndex + 1; } } return lListFilterToString; } catch (Exception e1) { throw e1; } finally { } } } //// //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону //// protected virtual TDirBase FindLastDirInList //// (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) //// { //// try //// { //// TDirBase lDirBase; //// lDirBase = null; //// //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (pFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.LastOrDefault(lPredicate); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.LastOrDefault(lPredicate); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.LastOrDefault(lPredicate); //// break; //// default: //// break; //// } //// return lDirBase; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону private TDirBase FindLastDirInList (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) { try { TDirBase lDirBase = null; //готовим делегата условия Func<TDirBase, bool> lPredicate = null; lPredicate = d => d.GetAttrib(pFieldObozn).ToString().ToLower().Contains(pFieldTemplate.ToLower()); lDirBase = pList.LastOrDefault(lPredicate); return lDirBase; } catch (Exception e1) { throw e1; } finally { } } //// //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону //// protected virtual TDirBase FindFirstDirInList //// (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) //// { //// try //// { //// TDirBase lDirBase; //// lDirBase = null; //// //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (pFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.FirstOrDefault(lPredicate); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.FirstOrDefault(lPredicate); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.FirstOrDefault(lPredicate); //// break; //// default: //// //throw (new CommonException("Нет такого поля")); //// break; //// } //// //// //lDirBase = pList.FirstOrDefault(lPredicate); //// //// return lDirBase; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону private TDirBase FindFirstDirInList (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) { try { TDirBase lDirBase = null; //готовим делегата условия Func<TDirBase, bool> lPredicate = null; lPredicate = d => d.GetAttrib(pFieldObozn).ToString().ToLower().Contains(pFieldTemplate.ToLower()); lDirBase = pList.FirstOrDefault(lPredicate); return lDirBase; } catch (Exception e1) { throw e1; } finally { } } //// //Фильтруе заданный список по установленному фильтру //// protected virtual IEnumerable<TDirBase> SelectListBySetFilter(IEnumerable<TDirBase> pList) //// { //// try //// { //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// //// if (mvarListFilter.Count != 0) //Есть фильтр //// { //// foreach (TFilterValue k in mvarListFilter) //// { //// switch (k.FieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(k.FilterTemplate.ToLower()); //// //pList = pList.Where(lPredicate); //// pList = pList.Where(lPredicate).ToList(); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(k.FilterTemplate.ToLower()); //// //pList = pList.Where(lPredicate); //// pList = pList.Where(lPredicate).ToList(); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(k.FilterTemplate.ToLower()); //// //pList = pList.Where(lPredicate); //// pList = pList.Where(lPredicate).ToList(); //// break; //// default: //// break; //// } //// //pList = pList.Where(lPredicate); //// } //// } //// return pList; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //Фильтруе заданный список по установленному фильтру private IEnumerable<TDirBase> SelectListBySetFilter(IEnumerable<TDirBase> pList) { try { //готовим делегата условия Func<TDirBase, bool> lPredicate; lPredicate = null; if (mvarListFilter.Count != 0) //Есть фильтр { foreach (TFilterValue k in mvarListFilter) { lPredicate = d => d.GetAttrib(k.FieldObozn).ToString().ToLower().Contains(k.FilterTemplate.ToLower()); pList = pList.Where(lPredicate).ToList(); } } return pList; } catch (Exception e1) { throw e1; } finally { } } //По заданному алиасу поля возвращает список уникальных значений из текущего списка public Collection<string> GetListUniqueValueForAliasField(string pAlias) { try { string pObozn; Collection<string> lListValue; pObozn = GetColumnOboznByAlias(pAlias); Collection<TDirBase> lCurList = GetCurList(); var hhh = lCurList.Select(h => h.GetAttrib(pObozn).ToString()) .Distinct() .OrderBy(k => k); lListValue = new Collection<string>(); foreach (string lFieldValue in hhh){lListValue.Add(lFieldValue);} return lListValue; } catch (Exception e1) { throw e1; } finally { } } public virtual string Title {get{return "Имя справочника не определено";}} #region Find... //Ищет элемент справочника по объекту и делает его текущим //при вызове справочника в контексте элемента документа // Поиск начианется с первой ячейки вниз списка //Если не находит, остается на текущей ячейке public virtual void FindByDir(TDirBase pDir) { try { TDirBase lDirBase; Collection<TDirBase> lCurList; ////string lFieldObozn; ////string lFindTemplate; TDirFindEventArgs lDirFindEventArgs; lCurList = GetCurList(); //готовим делегата условия Func<TDirBase, bool> lPredicate; ////lPredicate = d => d == pDir; ////lPredicate = d => d.Obozn == pDir.Obozn; lPredicate = d => d.Equals(pDir); lDirBase = lCurList.FirstOrDefault(lPredicate); if (lDirBase != null) { mvarCurItem = lDirBase; lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); } else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } FireEventFindDir(lDirFindEventArgs); } catch (Exception e1) { throw e1; } finally { } } //Находит ячейку с заданным критерием в текущем списке и делает ее текущей // Поиск начианется с текущей ячейки вниз списка //Если не находит, остается на текущей ячейке public void FindNext(TFilterValue lFindValue) { try { TDirBase lDirBase; Collection<TDirBase> lCurList; string lFieldObozn; string lFindTemplate; TDirFindEventArgs lDirFindEventArgs; //lFieldObozn = lFindValue.FieldObozn; lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } lFindTemplate = lFindValue.FilterTemplate; if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } lCurList = GetCurList(); //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (lFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } int lCurItemIndex; lCurItemIndex = GetCurItemIndex(); if (lCurItemIndex == -1) { lDirFindEventArgs = new TDirFindEventArgs(false, null); }//вообще нет записей -> негде искать else { var hhh = lCurList.Skip(lCurItemIndex + 1);// обрезаем сверху от текущей записис ////lDirBase = hhh.FirstOrDefault(lPredicate); lDirBase = FindFirstDirInList(lFieldObozn, lFindTemplate, hhh); if (lDirBase != null) { mvarCurItem = lDirBase; lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); } else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } } FireEventFindDir(lDirFindEventArgs); } catch (Exception e1) { throw e1; } finally { } } //Находит ячейку с заданным критерием в текущем списке и делает ее текущей // Поиск начианется с текущей ячейки вверх списка //Если не находит, остается на текущей ячейке public void FindPrev(TFilterValue lFindValue) { try { TDirBase lDirBase; Collection<TDirBase> lCurList; string lFieldObozn; string lFindTemplate; TDirFindEventArgs lDirFindEventArgs; //lFieldObozn = lFindValue.FieldObozn; lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } lFindTemplate = lFindValue.FilterTemplate; if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } lCurList = GetCurList(); //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (lFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } int lCurItemIndex; lCurItemIndex = GetCurItemIndex(); if (lCurItemIndex == -1) { lDirFindEventArgs = new TDirFindEventArgs(false, null); }//вообще нет записей -> негде искать else { var hhh = lCurList.Take(lCurItemIndex);// обрезаем снизу от текущей записис ////lDirBase = hhh.LastOrDefault(lPredicate); lDirBase = FindLastDirInList(lFieldObozn, lFindTemplate, hhh); if (lDirBase != null) { mvarCurItem = lDirBase; lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); } else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } } FireEventFindDir(lDirFindEventArgs); } catch (Exception e1) { throw e1; } finally { } } //Находит ячейку с заданным критерием в текущем списке и делает ее текущей // Поиск начианется с первой ячейки вниз списка //Если не находит, остается на текущей ячейке public void Find(TFilterValue lFindValue) { try { TDirBase lDirBase; Collection<TDirBase> lCurList; string lFieldObozn; string lFindTemplate; TDirFindEventArgs lDirFindEventArgs; lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } lFindTemplate = lFindValue.FilterTemplate; if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } lCurList = GetCurList(); // //готовим делегата условия // Func<TDirBase, bool> lPredicate; // lPredicate = null; // switch (lFieldObozn) // { // case "Id": // lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); // break; // case "Obozn": // lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); // break; // case "Naim": // lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); // break; // default: // throw (new CommonException("Нет такого поля")); // } // // lDirBase = lCurList.FirstOrDefault(lPredicate); lDirBase = FindFirstDirInList(lFieldObozn, lFindTemplate, lCurList); if (lDirBase != null) { mvarCurItem = lDirBase; lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); } else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } FireEventFindDir(lDirFindEventArgs); } catch (Exception e1) { throw e1; } finally { } } #endregion //Упорядочивем заданный список по установленной сортировке private IEnumerable<TDirBase> OrderListBySetSort(IEnumerable<TDirBase> pList) { try { Func<TDirBase, object> lSelector; lSelector = d => { object k = d.GetAttrib(mvarSortValue.FieldObozn); return k; }; if (mvarSortValue.SortType == ESortType.OrderForward) { pList = FullListDir.OrderBy(lSelector); } else if ((mvarSortValue.SortType == ESortType.OrderBackward)) { pList = FullListDir.OrderByDescending(lSelector); } else { throw (new CommonException("Нет типа сортировки")); } return pList; } catch (Exception e1) { throw e1; } finally { } } //// public void Delete() //// { //// try //// { //// TDirBase lCurDir; //// Collection<TDirBase> lCurListDir; //// int lIdAfterDelete; //// //// lCurListDir = GetCurList(); //// lCurDir = GetCurItem(); //// //// lIdAfterDelete = GetIdAfterDelete(lCurDir, lCurListDir); //// //// if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } //// //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; //// Esb.DeleteITCompany(ref lDirITCompanyBase); //// TDirITCompanyNull lDirITCompanyNull = (TDirITCompanyNull)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// //// Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); //// foreach (TDirITCompany h in lListDir){lListDirBase.Add((TDirBase)h);} //// //// TDirBase lCurItem; //// if (lIdAfterDelete > 0) { lCurItem = GetItemById(lIdAfterDelete, lListDirBase); } //// else if (lIdAfterDelete == 0) { lCurItem = null; } //// else if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } //// else { throw (new CommonException("Нет значения возврата для GetIdAfterDelete")); } //// //// mvarFullListDir = lListDirBase; //// mvarCurItem = lCurItem; //// //// //дальше здесь событие что обновлено //// FireEventUpdateList(EventArgs.Empty); //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Редактирует текущую элемент справочника, на вход объект TDirITCompanyNew с новыми знвчениями текщей записи //// public virtual void Edit(TDirITCompanyNew pDir) //// { //// try //// { //// TDirBase lCurDir; //// //// //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //// //Тут бы желательно открыть транзакцию //// //// lCurDir = this.GetCurItem(); //// lCurDir.Obozn = pDir.Obozn; //// lCurDir.Naim = pDir.Naim; //// //// //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; //// Esb.SaveITCompany(ref lDirITCompanyBase); //// TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// //// Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); //// foreach (TDirITCompany h in lListDir) //// { //// lListDirBase.Add((TDirBase)h); //// } //// //// TDirBase lCurItem; //// lCurItem = GetItemById(lDirITCompany.Id, lListDirBase); //// //// mvarFullListDir = lListDirBase; //// mvarCurItem = lCurItem; //// //// //дальше здесь событие что обновлено //// FireEventUpdateList(EventArgs.Empty); //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Добавляет элемент справочника и делает его текущим //// public virtual void Add(TDirITCompanyNew pDir) //// { //// try //// { //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)pDir; //// Esb.SaveITCompany(ref lDirITCompanyBase); //// TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// //// //// //// Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); //// foreach (TDirITCompany h in lListDir) //// { //// lListDirBase.Add((TDirBase)h); //// } //// //// //// //// //// TDirBase lCurItem; //// lCurItem = GetItemById(lDirITCompany.Id, lListDirBase); //// //// mvarFullListDir = lListDirBase; //// mvarCurItem = lCurItem; //// //// //дальше здесь событие что обновлено //// ////if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// FireEventUpdateList(EventArgs.Empty); //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //Проверяет наличие функции у делегата public bool CheckEventUpdateListIsNull() { if (EventUpdateList == null) { return true; } else { return false; } } //Проверяет наличие функции у делегата public bool CheckEventFindDirIsNull() { if (EventFindDir == null) { return true; } else { return false; } } protected virtual void FireEventFindDir(TDirFindEventArgs pDirFindEventArgs) { try { if (EventFindDir != null) EventFindDir(this, pDirFindEventArgs); } catch (Exception e1) { throw e1; } finally { } } protected virtual void FireEventUpdateList(EventArgs pUpdateListEventArgs) { try { if (EventUpdateList != null) EventUpdateList(this, pUpdateListEventArgs); } catch (Exception e1) { throw e1; } finally { } } //Возвращает элемент коллекции по значению идентификатора protected TDirBase GetItemById(int pId, Collection<TDirBase> pListDir) { try { TDirBase hhh = pListDir.SingleOrDefault(r => r.Id == pId); return hhh; } catch (Exception e1) { throw e1; } finally { } } public virtual void SetCurItem(int pId) { try { Collection<TDirBase> lCurList; TDirBase lCurItem; lCurList = GetCurList(); lCurItem = lCurList.Single(p => p.Id == pId); mvarCurItem = lCurItem; } catch (Exception e) { throw e; } finally { } } //Возвращает ИД следующего после удаления текущего элемента protected int GetIdAfterDelete(TDirBase pDir, Collection<TDirBase> pListDir) { try { int lIndex; int Result; TDirBase lAfterDeleteDir; lIndex = pListDir.IndexOf(pDir); if (lIndex == -1) { Result = -1; }//нет исходного объекта в коллекции else { lAfterDeleteDir = pListDir.ElementAtOrDefault(lIndex + 1); if (lAfterDeleteDir == null) { lAfterDeleteDir = pListDir.ElementAtOrDefault(lIndex - 1); if (lAfterDeleteDir == null) { Result = 0; }//Нет объектов после удаления} else { Result = lAfterDeleteDir.Id; }//Возвращаем предыдйущий объект} } else { Result = lAfterDeleteDir.Id; }//возвращаем следующий объект } return Result; } catch (Exception e1) { throw e1; } finally { } } //Возвращает индекс текущего итема в текущей последовательности //если нет текущего итема возвращает -1 // 0 это превыйэлемент последоватедьности (для справки) protected int GetCurItemIndex() { try { int lIndex; int lResult; Collection<TDirBase> lCurList; TDirBase lCurItem; lCurItem = GetCurItem(); if (lCurItem == null) { lResult = -1; } else { lCurList = GetCurList(); lIndex = lCurList.IndexOf(lCurItem); if (lIndex == -1) { throw (new CommonException("Текущий элемент не найден")); } else { lResult = lIndex; } } return lResult; } catch (Exception e1) { throw e1; } finally { } } //Возвращает текущий элемент public TDirBase GetCurItem() { return mvarCurItem; } //Возвращает первый элемент protected TDirBase GetFirstItem(Collection<TDirBase> pListDir) { try { TDirBase lDirBase; ////lDirITCompany = pListDir.First(); lDirBase = pListDir.FirstOrDefault(); return lDirBase; } catch (Exception e1) { throw e1; } finally { } } //Возвращает представление для клиента public virtual object GetCurListView() { try { Collection<TDirBase> lCurrentList = GetCurList(); var hhh = lCurrentList.Select(p => new { Id = p.Id, Обозначение = p.Obozn, Наименование = p.Naim, }).ToList(); return hhh; } catch (Exception e1) { throw e1; } finally { } } protected Collection<TDirBase> FullListDir { get{return mvarFullListDir;} } protected TEsb Esb { get { try { return TEsb.GetEsb(); } catch (Exception e) { throw e; } finally { } } } protected string GetColumnOboznByAlias(string pAlias) { try { TAliasForField lOboznAndAlias; string lObozn; Collection<TAliasForField> lListOboznAndAlias = GetListOboznAndAlias(); lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Alias == pAlias); if (lOboznAndAlias != null) { lObozn = lOboznAndAlias.Obozn; } else { lObozn = ""; } return lObozn; } catch (Exception e1) { throw e1; } finally { } } protected virtual Collection<TAliasForField> GetListOboznAndAlias() { Collection<TAliasForField> lList; lList = new Collection<TAliasForField>(); lList.Add(new TAliasForField("Id", "Id")); lList.Add(new TAliasForField("Obozn", "Обозначение")); lList.Add(new TAliasForField("Naim", "Наименование")); return lList; } protected string GetColumnAliasByObozn(string pObozn) { try { TAliasForField lOboznAndAlias; string lAlias; Collection<TAliasForField> lListOboznAndAlias = GetListOboznAndAlias(); lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Obozn == pObozn); if (lOboznAndAlias != null) { lAlias = lOboznAndAlias.Alias; } else { lAlias = ""; } return lAlias; } catch (Exception e1) { throw e1; } finally { } } public virtual TDirBase FindById(int pId) { throw (new CommonException("Функция не реализована")); } public virtual TDirBase FindByObozn(string pObozn) {throw (new CommonException("Функция не реализована"));} public virtual TDirBase FindByNaim (string pNaim) {throw (new CommonException("Функция не реализована"));} } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Directory/TRegDirBase.cs
C#
bsd
46,599
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Zzva.DomainObject; using Zzva.Common; using System.Collections; using Zzva.ESB; namespace Zzva.DomainObjectReg { public class TRegDirSoftType : TRegDirBase { private static TRegDirSoftType mvarRegDirSoftType; public void Delete() { try { TDirBase lCurDir; Collection<TDirBase> lCurListDir; int lIdAfterDelete; lCurListDir = GetCurList(); lCurDir = GetCurItem(); lIdAfterDelete = GetIdAfterDelete(lCurDir, lCurListDir); if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } TDirSoftTypeBase lDirSoftTypeBase = (TDirSoftTypeBase)lCurDir; Esb.DeleteSoftType(ref lDirSoftTypeBase); TDirSoftTypeNull lDirSoftTypeNull = (TDirSoftTypeNull)lDirSoftTypeBase; Collection<TDirSoftType> lListDir = Esb.GetListSoftType(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftType h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; if (lIdAfterDelete > 0) { lCurItem = GetItemById(lIdAfterDelete, lListDirBase); } else if (lIdAfterDelete == 0) { lCurItem = null; } else if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } else { throw (new CommonException("Нет значения возврата для GetIdAfterDelete")); } mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Редактирует текущую элемент справочника, на вход объект TDirSoftTypeNew с новыми знвчениями текщей записи public void Edit(TDirSoftTypeNew pDir) { try { TDirBase lCurDir; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Тут бы желательно открыть транзакцию lCurDir = this.GetCurItem(); lCurDir.Obozn = pDir.Obozn; lCurDir.Naim = pDir.Naim; TDirSoftTypeBase lDirSoftTypeBase = (TDirSoftTypeBase)lCurDir; Esb.SaveSoftType(ref lDirSoftTypeBase); TDirSoftType lDirSoftType = (TDirSoftType)lDirSoftTypeBase; Collection<TDirSoftType> lListDir = Esb.GetListSoftType(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftType h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirSoftType.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Добавляет элемент справочника и делает его текущим public void Add(TDirSoftTypeNew pDir) { try { TDirSoftTypeBase lDirSoftTypeBase = (TDirSoftTypeBase)pDir; Esb.SaveSoftType(ref lDirSoftTypeBase); TDirSoftType lDirSoftType = (TDirSoftType)lDirSoftTypeBase; Collection<TDirSoftType> lListDir = Esb.GetListSoftType(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftType h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirSoftType.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } #region (Конструктор, Singeleton)... //Возвращает единственный экземпляр Контроллера себя любимого public static TRegDirSoftType GetObject() { try { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 //Убираем сингелетон то выяснения причин сбоя при повторном вызове //if (mvarRegDirSoftType == null) //{ Collection<TDirSoftType> lListSoftType; lListSoftType = TEsb.GetEsb().GetListSoftType(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftType h in lListSoftType) { lListDirBase.Add((TDirBase)h); } mvarRegDirSoftType = new TRegDirSoftType(lListDirBase); //} return mvarRegDirSoftType; } catch (Exception e) { throw e; } finally { } } protected TRegDirSoftType(Collection<TDirBase> pFullListDir) : base(pFullListDir) { try { } catch (Exception e) { throw e; } finally { } } #endregion public override string Title { get { return "Справочник.Категории ПО"; } } private string TestDelegateFuncGetSelector(TDirSoftType lDirSoftType) { return lDirSoftType.Obozn; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Directory/TRegDirSoftType.cs
C#
bsd
6,970
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Zzva.DomainObject; using Zzva.Common; using System.Collections; using Zzva.ESB; namespace Zzva.DomainObjectReg { public class TRegDirITCompany: TRegDirBase { private static TRegDirITCompany mvarRegDirITCompany; public void Delete() { try { TDirBase lCurDir; Collection<TDirBase> lCurListDir; int lIdAfterDelete; lCurListDir = GetCurList(); lCurDir = GetCurItem(); lIdAfterDelete = GetIdAfterDelete(lCurDir, lCurListDir); if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; Esb.DeleteITCompany(ref lDirITCompanyBase); TDirITCompanyNull lDirITCompanyNull = (TDirITCompanyNull)lDirITCompanyBase; Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirITCompany h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; if (lIdAfterDelete > 0) { lCurItem = GetItemById(lIdAfterDelete, lListDirBase); } else if (lIdAfterDelete == 0) { lCurItem = null; } else if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } else { throw (new CommonException("Нет значения возврата для GetIdAfterDelete")); } mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Редактирует текущую элемент справочника, на вход объект TDirITCompanyNew с новыми знвчениями текщей записи public void Edit(TDirITCompanyNew pDir) { try { TDirBase lCurDir; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Тут бы желательно открыть транзакцию lCurDir = this.GetCurItem(); lCurDir.Obozn = pDir.Obozn; lCurDir.Naim = pDir.Naim; TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; Esb.SaveITCompany(ref lDirITCompanyBase); TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirITCompany h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirITCompany.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Добавляет элемент справочника и делает его текущим public void Add(TDirITCompanyNew pDir) { try { TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)pDir; Esb.SaveITCompany(ref lDirITCompanyBase); TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirITCompany h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirITCompany.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } #region (Конструктор, Singeleton)... //Возвращает единственный экземпляр Контроллера себя любимого public static TRegDirITCompany GetObject() { try { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 //Убираем сингелетон то выяснения причин сбоя при повторном вызове ////if (mvarRegDirITCompany == null) ////{ Collection<TDirITCompany> lListITCompany; lListITCompany = TEsb.GetEsb().GetListITCompany(); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirITCompany h in lListITCompany){lListDirBase.Add((TDirBase)h);} mvarRegDirITCompany = new TRegDirITCompany(lListDirBase); ////} return mvarRegDirITCompany; } catch (Exception e) { throw e; } finally { } } protected TRegDirITCompany(Collection<TDirBase> pFullListDir) : base(pFullListDir) { try { } catch (Exception e) { throw e; } finally { } } #endregion public override string Title { get { return "Справочник. ИТ Компании"; } } //// //Проверяет наличие функции у делегата //// public bool CheckEventUpdateListIsNull() //// { //// if (EventUpdateList == null) { return true; } //// else { return false; } //// } //// //Проверяет наличие функции у делегата //// public bool CheckEventFindDirIsNull() //// { //// if (EventFindDir == null) { return true; } //// else { return false; } //// } //// protected virtual void FireEventFindDir(TDirFindEventArgs pDirFindEventArgs) //// { //// try { if (EventFindDir != null) EventFindDir(this, pDirFindEventArgs); } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// protected virtual void FireEventUpdateList(EventArgs pUpdateListEventArgs) //// { //// try{if (EventUpdateList != null) EventUpdateList(this, pUpdateListEventArgs);} //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Возвращает текущий элемент //// public TDirITCompany GetCurItem() //// { return mvarCurItem; } //// //Возвращает текущее представление справочника с учетом фильта и сортировки //// private Collection<TDirITCompany> GetCurList() //// { //// try //// { //// Collection<TDirITCompany> lCurList; //// lCurList = new Collection<TDirITCompany>(); //// //// //// #region (Примеры использования делегата public delegate TResult Func<T, TResult>(T arg)) в операциях LINQ //// //1 метод - делегат внешняя функция //// ////Func<TDirITCompany, string> lSelector = TestDelegateFuncGetSelector; //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// //2 метод - делегат внешняя функция //// ////Func<TDirITCompany, string> lSelector; //// ////lSelector = TestDelegateFuncGetSelector; //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// //3 метод с использованием анонимной фукнкции //// ////Func<TDirITCompany, string> lSelector; //// ////lSelector = delegate(TDirITCompany lDirITCompany) //// ////{ //// //// return lDirITCompany.Obozn; //// ////}; //// //// //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// //// //4 метод с использованием анонимной фукнкции //// ////Func<TDirITCompany, string> lSelector = delegate(TDirITCompany lDirITCompany) //// ////{ //// //// return lDirITCompany.Obozn; //// ////}; //// //// //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// ////5 метод с использованием лямбада выражения в описании функции //// ////Func<TDirITCompany, string> lSelector = h => h.Obozn; //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// ////6 метод с использованием лямбада выражения в описании функции //// ////Func<TDirITCompany, string> lSelector; //// ////lSelector = h => h.Obozn; //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// //// ////7метод с использованием лямбада выражения в описании функции //// ////Func<TDirITCompany, string> lSelector; //// ////lSelector = h => //// ////{ //// //// string k = h.Obozn; //// //// return k; //// ////}; //// ////var hhh = mvarListDir.OrderBy(lSelector); //// //// ////8метод с использованием лямбада выражения в описании функции //// ////var hhh = mvarListDir.OrderBy(h => h.Obozn); //// #endregion //// //// //// IEnumerable<TDirITCompany> hhh; //// //// //// //// //// //Sort //// //// Func<TDirITCompany, string> lSelector; //// //// lSelector = null; //// //// switch (mvarSortValue.FieldObozn) //// //// { //// //// case "Id": //// //// lSelector = h => { return h.Id.ToString(); }; //// //// break; //// //// case "Obozn": //// //// lSelector = h => { return h.Obozn; }; //// //// break; //// //// case "Naim": //// //// lSelector = h => { return h.Naim + "," + h.Obozn; }; //// //// break; //// //// default: //// //// throw (new CommonException("Нет такого поля")); //// //// } //// //// //// //// if (mvarSortValue.SortType == ESortType.OrderForward){hhh = mvarListDir.OrderBy(lSelector);} //// //// else if ((mvarSortValue.SortType == ESortType.OrderBackward)){hhh = mvarListDir.OrderByDescending(lSelector);} //// //// else { throw (new CommonException("Нет типа сортировки")); } //// //// //// //// //Sort //// Func<TDirITCompany, object> lSelector; //// lSelector = h => { return h.GetAttrib(mvarSortValue.FieldObozn); }; //// if (mvarSortValue.SortType == ESortType.OrderForward) //// { //// ////hhh = mvarListDir.OrderBy(h => h.GetAttrib(mvarSortValue.FieldObozn)); //// hhh = mvarListDir.OrderBy(lSelector); //// } //// else if ((mvarSortValue.SortType == ESortType.OrderBackward)) //// { //// ////hhh = mvarListDir.OrderByDescending(h => h.GetAttrib(mvarSortValue.FieldObozn)); //// hhh = mvarListDir.OrderByDescending(lSelector); //// } //// else { throw (new CommonException("Нет типа сортировки")); } //// //// //// //// //Filter //// //готовим делегата условия //// Func<TDirITCompany, bool> lPredicate; //// lPredicate = null; //// //// if (mvarListFilter.Count != 0) //Есть фильтр //// { //// foreach (TFilterValue k in mvarListFilter) //// { //// switch (k.FieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(k.FilterTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(k.FilterTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(k.FilterTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } //// hhh = hhh.Where(lPredicate).ToList(); //// } //// } //// //// foreach (TDirITCompany h in hhh) { lCurList.Add(h); } //// //// return lCurList; //// } //// catch (Exception e) { throw e; } //// finally { } //// } //// public object GetCurListView() //// { //// try //// { //// Collection<TDirITCompany> lCurrentList = GetCurList(); //// //// var hhh = lCurrentList.Select(p => new //// { //// Id = p.Id, //// Обозначение = p.Obozn, //// Наименование = p.Naim, //// }).ToList(); //// return hhh; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Возвращает первый элемент //// private TDirITCompany GetFirstItem(Collection<TDirITCompany> pListDir) //// { //// try //// { //// TDirITCompany lDirITCompany; //// //// ////lDirITCompany = pListDir.First(); //// lDirITCompany = pListDir.FirstOrDefault(); //// return lDirITCompany; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// public void Sort(TSortValue pSortValue) //// { //// try //// { //// //// //Изменяем алиас на код поля //// TSortValue lSortValue; //// string lFieldObozn; //// lFieldObozn = GetColumnOboznByAlias(pSortValue.FieldObozn); //// if (lFieldObozn == "") { throw (new CommonException("Нет обозначения по алиасу")); } //// lSortValue = new TSortValue(lFieldObozn, pSortValue.SortType); //// //// //// ////mvarSortValue = pSortValue; //// mvarSortValue = lSortValue; //// //// //// Collection<TDirITCompany> lCurList; //// lCurList = GetCurList(); //// //// TDirITCompany lFirstItem; //// lFirstItem = GetFirstItem(lCurList); //// mvarCurItem = lFirstItem; //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } #region Filter... //// public void FilterAdd(TFilterValue pFilterValue) //// { //// try //// { //// if (pFilterValue.FilterTemplate.Trim() != "")//Фильтр с пустой строкой игнорируются //// { //// //Изменяем алиас на код поля //// TFilterValue lFilterValue; //// string lFieldObozn; //// lFieldObozn = GetColumnOboznByAlias(pFilterValue.FieldObozn); //// if (lFieldObozn == "") { throw (new CommonException("Нет обозначения по алиасу")); } //// lFilterValue = new TFilterValue(lFieldObozn, pFilterValue.FilterTemplate); //// //// //// ////mvarListFilter.Add(pFilterValue); //// mvarListFilter.Add(lFilterValue); //// //// //// Collection<TDirITCompany> lCurList; //// lCurList = GetCurList(); //// //// TDirITCompany lFirstItem; //// lFirstItem = GetFirstItem(lCurList); //// mvarCurItem = lFirstItem; //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// } //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// public void FilterDel() //// { //// try //// { //// mvarListFilter.Clear(); //// //// Collection<TDirITCompany> lCurList; //// lCurList = GetCurList(); //// //// TDirITCompany lFirstItem; //// lFirstItem = GetFirstItem(lCurList); //// mvarCurItem = lFirstItem; //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } #endregion //// //Возвращает текущий элемент //// public TDirITCompany GetCurItem() //// { return mvarCurItem; } //// //Возвращает индекс текущего итема в текущей последовательности //// //если нет текущего итема возвращает -1 //// // 0 это превыйэлемент последоватедьности (для справки) //// private int GetCurItemIndex() //// { //// try //// { //// int lIndex; //// int lResult; //// Collection<TDirITCompany> lCurList; //// TDirITCompany lCurItem; //// //// lCurItem = GetCurItem(); //// //// if (lCurItem == null) { lResult = -1; } //// else //// { //// lCurList = GetCurList(); //// lIndex = lCurList.IndexOf(lCurItem); //// if (lIndex == -1) { throw (new CommonException("Текущий элемент не найден")); } //// else { lResult = lIndex; } //// } //// //// return lResult; //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } #region Find... //// //Находит ячейку с заданным критерием в текущем списке и делает ее текущей //// // Поиск начианется с текущей ячейки вверх списка //// //Если не находит, остается на текущей ячейке //// public void FindPrev(TFilterValue lFindValue) //// { //// try //// { //// TDirITCompany lDirITCompany; //// Collection<TDirITCompany> lCurList; //// string lFieldObozn; //// string lFindTemplate; //// TDirFindEventArgs lDirFindEventArgs; //// //// ////lFieldObozn = lFindValue.FieldObozn; //// lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); //// if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } //// //// //// lFindTemplate = lFindValue.FilterTemplate; //// //// if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } //// //// lCurList = GetCurList(); //// //// //готовим делегата условия //// Func<TDirITCompany, bool> lPredicate; //// lPredicate = null; //// switch (lFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } //// //// //// int lCurItemIndex; //// lCurItemIndex = GetCurItemIndex(); //// if (lCurItemIndex == -1) { lDirFindEventArgs = new TDirFindEventArgs(false, null); }//вообще нет записей -> негде искать //// else //// { //// //// var hhh = lCurList.Take(lCurItemIndex);// обрезаем снизу от текущей записис //// lDirITCompany = hhh.LastOrDefault(lPredicate); //// //// if (lDirITCompany != null) //// { //// mvarCurItem = lDirITCompany; //// lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); //// } //// else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } //// //// } //// //// EventFindDir(this, lDirFindEventArgs); //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Находит ячейку с заданным критерием в текущем списке и делает ее текущей //// // Поиск начианется с текущей ячейки вниз списка //// //Если не находит, остается на текущей ячейке //// public void FindNext(TFilterValue lFindValue) //// { //// try //// { //// TDirITCompany lDirITCompany; //// Collection<TDirITCompany> lCurList; //// string lFieldObozn; //// string lFindTemplate; //// TDirFindEventArgs lDirFindEventArgs; //// //// //// ////lFieldObozn = lFindValue.FieldObozn; //// lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); //// if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } //// //// //// //// //// lFindTemplate = lFindValue.FilterTemplate; //// //// //// //// //// //// //// //// //// if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } //// //// lCurList = GetCurList(); //// //// //готовим делегата условия //// Func<TDirITCompany, bool> lPredicate; //// lPredicate = null; //// switch (lFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } //// //// //// int lCurItemIndex; //// lCurItemIndex = GetCurItemIndex(); //// if (lCurItemIndex == -1) { lDirFindEventArgs = new TDirFindEventArgs(false, null); }//вообще нет записей -> негде искать //// else //// { //// var hhh = lCurList.Skip(lCurItemIndex + 1);// обрезаем сверху от текущей записис //// lDirITCompany = hhh.FirstOrDefault(lPredicate); //// //// if (lDirITCompany != null) //// { //// mvarCurItem = lDirITCompany; //// lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); //// } //// else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } //// } //// //// EventFindDir(this, lDirFindEventArgs); //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Находит ячейку с заданным критерием в текущем списке и делает ее текущей //// // Поиск начианется с первой ячейки вниз списка //// //Если не находит, остается на текущей ячейке //// public void Find(TFilterValue lFindValue) //// { //// try //// { //// TDirITCompany lDirITCompany; //// Collection<TDirITCompany> lCurList; //// string lFieldObozn; //// string lFindTemplate; //// TDirFindEventArgs lDirFindEventArgs; //// //// //// ////lFieldObozn = lFindValue.FieldObozn; //// lFieldObozn = GetColumnOboznByAlias(lFindValue.FieldObozn); //// if (lFieldObozn == "") { throw (new CommonException("Нет такого обозначения по алиасу")); } //// //// //// //// //// lFindTemplate = lFindValue.FilterTemplate; //// //// if (lFindTemplate == "") { throw (new CommonException("Отсутсвует критерий поиска")); } //// //// lCurList = GetCurList(); //// //готовим делегата условия //// Func<TDirITCompany, bool> lPredicate; //// lPredicate = null; //// switch (lFieldObozn) //// { //// case "Id": //// lPredicate = d => d.Id.ToString().ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Obozn": //// lPredicate = d => d.Obozn.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// case "Naim": //// lPredicate = d => d.Naim.ToLower().Contains(lFindTemplate.ToLower()); //// break; //// default: //// throw (new CommonException("Нет такого поля")); //// } //// //// lDirITCompany = lCurList.FirstOrDefault(lPredicate); //// //// //// if (lDirITCompany != null) //// { //// mvarCurItem = lDirITCompany; //// lDirFindEventArgs = new TDirFindEventArgs(true, (TDirBase)GetCurItem()); //// } //// else { lDirFindEventArgs = new TDirFindEventArgs(false, null); } //// //// EventFindDir(this, lDirFindEventArgs); //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } #endregion //// //Возвращает ИД следующего после удаления текущего элемента //// private int GetIdAfterDelete(TDirITCompany pDir, Collection<TDirITCompany> pListDir) //// { //// try //// { //// int lIndex; //// int Result; //// TDirITCompany lAfterDeleteDir; //// //// lIndex = pListDir.IndexOf(pDir); //// //// if (lIndex == -1) { Result = -1; }//нет исходного объекта в коллекции //// else //// { //// lAfterDeleteDir = pListDir.ElementAtOrDefault(lIndex + 1); //// if (lAfterDeleteDir == null) //// { //// lAfterDeleteDir = pListDir.ElementAtOrDefault(lIndex - 1); //// if (lAfterDeleteDir == null) { Result = 0; }//Нет объектов после удаления} //// else { Result = lAfterDeleteDir.Id; }//Возвращаем предыдйущий объект} //// } //// else { Result = lAfterDeleteDir.Id; }//возвращаем следующий объект //// //// } //// return Result; //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Клиент устанавливает текущую запись в текщем представлении //// public void SetCurItem(int pId) //// { //// try //// { //// Collection<TDirITCompany> lCurList; //// TDirITCompany lCurItem; //// //// lCurList = GetCurList(); //// lCurItem = lCurList.Single(p => p.Id == pId); //// mvarCurItem = lCurItem; //// } //// catch (Exception e) { throw e; } //// finally { } //// } //// //Возвращает элемент коллекции по значению идентификатора //// private TDirITCompany GetItemById(int pId, Collection<TDirITCompany> pListDir) //// { //// try //// { //// TDirITCompany hhh = pListDir.SingleOrDefault(r => r.Id == pId); //// return hhh; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Удаляет текущую запись //// public void Delete() //// { //// try //// { //// TDirITCompany lCurDir; //// Collection<TDirITCompany> lCurListDir; //// int lIdAfterDelete; //// //// lCurListDir = GetCurList(); //// lCurDir = GetCurItem(); //// //// lIdAfterDelete = GetIdAfterDelete(lCurDir, lCurListDir); //// //// if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } //// //// //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; //// Esb.DeleteITCompany(ref lDirITCompanyBase); //// TDirITCompanyNull lDirITCompanyNull = (TDirITCompanyNull)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// //// //// TDirITCompany lCurItem; //// //// if (lIdAfterDelete > 0) { lCurItem = GetItemById(lIdAfterDelete, lListDir); } //// else if (lIdAfterDelete == 0) { lCurItem = null; } //// else if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } //// else { throw (new CommonException("Нет значения возврата для GetIdAfterDelete")); } //// //// //// //// //// mvarListDir = lListDir; //// mvarCurItem = lCurItem; //// //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //Удаляет текущую запись //// //Редактирует текущую элемент справочника, на вход объект TDirITCompanyNew с новыми знвчениями текщей записи //// public void Edit(TDirITCompanyNew pDir) //// { //// try //// { //// TDirITCompany lCurDir; //// //// //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //// //Тут бы желательно открыть транзакцию //// //// lCurDir = this.GetCurItem(); //// lCurDir.Obozn = pDir.Obozn; //// lCurDir.Naim = pDir.Naim; //// //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)lCurDir; //// Esb.SaveITCompany(ref lDirITCompanyBase); //// TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// TDirITCompany lCurItem; //// lCurItem = GetItemById(lDirITCompany.Id, lListDir); //// //// mvarListDir = lListDir; //// mvarCurItem = lCurItem; //// //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Добавляет элемент справочника и делает его текущим //// public void Add(TDirITCompanyNew pDir) //// { //// try //// { //// TDirITCompanyBase lDirITCompanyBase = (TDirITCompanyBase)pDir; //// Esb.SaveITCompany(ref lDirITCompanyBase); //// TDirITCompany lDirITCompany = (TDirITCompany)lDirITCompanyBase; //// Collection<TDirITCompany> lListDir = Esb.GetListITCompany(); //// TDirITCompany lCurItem; //// lCurItem = GetItemById(lDirITCompany.Id, lListDir); //// //// mvarListDir = lListDir; //// mvarCurItem = lCurItem; //// //// //дальше здесь событие что обновлено //// if (EventUpdateList != null) EventUpdateList(this, EventArgs.Empty); //// //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } private string TestDelegateFuncGetSelector(TDirITCompany lDirITCompany) { return lDirITCompany.Obozn; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Directory/TRegDirITCompany.cs
C#
bsd
39,593
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.DomainObject; namespace Zzva.DomainObjectReg { public class TDirFindEventArgs : EventArgs { public TDirBase CurDir; //текущий найденный объект, если не нашли то nuul public bool Result;//true - нашли, false - не нашли public TDirFindEventArgs(bool pResult,TDirBase pCurDir) { this.CurDir = pCurDir; this.Result = pResult; } } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Directory/TDirFindEventArgs.cs
C#
bsd
577
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using Zzva.DomainObject; using Zzva.ESB; using Zzva.Common; namespace Zzva.DomainObjectReg { public class TRegDirSoftware : TRegDirBase { private static TRegDirSoftware mvarRegDirSoftware; public void Delete() { try { TDirBase lCurDir; Collection<TDirBase> lCurListDir; int lIdAfterDelete; lCurListDir = GetCurList(); lCurDir = GetCurItem(); lIdAfterDelete = GetIdAfterDelete(lCurDir, lCurListDir); if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } TDirSoftwareBase lDirSoftwareBase = (TDirSoftwareBase)lCurDir; Esb.DeleteSoftware(ref lDirSoftwareBase); TDirSoftwareNull lDirSoftwareNull = (TDirSoftwareNull)lDirSoftwareBase; ////Collection<TDirSoftware> lListDir = Esb.GetListSoftware(); Collection<TDirSoftware> lListDir = Esb.GetListSoftware(0); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftware h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; if (lIdAfterDelete > 0) { lCurItem = GetItemById(lIdAfterDelete, lListDirBase); } else if (lIdAfterDelete == 0) { lCurItem = null; } else if (lIdAfterDelete == -1) { throw (new CommonException("Нет текущего элемента в коллекции")); } else { throw (new CommonException("Нет значения возврата для GetIdAfterDelete")); } mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Редактирует текущую элемент справочника, на вход объект TDirITCompanyNew с новыми знвчениями текщей записи public void Edit(TDirSoftwareNew pDir) { try { TDirSoftware lCurDir; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Тут бы желательно открыть транзакцию lCurDir = (TDirSoftware)this.GetCurItem(); lCurDir.Obozn = pDir.Obozn; lCurDir.Naim = pDir.Naim; lCurDir.Developer = pDir.Developer; lCurDir.Holder = pDir.Holder; //// lCurDir.SoftType = pDir.SoftType; TDirSoftwareBase lDirSoftwareBase = (TDirSoftwareBase)lCurDir; ////Esb.SaveSoftware(ref lDirSoftwareBase); Esb.SaveSoftware(ref lDirSoftwareBase, 0); TDirSoftware lDirSoftware = (TDirSoftware)lDirSoftwareBase; ////Collection<TDirSoftware> lListDir = Esb.GetListSoftware(); Collection<TDirSoftware> lListDir = Esb.GetListSoftware(0); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftware h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirSoftware.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } //Добавляет элемент справочника и делает его текущим public void Add(TDirSoftwareNew pDir) { try { TDirSoftwareBase lDirSoftwareBase = (TDirSoftwareBase)pDir; //Esb.SaveSoftware(ref lDirSoftwareBase); Esb.SaveSoftware(ref lDirSoftwareBase, 0); TDirSoftware lDirSoftware = (TDirSoftware)lDirSoftwareBase; //Collection<TDirSoftware> lListDir = Esb.GetListSoftware(); Collection<TDirSoftware> lListDir = Esb.GetListSoftware(0); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftware h in lListDir) { lListDirBase.Add((TDirBase)h); } TDirBase lCurItem; lCurItem = GetItemById(lDirSoftware.Id, lListDirBase); mvarFullListDir = lListDirBase; mvarCurItem = lCurItem; //// mvarFlgSinhroCurListAndCurState = false; //дальше здесь событие что обновлено FireEventUpdateList(EventArgs.Empty); } catch (Exception e1) { throw e1; } finally { } } protected override Collection<TAliasForField> GetListOboznAndAlias() { Collection<TAliasForField> lList; lList = base.GetListOboznAndAlias(); lList.Add(new TAliasForField("Developer", "Разработчик")); lList.Add(new TAliasForField("Holder", "Правообладатель")); //// lList.Add(new TAliasForField("SoftType", "Категория")); return lList; } //Возвращает единственный экземпляр Контроллера себя любимого public static TRegDirSoftware GetObject() { try { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Убираем сингелетон до вяснения причин сбоя при повторном открытии //if (mvarRegDirSoftware == null) //{ Collection<TDirSoftware> lListSoftware; ////lListSoftware = TEsb.GetEsb().GetListSoftware(); lListSoftware = TEsb.GetEsb().GetListSoftware(0); Collection<TDirBase> lListDirBase = new Collection<TDirBase>(); foreach (TDirSoftware h in lListSoftware) { lListDirBase.Add((TDirBase)h); } mvarRegDirSoftware = new TRegDirSoftware(lListDirBase); //} return mvarRegDirSoftware; } catch (Exception e) { throw e; } finally { } } //Возвращает представление для клиента public override object GetCurListView() { try { Collection<TDirBase> lCurrentList = GetCurList(); var hhh = lCurrentList.Select (p => { TDirSoftware d = (TDirSoftware)p; var k = new { Id = d.Id, Обозначение = d.Obozn, Наименование = d.Naim, //Разработчик = d.Developer.Obozn, Разработчик = d.Developer, //// Категория = d.SoftType, //Правообладатель = d.Holder.Obozn, Правообладатель = d.Holder, }; return k; } ); hhh = hhh.ToList(); return hhh; } catch (Exception e1) { throw e1; } finally { } } //// //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону //// protected override TDirBase FindLastDirInList //// (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) //// { //// try //// { //// TDirBase lDirBase; //// //// lDirBase = base.FindLastDirInList(pFieldObozn, pFieldTemplate, pList); //// //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (pFieldObozn) //// { //// case "Developer": //// lPredicate = d => ((TDirSoftware)d).Developer.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.LastOrDefault(lPredicate); //// break; //// case "Holder": //// lPredicate = d => ((TDirSoftware)d).Holder.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.LastOrDefault(lPredicate); //// break; //// default: //// break; //// } //// return lDirBase; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Ищет в заданном списке элемент справочника в заданном поле по заданному шаблону //// protected override TDirBase FindFirstDirInList //// (string pFieldObozn, string pFieldTemplate, IEnumerable<TDirBase> pList) //// { //// try //// { //// TDirBase lDirBase; //// //// lDirBase = base.FindFirstDirInList(pFieldObozn, pFieldTemplate, pList); //// //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// switch (pFieldObozn) //// { //// case "Developer": //// ////lPredicate = d => d.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lPredicate = d => ((TDirSoftware)d).Developer.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.FirstOrDefault(lPredicate); //// break; //// case "Holder": //// ////lPredicate = d => d.Naim.ToLower().Contains(pFieldTemplate.ToLower()); //// lPredicate = d => ((TDirSoftware)d).Holder.Obozn.ToLower().Contains(pFieldTemplate.ToLower()); //// lDirBase = pList.FirstOrDefault(lPredicate); //// break; //// default: //// break; //// } //// //// return lDirBase; //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// //Фильтруе заданный список по установленному фильтру //// protected override IEnumerable<TDirBase> SelectListBySetFilter(IEnumerable<TDirBase> pList) //// { //// try //// { //// //Фильт по базовым полям //// pList = base.SelectListBySetFilter(pList); //// //// //готовим делегата условия //// Func<TDirBase, bool> lPredicate; //// lPredicate = null; //// //// if (mvarListFilter.Count != 0) //Есть фильтр //// { //// foreach (TFilterValue k in mvarListFilter) //// { //// switch (k.FieldObozn) //// { //// case "Developer": //// //lPredicate = d => d.Obozn.ToLower().Contains(k.FilterTemplate.ToLower()); //// lPredicate = d => ((TDirSoftware)d).Developer.Obozn.ToLower().Contains(k.FilterTemplate.ToLower()); //// //// //pList = pList.Where(lPredicate); //// pList = pList.Where(lPredicate).ToList(); //// //// break; //// case "Holder": //// lPredicate = d => ((TDirSoftware)d).Holder.Obozn.ToLower().Contains(k.FilterTemplate.ToLower()); //// //// //pList = pList.Where(lPredicate); //// pList = pList.Where(lPredicate).ToList(); //// //// break; //// default: //// break; //// //throw (new CommonException("Нет такого поля")); //// } //// //pList = pList.Where(lPredicate); //// } //// } //// return pList; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //Возвращает Шаблон нового объекта public TDirBase GetTemplateNewItem() { try { TDirSoftwareNew lDirSoftwareNew; string lNewOboznSoftware; lNewOboznSoftware = GetNewOboznSoftware(); lDirSoftwareNew = new TDirSoftwareNew(); lDirSoftwareNew.Obozn = lNewOboznSoftware; return (TDirBase)lDirSoftwareNew; } catch (Exception e1) { throw e1; } finally { } } //Вернуть внутренний код для нового объекта Software private string GetNewOboznSoftware() { try { int lLastIdSoftware; string lTemplateOboznSoftware; string lNewOboznSoftware; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаем шаблон из установок, а пока так lTemplateOboznSoftware = "ВЛИЕ.2/38-7-1"; lLastIdSoftware = Esb.GetLastIdSoftware(); lLastIdSoftware = lLastIdSoftware + 1; string lLastIdSoftwareString; string lDeltaObozn; lLastIdSoftwareString = lLastIdSoftware.ToString(); switch (lLastIdSoftwareString.Length) { case 1: lDeltaObozn = "00" + lLastIdSoftwareString; break; case 2: lDeltaObozn = "0" + lLastIdSoftwareString; break; case 3: lDeltaObozn = lLastIdSoftwareString; break; default: throw (new CommonException("Перебор знаков в коде ПО")); ////break; } lNewOboznSoftware = lTemplateOboznSoftware + lDeltaObozn; return lNewOboznSoftware; } catch (Exception e1) { throw e1; } finally { } } #region (Конструктор, Singeleton)... protected TRegDirSoftware(Collection<TDirBase> pFullListDir) : base(pFullListDir) { try { } catch (Exception e) { throw e; } finally { } } #endregion public override string Title {get{return "Справочник. Программное обеспечение";}} } }
zzvalib
trunk/DomainObjectReg/DomainObjectReg/Zzva.DomainObjectReg/Directory/TRegDirSoftware.cs
C#
bsd
17,518
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Zzva.ESB.Test { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TFormTest()); } } }
zzvalib
trunk/ESB/ESB/Zzva.ESB.Test/Program.cs
C#
bsd
509
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.ESB.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.ESB.Test")] [assembly: AssemblyCopyright("Copyright © zzva 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4dc69a32-6b60-4bac-a40f-d06ef587475c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/ESB/ESB/Zzva.ESB.Test/Properties/AssemblyInfo.cs
C#
bsd
1,446
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Zzva.Common; using System.Data; using Zzva.DomainObject; using System.Collections.ObjectModel; using System.Collections; namespace Zzva.ESB { public class TEsb:TEsbDomainObject { private static TEsb mvarEsb; # region Software переопределяем всвязи с вводом связи SoftType public Collection<TDirSoftware> GetListSoftware(int pForOverLoad) { try { DataTable lListSoftware; Collection<TDirSoftware> lCollSoftware; int lId; TDirSoftware lDirSoftware; lListSoftware = SysMrpZzva.GetListSoftware(); lCollSoftware = new Collection<TDirSoftware>(); if (lListSoftware.Rows.Count != 0) { foreach (DataRow row in lListSoftware.Rows) { lId = (int)row["Id"]; lDirSoftware = GetSoftware(lId,0); lCollSoftware.Add(lDirSoftware); } } else { } return lCollSoftware; } catch (Exception e) { throw e; } finally { } } public void SaveSoftware(ref TDirSoftwareBase pDirSoftwareBase, int pForOverLoad) { try { Type lTypeObject; lTypeObject = pDirSoftwareBase.GetType(); switch (lTypeObject.Name) { case "TDirSoftware": TDirSoftware lDirSoftware = (TDirSoftware)pDirSoftwareBase; EditSoftware(ref lDirSoftware, 0); break; case "TDirSoftwareNew": AddSoftware(ref pDirSoftwareBase,0); break; default: throw (new CommonException("Нет типа Software")); //break; } } catch (Exception e) { throw e; } finally { } } private void AddSoftware(ref TDirSoftwareBase pDirSoftwareBase, int pForOverLoad) { try { int lId; string lObozn; string lNaim; int lHolderId; int lDeveloperId; TDirITCompanyBase lHolder; TDirITCompanyBase lDeveloper; Type lTypeObject; int lSoftTypeId; TDirSoftTypeBase lSoftType; lObozn = pDirSoftwareBase.Obozn; lNaim = pDirSoftwareBase.Naim; lHolder = pDirSoftwareBase.Holder; lTypeObject = lHolder.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lHolderId = ((TDirITCompany)pDirSoftwareBase.Holder).Id; break; case "TDirITCompanyNull": lHolderId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lDeveloper = pDirSoftwareBase.Developer; lTypeObject = lDeveloper.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lDeveloperId = ((TDirITCompany)pDirSoftwareBase.Developer).Id; break; case "TDirITCompanyNull": lDeveloperId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lSoftType = pDirSoftwareBase.SoftType; lTypeObject = lSoftType.GetType(); switch (lTypeObject.Name) { case "TDirSoftType": lSoftTypeId = ((TDirSoftType)pDirSoftwareBase.SoftType).Id; break; case "TDirSoftTypeNull": lSoftTypeId = 0; break; default: throw (new CommonException("Нет типа SoftType")); //break; } lId = SysMrpZzva.AddSoftware(lObozn, lNaim, lHolderId, lDeveloperId,lSoftTypeId); pDirSoftwareBase = this.GetSoftware(lId,0); } catch (Exception e) { throw e; } finally { } } private void EditSoftware(ref TDirSoftware pDirSoftware, int pForOverLoad) { try { int lId; string lObozn; string lNaim; int lHolderId; int lDeveloperId; TDirITCompanyBase lHolder; TDirITCompanyBase lDeveloper; Type lTypeObject; int lSoftTypeId; TDirSoftTypeBase lSoftType; lId = pDirSoftware.Id; lObozn = pDirSoftware.Obozn; lNaim = pDirSoftware.Naim; lHolder = pDirSoftware.Holder; lTypeObject = lHolder.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lHolderId = ((TDirITCompany)pDirSoftware.Holder).Id; break; case "TDirITCompanyNull": lHolderId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lDeveloper = pDirSoftware.Developer; lTypeObject = lDeveloper.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lDeveloperId = ((TDirITCompany)pDirSoftware.Developer).Id; break; case "TDirITCompanyNull": lDeveloperId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lSoftType = pDirSoftware.SoftType; lTypeObject = lSoftType.GetType(); switch (lTypeObject.Name) { case "TDirSoftType": lSoftTypeId = ((TDirSoftType)pDirSoftware.SoftType).Id; break; case "TDirSoftTypeNull": lSoftTypeId = 0; break; default: throw (new CommonException("Нет типа SoftType")); //break; } SysMrpZzva.EditSoftware(lId, lObozn, lNaim, lDeveloperId, lHolderId,lSoftTypeId); pDirSoftware = this.GetSoftware(lId,0); } catch (Exception e) { throw e; } finally { } } public TDirSoftware GetSoftware(int pId, int pForOverload) { try { TDirSoftware lDirSoftware; string lObozn; string lNaim; int lHolder; int lDeveloper; int lSoftType; if (SysMrpZzva.GetSoftware(pId, out lObozn, out lNaim, out lHolder, out lDeveloper,out lSoftType) == true) { return lDirSoftware = new TDirSoftware(this, pId, lObozn, lNaim, lHolder, lDeveloper,lSoftType); } else{throw (new CommonException("Software ИД = " + pId + " отсутсвует"));} } catch (Exception e) { throw e; } finally { } } # endregion # region SoftType public override TDirSoftType GetSoftType(int pId) { try { TDirSoftType lDirSoftType; string lObozn; string lNaim; if (SysMrpZzva.GetSoftType(pId, out lObozn, out lNaim) == true) { return lDirSoftType = new TDirSoftType(this, pId, lObozn, lNaim); } else { throw (new CommonException("SoftType ИД = " + pId + " отсутсвует")); } } catch (Exception e) { throw e; } finally { } } public void SaveSoftType(ref TDirSoftTypeBase pDirSoftType) { try { Type lTypeObject; lTypeObject = pDirSoftType.GetType(); switch (lTypeObject.Name) { case "TDirSoftType": TDirSoftType lDirSoftType = (TDirSoftType)pDirSoftType; EditSoftType(ref lDirSoftType); break; case "TDirSoftTypeNew": //TDirSoftTypeNew lDirSoftTypeNew = (TDirSoftTypeNew)pDirSoftType; //AddSoftType(ref lDirSoftTypeNew); AddSoftType(ref pDirSoftType); break; default: throw (new CommonException("Нет типа DirSoftType")); //break; } } catch (Exception e) { throw e; } finally { } } private void EditSoftType(ref TDirSoftType pDirSoftType) { try { int lId; string lObozn; string lNaim; lId = pDirSoftType.Id; lObozn = pDirSoftType.Obozn; lNaim = pDirSoftType.Naim; SysMrpZzva.EditSoftType(lId, lObozn, lNaim); pDirSoftType = this.GetSoftType(lId); } catch (Exception e) { throw e; } finally { } } public void DeleteSoftType(ref TDirSoftTypeBase pDirSoftType) { try { Type lTypeObject; lTypeObject = pDirSoftType.GetType(); if (lTypeObject.Name == "TDirSoftType") { TDirSoftType lDirSoftType = (TDirSoftType)pDirSoftType; if (CheckRelationSoftType(lDirSoftType) == false) { SysMrpZzva.DeleteSoftType(lDirSoftType.Id); pDirSoftType = new TDirSoftTypeNull(); } else { throw (new CommonException("Не удаляется! Существуют связи этой SoftType с другими объектами")); } } else { throw (new CommonException("Только постоянный объект можно удалять")); } } catch (Exception e) { throw e; } finally { } } private bool CheckRelationSoftType(TDirSoftType pDirSoftType) { try { int lId; bool Result; lId = pDirSoftType.Id; if (SysMrpZzva.CheckRelationSoftType(lId) == false) //& (SysKis.CheckRelationSoftType(lId) == false)//проверяется по всем физическим системам в котроых есть связи { Result = false; } else { Result = true; } return Result; } catch (Exception e) { throw e; } finally { } } public Collection<TDirSoftType> GetListSoftType() { try { DataTable lListSoftType; Collection<TDirSoftType> lCollSoftType; int lId; TDirSoftType lDirSoftType; lListSoftType = SysMrpZzva.GetListSoftType(); lCollSoftType = new Collection<TDirSoftType>(); if (lListSoftType.Rows.Count != 0) { foreach (DataRow row in lListSoftType.Rows) { lId = (int)row["Id"]; lDirSoftType = GetSoftType(lId); lCollSoftType.Add(lDirSoftType); } } else { } return lCollSoftType; } catch (Exception e) { throw e; } finally { } } private void AddSoftType(ref TDirSoftTypeBase pDirSoftType) { try { int lId; string lObozn; string lNaim; lObozn = pDirSoftType.Obozn; lNaim = pDirSoftType.Naim; lId = SysMrpZzva.AddSoftType(lObozn, lNaim); pDirSoftType = this.GetSoftType(lId); } catch (Exception e) { throw e; } finally { } } # endregion //Вернуть последний код ИД Software public int GetLastIdSoftware() { try { return SysMrpZzva.GetLastIdSoftware(); } catch (Exception e) { throw e; } finally { } } public Collection<TDirSoftware> GetListSoftware() { try { DataTable lListSoftware; Collection<TDirSoftware> lCollSoftware; int lId; TDirSoftware lDirSoftware; lListSoftware = SysMrpZzva.GetListSoftware(); lCollSoftware = new Collection<TDirSoftware>(); if (lListSoftware.Rows.Count != 0) { foreach (DataRow row in lListSoftware.Rows) { lId = (int)row["Id"]; lDirSoftware = GetSoftware(lId); lCollSoftware.Add(lDirSoftware); } } else { } return lCollSoftware; } catch (Exception e) { throw e; } finally { } } #region {Constructors} protected TEsb() { } #endregion #region {DirITCompany} //'' private void AddITCompany(ref TDirITCompanyBase pDirITCompany) //'' { //'' try //'' { //'' int lId; //'' string lObozn; //'' string lNaim; //'' //'' lObozn = pDirITCompany.Obozn; //'' lNaim = pDirITCompany.Naim; //'' //'' //'' lId = SysMrpZzva.AddITCompany(lObozn, lNaim); //'' //'' pDirITCompany = this.GetITCompany(lId); //'' //'' //'' } //'' catch (Exception e) { throw e; } //'' finally { } //'' } private void AddITCompany(ref TDirITCompanyBase pDirITCompany) { try { int lId; string lObozn; string lNaim; lObozn = pDirITCompany.Obozn; lNaim = pDirITCompany.Naim; lId = SysMrpZzva.AddITCompany(lObozn, lNaim); pDirITCompany = this.GetITCompany(lId); } catch (Exception e) { throw e; } finally { } } public Collection<TDirITCompany> GetListITCompany() { try { DataTable lListITCompany; Collection<TDirITCompany> lCollITCompany; int lId; TDirITCompany lDirITCompany; lListITCompany = SysMrpZzva.GetListITCompany(); lCollITCompany = new Collection<TDirITCompany>(); if (lListITCompany.Rows.Count != 0) { foreach (DataRow row in lListITCompany.Rows) { lId = (int)row["Id"]; lDirITCompany = GetITCompany(lId); lCollITCompany.Add(lDirITCompany); } } else{} return lCollITCompany; } catch (Exception e) { throw e; } finally { } } public void DeleteITCompany(ref TDirITCompanyBase pDirITCompany) { try { Type lTypeObject; lTypeObject = pDirITCompany.GetType(); if (lTypeObject.Name == "TDirITCompany") { TDirITCompany lDirITCompany = (TDirITCompany)pDirITCompany; if (CheckRelationITCompany(lDirITCompany) == false) { SysMrpZzva.DeleteITCompany(lDirITCompany.Id); pDirITCompany = new TDirITCompanyNull(); } else { throw (new CommonException("Не удаляется! Существуют связи этой ITCompany с другими объектами")); } } else { throw (new CommonException("Только постоянный объект можно удалять")); } } catch (Exception e) { throw e; } finally { } } private bool CheckRelationITCompany(TDirITCompany pDirITCompany) { try { int lId; bool Result; lId = pDirITCompany.Id; if (SysMrpZzva.CheckRelationITCompany(lId) == false) //& (SysKis.CheckRelationITCompany(lId) == false)//проверяется по всем физическим системам в котроых есть связи { Result = false; } else { Result = true; } return Result; } catch (Exception e) { throw e; } finally { } } private void EditITCompany(ref TDirITCompany pDirITCompany) { try { int lId; string lObozn; string lNaim; lId = pDirITCompany.Id; lObozn = pDirITCompany.Obozn; lNaim = pDirITCompany.Naim; SysMrpZzva.EditITCompany(lId, lObozn, lNaim); pDirITCompany = this.GetITCompany(lId); } catch (Exception e) { throw e; } finally { } } public void SaveITCompany(ref TDirITCompanyBase pDirITCompany) { try { Type lTypeObject; lTypeObject = pDirITCompany.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": TDirITCompany lDirITCompany = (TDirITCompany)pDirITCompany; EditITCompany(ref lDirITCompany); break; case "TDirITCompanyNew": //TDirITCompanyNew lDirITCompanyNew = (TDirITCompanyNew)pDirITCompany; //AddITCompany(ref lDirITCompanyNew); AddITCompany(ref pDirITCompany); break; default: throw (new CommonException("Нет типа DirITCompany")); //break; } } catch (Exception e) { throw e; } finally { } } public override TDirITCompany GetITCompany(int pId) { try { TDirITCompany lDirITCompany; string lObozn; string lNaim; if (SysMrpZzva.GetITCompany(pId, out lObozn, out lNaim) == true) { return lDirITCompany = new TDirITCompany(this, pId, lObozn, lNaim); } else { throw (new CommonException("ITCompany ИД = " + pId + " отсутсвует")); } } catch (Exception e) { throw e; } finally { } } #endregion #region {DirSoftware} public void DeleteSoftware(ref TDirSoftwareBase pDirSoftwareBase) { try { Type lTypeObject; lTypeObject = pDirSoftwareBase.GetType(); if (lTypeObject.Name == "TDirSoftware") { TDirSoftware lDirSoftware = (TDirSoftware)pDirSoftwareBase; if (CheckRelationSoftware(lDirSoftware) == false) { SysMrpZzva.DeleteSoftware(lDirSoftware.Id); pDirSoftwareBase = new TDirSoftwareNull(); } else { throw (new CommonException("Не удаляется! Существуют связи этой Software с другими объектами")); } } else { throw (new CommonException("Только постоянный объект можно удалять")); } } catch (Exception e) { throw e; } finally { } } private bool CheckRelationSoftware(TDirSoftware pDirSoftware) { try { bool Result; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Заглушка до момента появления связей Result = false; return Result; } catch (Exception e) { throw e; } finally { } } private void AddSoftware(ref TDirSoftwareBase pDirSoftwareBase) { try { int lId; string lObozn; string lNaim; int lHolderId; int lDeveloperId; TDirITCompanyBase lHolder; TDirITCompanyBase lDeveloper; Type lTypeObject; lObozn = pDirSoftwareBase.Obozn; lNaim = pDirSoftwareBase.Naim; lHolder = pDirSoftwareBase.Holder; lTypeObject = lHolder.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lHolderId = ((TDirITCompany)pDirSoftwareBase.Holder).Id; break; case "TDirITCompanyNull": lHolderId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lDeveloper = pDirSoftwareBase.Developer; lTypeObject = lDeveloper.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lDeveloperId = ((TDirITCompany)pDirSoftwareBase.Developer).Id; break; case "TDirITCompanyNull": lDeveloperId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lId = SysMrpZzva.AddSoftware(lObozn, lNaim,lHolderId,lDeveloperId); pDirSoftwareBase = this.GetSoftware(lId); } catch (Exception e) { throw e; } finally { } } private void EditSoftware(ref TDirSoftware pDirSoftware) { try { int lId; string lObozn; string lNaim; int lHolderId; int lDeveloperId; TDirITCompanyBase lHolder; TDirITCompanyBase lDeveloper; Type lTypeObject; lId = pDirSoftware.Id; lObozn = pDirSoftware.Obozn; lNaim = pDirSoftware.Naim; lHolder = pDirSoftware.Holder; lTypeObject = lHolder.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lHolderId = ((TDirITCompany)pDirSoftware.Holder).Id; break; case "TDirITCompanyNull": lHolderId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } lDeveloper = pDirSoftware.Developer; lTypeObject = lDeveloper.GetType(); switch (lTypeObject.Name) { case "TDirITCompany": lDeveloperId = ((TDirITCompany)pDirSoftware.Developer).Id; break; case "TDirITCompanyNull": lDeveloperId = 0; break; default: throw (new CommonException("Нет типа Software")); //break; } SysMrpZzva.EditSoftware(lId, lObozn, lNaim,lDeveloperId,lHolderId); pDirSoftware = this.GetSoftware(lId); } catch (Exception e) { throw e; } finally { } } public void SaveSoftware(ref TDirSoftwareBase pDirSoftwareBase) { try { Type lTypeObject; lTypeObject = pDirSoftwareBase.GetType(); switch (lTypeObject.Name) { case "TDirSoftware": TDirSoftware lDirSoftware = (TDirSoftware)pDirSoftwareBase; EditSoftware(ref lDirSoftware); break; case "TDirSoftwareNew": AddSoftware(ref pDirSoftwareBase); break; default: throw (new CommonException("Нет типа Software")); //break; } } catch (Exception e) { throw e; } finally { } } public TDirSoftware GetSoftware(int pId) { try { TDirSoftware lDirSoftware; string lObozn; string lNaim; int lHolder; int lDeveloper; if (SysMrpZzva.GetSoftware(pId, out lObozn, out lNaim, out lHolder, out lDeveloper) == true) { return lDirSoftware = new TDirSoftware(this, pId, lObozn, lNaim, lHolder, lDeveloper); } else { throw (new CommonException("Software ИД = " + pId + " отсутсвует")); } } catch (Exception e) { throw e; } finally { } } #endregion #region {Systems} public static TEsb GetEsb() { try { if (mvarEsb == null) { mvarEsb = new TEsb(); } return mvarEsb; } catch (Exception e) { throw e; } finally { } } private TSysKis SysKis { get { try { return TSysKis.GetSystem(); } catch (Exception e) { throw e; } finally { } } } private TSysMrpZzva SysMrpZzva { get { try { return TSysMrpZzva.GetSystem(); } catch (Exception e) { throw e; } finally { } } } private TSysBko SysBko { get { try { return TSysBko.GetSystem(); } catch (Exception e) { throw e; } finally { } } } private TSysBuhuch SysBuhuch { get { try { return TSysBuhuch.GetSystem(); } catch (Exception e) { throw e; } finally { } } } private TSysWorkprogress SysWorkprogress { get { try { return TSysWorkprogress.GetSystem(); } catch (Exception e) { throw e; } finally { } } } #endregion #region {TestFunction} public DataTable TestGetListMater() { try { return SysKis.TestGetListMater(); } catch (Exception e) { throw e; } finally { } } public string TestConnectSysMrpZzva() { return SysMrpZzva.TestConnect(); } public string TestConnectSysWorkprogress() { return SysWorkprogress.TestConnect() ; } public string TestGetNetNamePk(int Pk) { return SysBko.TestGetNetNamePk(Pk); } public bool TestGetNomencl(string pObozn, out string pNaim, out string pEi) { try { return SysBuhuch.GetNomencl(pObozn, out pNaim, out pEi); } catch (Exception e) { throw e; } finally { } } #endregion } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TEsb.cs
C#
bsd
32,018
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Zzva.Common; using System.Data; namespace Zzva.ESB { public class TSysKis { private static TSysKis mvarSysKis; private SqlConnection mvarConnect; protected TSysKis(SqlConnection pConnect) { try { mvarConnect = pConnect; } catch (Exception e) { throw e; } finally { } } public static TSysKis GetSystem() { try { if (mvarSysKis == null) { mvarSysKis = GetSysKis(); } return mvarSysKis; } catch (Exception e) { throw e; } finally { } } private static TSysKis GetSysKis() { string lConnectStr; SqlConnection lConnect; TSysKis lSysKis; try { //!!!!!!!!!!!!! //достаем Connect из установок ////Connect = RegisterLokal.GetSetting("Common", "SysBuhuchConnect"); //lConnectStr = "Data Source=TEH-SRV;Initial Catalog=Kis;Integrated Security=True;"; //lConnectStr = lConnectStr + "User ID=" + User + ";Password=" + Password + ";"; lConnectStr = "Data Source=TEH-SRV;Initial Catalog=Kis;Integrated Security=True;" + "User ID=Sergey;Password=Cl254J;"; lConnect = new SqlConnection(lConnectStr); lConnect.Open(); lSysKis = new TSysKis(lConnect); return lSysKis; } catch (Exception e) { throw e; } finally { } } public DataTable TestGetListMater() { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DSE, DISP, NAIMDSE" + " FROM DSE" + " WHERE (RAZD = 7)"; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); return rst; } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TSysKis.cs
C#
bsd
2,640
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using Zzva.Common; namespace Zzva.ESB { public class TSysMrpZzva { private static TSysMrpZzva mvarSysMrpZzva; private SqlConnection mvarConnect; private SqlTransaction mvarTransaction; # region Software переопределяем в связи с добавлением ссылки на SoftType public bool GetSoftware(int Id, out string Obozn, out string Naim, out int Holder, out int Developer, out int SoftType) { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; DataRow row; bool Result; string lObozn; string lNaim; int lHolder; int lDeveloper; int lSoftType; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware" + " WHERE Id = " + Id; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); if (rst.Rows.Count == 1) { row = rst.Rows[0]; lObozn = (string)row["Obozn"]; if (Convert.IsDBNull(row["Naim"]) == true) { lNaim = ""; } else { lNaim = (string)row["Naim"]; } if (Convert.IsDBNull(row["Holder"]) == true) { lHolder = 0; } else { lHolder = (int)row["Holder"]; } if (Convert.IsDBNull(row["Developer"]) == true) { lDeveloper = 0; } else { lDeveloper = (int)row["Developer"]; } if (Convert.IsDBNull(row["SoftType"]) == true) { lSoftType = 0; } else { lSoftType = (int)row["SoftType"]; } Result = true; } else { lObozn = ""; lNaim = ""; lHolder = 0; lDeveloper = 0; lSoftType = 0; Result = false; } Obozn = lObozn; Naim = lNaim; Holder = lHolder; Developer = lDeveloper; SoftType = lSoftType; return Result; } catch (Exception e) { throw e; } finally { } } public void EditSoftware(int pId, string pObozn, string pNaim, int pDeveloper, int pHolder, int pSoftType) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоночального заполнения справочника //// sql.CommandText = " UPDATE DirSoftware" //// + " SET Naim = @Naim, Holder = @Holder, Developer = @Developer, SoftType = @SoftType" //// + " WHERE Id = " + pId; sql.CommandText = " UPDATE DirSoftware" + " SET Naim = @Naim, Holder = @Holder, Developer = @Developer, Obozn = @Obozn, SoftType = @SoftType" + " WHERE Id = " + pId; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters.Add("@Developer", SqlDbType.Int); sql.Parameters.Add("@Holder", SqlDbType.Int); sql.Parameters.Add("@SoftType", SqlDbType.Int); sql.Parameters["@Naim"].Value = pNaim; if (pDeveloper == 0) { sql.Parameters["@Developer"].Value = DBNull.Value; } else { sql.Parameters["@Developer"].Value = pDeveloper; } if (pHolder == 0) { sql.Parameters["@Holder"].Value = DBNull.Value; } else { sql.Parameters["@Holder"].Value = pHolder; } if (pSoftType == 0) { sql.Parameters["@SoftType"].Value = DBNull.Value; } else { sql.Parameters["@SoftType"].Value = pSoftType; } ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования SoftType")); } } catch (Exception e) { throw e; } finally { } } public int AddSoftware(string pObozn, string pNaim, int pHolder, int pDeveloper, int pSoftType) { SqlTransaction Trans = null; try { SqlCommand sql; int Result; Trans = mvarConnect.BeginTransaction("SampleTransaction"); sql = new SqlCommand(); sql.Transaction = Trans; sql.Connection = mvarConnect; sql.CommandText = " INSERT INTO DirSoftware" + "(Obozn, Naim, Holder, Developer, SoftType)" + " VALUES (@Obozn, @Naim, @Holder, @Developer, @SoftType);" + " SELECT CAST(scope_identity() AS int)"; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters.Add("@Holder", SqlDbType.Int); sql.Parameters.Add("@Developer", SqlDbType.Int); sql.Parameters.Add("@SoftType", SqlDbType.Int); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters["@Naim"].Value = pNaim; if (pDeveloper == 0) { sql.Parameters["@Developer"].Value = DBNull.Value; } else { sql.Parameters["@Developer"].Value = pDeveloper; } if (pHolder == 0) { sql.Parameters["@Holder"].Value = DBNull.Value; } else { sql.Parameters["@Holder"].Value = pHolder; } if (pSoftType == 0) { sql.Parameters["@SoftType"].Value = DBNull.Value; } else { sql.Parameters["@SoftType"].Value = pSoftType; } Result = (int)sql.ExecuteScalar(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Как проверитьчто запись добавлена - критерий???? Trans.Commit(); return Result; } catch (Exception e) { if (Trans != null) { Trans.Rollback(); } throw e; } finally { } } # endregion # region {DirSoftType} public bool CheckRelationSoftType(int pId) { try { bool Result; if (CheckRelatSoftTypeSoft(pId) == false) { Result = false; } else { Result = true; } return Result; } catch (Exception e) { throw e; } finally { } } //Проверка связи Типа ПО с ПО private bool CheckRelatSoftTypeSoft(int pId) { try { SqlCommand sql; SqlDataReader rst; bool Result; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware" + " WHERE SoftType = " + pId; rst = sql.ExecuteReader(); if (rst.HasRows == true) { Result = true; } else { Result = false; } rst.Close(); return Result; } catch (Exception e) { throw e; } finally { } } public bool GetSoftType(int Id, out string Obozn, out string Naim) { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; DataRow row; bool Result; string lObozn; string lNaim; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftType.*" + " FROM DirSoftType" + " WHERE Id = " + Id; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); if (rst.Rows.Count == 1) { row = rst.Rows[0]; lObozn = (string)row["Obozn"]; if (Convert.IsDBNull(row["Naim"]) == true) { lNaim = ""; } else { lNaim = (string)row["Naim"]; } Result = true; } else { lObozn = ""; lNaim = ""; Result = false; } Obozn = lObozn; Naim = lNaim; return Result; } catch (Exception e) { throw e; } finally { } } public int AddSoftType(string pObozn, string pNaim) { SqlTransaction Trans = null; try { SqlCommand sql; //int ColRowExecute; int Result; Trans = mvarConnect.BeginTransaction("SampleTransaction"); sql = new SqlCommand(); sql.Transaction = Trans; sql.Connection = mvarConnect; sql.CommandText = " INSERT INTO DirSoftType" + "(Obozn, Naim)" + " VALUES (@Obozn, @Naim);" + " SELECT CAST(scope_identity() AS int)"; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters["@Naim"].Value = pNaim; //ColRowExecute = sql.ExecuteNonQuery(); Result = (int)sql.ExecuteScalar(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Как проверитьчто запись добавлена - критерий???? //if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования SoftType")); } Trans.Commit(); return Result; } catch (Exception e) { if (Trans != null) { Trans.Rollback(); } throw e; } finally { } } public void DeleteSoftType(int pId) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " DELETE FROM DirSoftType" + " WHERE Id = " + pId; ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка удаления SoftType")); } } catch (Exception e) { throw e; } finally { } } //Возвращает справочник типов софта public DataTable GetListSoftType() { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftType.*" + " FROM DirSoftType"; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); return rst; } catch (Exception e) { throw e; } finally { } } public void EditSoftType(int pId, string pObozn, string pNaim) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоночального заполнения справочника //// sql.CommandText = " UPDATE DirSoftType" //// + " SET Naim = @Naim" //// + " WHERE Id = " + pId; sql.CommandText = " UPDATE DirSoftType" + " SET Naim = @Naim, Obozn = @Obozn" + " WHERE Id = " + pId; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters["@Naim"].Value = pNaim; ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования ITCompany")); } } catch (Exception e) { throw e; } finally { } } # endregion //// public void DeleteSoftware(int pId) //// { //// try //// { //// SqlCommand sql; //// int ColRowExecute; //// sql = new SqlCommand(); //// sql.Connection = mvarConnect; //// sql.CommandText = " DELETE FROM DirSoftware" //// + " WHERE Id = " + pId; //// ColRowExecute = sql.ExecuteNonQuery(); //// if (ColRowExecute != 1) { throw (new CommonException("Ошибка удаления ITCompany")); } //// //// } //// catch (Exception e) { throw e; } //// finally { } //// } public void DeleteSoftware(int pId) { try { SqlCommand sql; int ColRowExecute; mvarTransaction = mvarConnect.BeginTransaction("SampleTransaction"); //Удаляем запись sql = new SqlCommand(); sql.Transaction = mvarTransaction; sql.Connection = mvarConnect; sql.CommandText = " DELETE FROM DirSoftware" + " WHERE Id = " + pId; ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка удаления ITCompany")); } //Возвращаем максимальное значение Id у котрого поле икримент int lMaxId; lMaxId = GetLastIdSoftware(); //Сбрасываем до максимального значения ResetFieldIncrement("DirSoftware", lMaxId); mvarTransaction.Commit(); } catch (Exception e) { if (mvarTransaction != null) { mvarTransaction.Rollback(); } throw e; } finally { mvarTransaction = null; } } //Сбрасывает поле инкримента в указанной табоице, до указанного значения private void ResetFieldIncrement(string pTable, int pNewIncrement) { try { SqlCommand sql; //SqlDataReader rst; sql = new SqlCommand(); sql.Transaction = mvarTransaction; sql.Connection = mvarConnect; //sql.CommandText = "DBCC CHECKIDENT(@Table, NORESEED)"; sql.CommandText = "DBCC CHECKIDENT(@Table, RESEED, @NewIncrement)"; sql.Parameters.Add("@Table", SqlDbType.NVarChar); sql.Parameters["@Table"].Direction = ParameterDirection.Input; //sql.Parameters["@Table"].Value = "MrpData.dbo.DirSoftware"; sql.Parameters["@Table"].Value = pTable; sql.Parameters.Add("@NewIncrement", SqlDbType.Int); sql.Parameters["@NewIncrement"].Direction = ParameterDirection.Input; sql.Parameters["@NewIncrement"].Value = pNewIncrement; ////sql.Parameters.Add("@CurId", SqlDbType.Int); ////sql.Parameters["@CurId"].Direction = ParameterDirection.ReturnValue; sql.ExecuteNonQuery(); ////int ffff = (int)sql.Parameters["@CurId"].Value; } catch (Exception e1) { throw e1; } finally { } } //Вернуть последний код ИД Software public int GetLastIdSoftware() { try { SqlCommand sql; SqlDataReader rst; int lLastIdSoftware; sql = new SqlCommand(); sql.Transaction = mvarTransaction; sql.Connection = mvarConnect; sql.CommandText = " SELECT MAX(DISTINCT Id) AS LastId" + " FROM DirSoftware"; rst = sql.ExecuteReader(); if (rst.HasRows == true) { rst.Read(); lLastIdSoftware = (int)rst["LastId"]; } else { throw (new CommonException("Нет Id Software")); } rst.Close(); return lLastIdSoftware; } catch (Exception e) { throw e; } finally { } } public void EditSoftware(int pId, string pObozn, string pNaim, int pDeveloper, int pHolder) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоночального заполнения справочника //// sql.CommandText = " UPDATE DirSoftware" //// + " SET Naim = @Naim, Holder = @Holder, Developer = @Developer" //// + " WHERE Id = " + pId; sql.CommandText = " UPDATE DirSoftware" + " SET Naim = @Naim, Holder = @Holder, Developer = @Developer, Obozn = @Obozn" + " WHERE Id = " + pId; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters.Add("@Developer", SqlDbType.Int); sql.Parameters.Add("@Holder", SqlDbType.Int); sql.Parameters["@Naim"].Value = pNaim; if (pDeveloper == 0) { sql.Parameters["@Developer"].Value = DBNull.Value; } else { sql.Parameters["@Developer"].Value = pDeveloper; } if (pHolder == 0) { sql.Parameters["@Holder"].Value = DBNull.Value; } else { sql.Parameters["@Holder"].Value = pHolder; } ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования Software")); } } catch (Exception e) { throw e; } finally { } } public void EditITCompany(int pId, string pObozn, string pNaim) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоночального заполнения справочника //// sql.CommandText = " UPDATE DirITCompany" //// + " SET Naim = @Naim" //// + " WHERE Id = " + pId; sql.CommandText = " UPDATE DirITCompany" + " SET Naim = @Naim, Obozn = @Obozn" + " WHERE Id = " + pId; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters["@Naim"].Value = pNaim; ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования ITCompany")); } } catch (Exception e) { throw e; } finally { } } //Возвращает справочник компаний public DataTable GetListSoftware() { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware"; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); return rst; } catch (Exception e) { throw e; } finally { } } #region {ITCompany} //Возвращает справочник компаний public DataTable GetListITCompany() { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirITCompany.*" + " FROM DirITCompany"; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); return rst; } catch (Exception e) { throw e; } finally { } } public bool CheckRelationITCompany(int pId) { try { bool Result; if (CheckRelatITCompSoftDev(pId) == false & CheckRelatITComSoftHold(pId) == false) { Result = false; } else { Result = true; } return Result; } catch (Exception e) { throw e; } finally { } } //Проверка связи ИТ компании с разработчиком софта private bool CheckRelatITCompSoftDev(int pId) { try { SqlCommand sql; SqlDataReader rst; bool Result; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware" + " WHERE Developer = " + pId; rst = sql.ExecuteReader(); if (rst.HasRows == true) { Result = true; } else { Result = false; } rst.Close(); return Result; } catch (Exception e) { throw e; } finally { } } //Проверка связи ИТ компании с владельцем софта private bool CheckRelatITComSoftHold(int pId) { try { SqlCommand sql; SqlDataReader rst; bool Result; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware" + " WHERE Holder = " + pId; rst = sql.ExecuteReader(); if (rst.HasRows == true) { Result = true; } else { Result = false; } rst.Close(); return Result; } catch (Exception e) { throw e; } finally { } } public void DeleteITCompany(int pId) { try { SqlCommand sql; int ColRowExecute; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " DELETE FROM DirITCompany" + " WHERE Id = " + pId; ColRowExecute = sql.ExecuteNonQuery(); if (ColRowExecute != 1) { throw (new CommonException("Ошибка удаления ITCompany")); } } catch (Exception e) { throw e; } finally { } } public int AddITCompany(string pObozn, string pNaim) { SqlTransaction Trans = null; try { SqlCommand sql; //int ColRowExecute; int Result; Trans = mvarConnect.BeginTransaction("SampleTransaction"); sql = new SqlCommand(); sql.Transaction = Trans; sql.Connection = mvarConnect; sql.CommandText = " INSERT INTO DirITCompany" + "(Obozn, Naim)" + " VALUES (@Obozn, @Naim);" + " SELECT CAST(scope_identity() AS int)"; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters["@Naim"].Value = pNaim; ////ColRowExecute = sql.ExecuteNonQuery(); Result = (int)sql.ExecuteScalar(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Как проверитьчто запись добавлена - критерий???? ////if (ColRowExecute != 1) { throw (new CommonException("Ошибка редактирования ITCompany")); } Trans.Commit(); return Result; } catch (Exception e) { if (Trans != null) { Trans.Rollback(); } throw e; } finally { } } public bool GetITCompany(int Id, out string Obozn, out string Naim) { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; DataRow row; bool Result; string lObozn; string lNaim; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirITCompany.*" + " FROM DirITCompany" + " WHERE Id = " + Id; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); if (rst.Rows.Count == 1) { row = rst.Rows[0]; lObozn = (string)row["Obozn"]; if (Convert.IsDBNull(row["Naim"]) == true) { lNaim = ""; } else { lNaim = (string)row["Naim"]; } Result = true; } else { lObozn = ""; lNaim = ""; Result = false; } Obozn = lObozn; Naim = lNaim; return Result; } catch (Exception e) { throw e; } finally { } } #endregion #region {Software} public int AddSoftware(string pObozn, string pNaim,int pHolder, int pDeveloper) { SqlTransaction Trans = null; try { SqlCommand sql; int Result; Trans = mvarConnect.BeginTransaction("SampleTransaction"); sql = new SqlCommand(); sql.Transaction = Trans; sql.Connection = mvarConnect; sql.CommandText = " INSERT INTO DirSoftware" + "(Obozn, Naim, Holder, Developer)" + " VALUES (@Obozn, @Naim, @Holder, @Developer);" + " SELECT CAST(scope_identity() AS int)"; sql.Parameters.Add("@Obozn", SqlDbType.NVarChar); sql.Parameters.Add("@Naim", SqlDbType.NVarChar); sql.Parameters.Add("@Holder", SqlDbType.Int); sql.Parameters.Add("@Developer", SqlDbType.Int); sql.Parameters["@Obozn"].Value = pObozn; sql.Parameters["@Naim"].Value = pNaim; if (pDeveloper == 0) { sql.Parameters["@Developer"].Value = DBNull.Value; } else { sql.Parameters["@Developer"].Value = pDeveloper; } if (pHolder == 0) { sql.Parameters["@Holder"].Value = DBNull.Value; } else { sql.Parameters["@Holder"].Value = pHolder; } Result = (int)sql.ExecuteScalar(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Как проверитьчто запись добавлена - критерий???? Trans.Commit(); return Result; } catch (Exception e) { if (Trans != null) { Trans.Rollback(); } throw e; } finally { } } public bool GetSoftware(int Id, out string Obozn, out string Naim, out int Holder, out int Developer) { try { SqlCommand sql; DataTable rst; SqlDataAdapter adp; DataRow row; bool Result; string lObozn; string lNaim; int lHolder; int lDeveloper; sql = new SqlCommand(); sql.Connection = mvarConnect; sql.CommandText = " SELECT DirSoftware.*" + " FROM DirSoftware" + " WHERE Id = " + Id; adp = new SqlDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); if (rst.Rows.Count == 1) { row = rst.Rows[0]; lObozn = (string)row["Obozn"]; if (Convert.IsDBNull(row["Naim"]) == true) { lNaim = ""; } else { lNaim = (string)row["Naim"]; } if (Convert.IsDBNull(row["Holder"]) == true) { lHolder = 0; } else { lHolder = (int)row["Holder"]; } if (Convert.IsDBNull(row["Developer"]) == true) { lDeveloper = 0; } else { lDeveloper = (int)row["Developer"]; } Result = true; } else { lObozn = ""; lNaim = ""; lHolder = 0; lDeveloper = 0; Result = false; } Obozn = lObozn; Naim = lNaim; Holder = lHolder; Developer = lDeveloper; return Result; } catch (Exception e) { throw e; } finally { } } #endregion protected TSysMrpZzva(SqlConnection pConnect) { try { mvarConnect = pConnect; } catch (Exception e) { throw e; } finally { } } public static TSysMrpZzva GetSystem() { try { if (mvarSysMrpZzva == null){mvarSysMrpZzva = GetSysMrpZzva();} return mvarSysMrpZzva; } catch (Exception e) { throw e; } finally { } } private static TSysMrpZzva GetSysMrpZzva() { string lConnectStr; SqlConnection lConnect; TSysMrpZzva lSysMrpZzva; try { //!!!!!!!!!!!!! //достаем Connect из установок ////Connect = RegisterLokal.GetSetting("Common", "SysBuhuchConnect"); //lConnectStr = "Data Source=TEH-SRV;Initial Catalog=MrpData;Integrated Security=True;"; //lConnectStr = lConnectStr + "User ID=" + User + ";Password=" + Password + ";"; lConnectStr = "Data Source=TEH-SRV;Initial Catalog=MrpData;Integrated Security=True;" + "User ID=Sergey;Password=Cl254J;"; lConnect = new SqlConnection(lConnectStr); lConnect.Open(); lSysMrpZzva = new TSysMrpZzva(lConnect); return lSysMrpZzva; } catch (Exception e) { throw e; } finally { } } public string TestConnect(){return "YesConnectMrpZzva";} } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TSysMrpZzva.cs
C#
bsd
36,695
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; using System.Data; namespace Zzva.ESB { public class TSysBko { private static TSysBko mvarSysBko; private OleDbConnection mvarConnect; protected TSysBko(OleDbConnection pConnect) { try { mvarConnect = pConnect; } catch (Exception e) { throw e; } finally { } } public static TSysBko GetSystem() { try { if (mvarSysBko == null) { mvarSysBko = GetSysBko(); } return mvarSysBko; } catch (Exception e) { throw e; } finally { } } private static TSysBko GetSysBko() { string lConnectStr; OleDbConnection lConnect; TSysBko lSysBko; try { //!!!!!!!!!!!!! //достаем Connect из установок ////Connect = RegisterLokal.GetSetting("Common", "SysBuhuchConnect"); //lConnectStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\srvsapr\BKO\database\basekomp.mdb;Jet OLEDB:Database Password=Cl254J"; lConnectStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\srvsapr\BKO\database\basekomp.mdb"; //lConnectStr = lConnectStr + "User ID=" + User + ";Password=" + Password + ";"; lConnect = new OleDbConnection(lConnectStr); lConnect.Open(); lSysBko = new TSysBko(lConnect); return lSysBko; } catch (Exception e) { throw e; } finally { } } public string TestGetNetNamePk(int Id) { try { OleDbCommand sql; DataTable rst; OleDbDataAdapter adp; DataRow row; string NetNamePk; sql = new OleDbCommand(); sql.Connection = mvarConnect; //sql.CommandText = " SELECT DSE, DISP, NAIMDSE, RAZD" // + " FROM DSE" // + " WHERE DSE_ID = " + Id; sql.CommandText = " SELECT NET_NAME" + " FROM kompy" + " WHERE ID = " + Id; adp = new OleDbDataAdapter(); adp.SelectCommand = sql; rst = new DataTable(); adp.Fill(rst); if (rst.Rows.Count == 1) { row = rst.Rows[0]; NetNamePk = (string)row["NET_NAME"]; } else { NetNamePk = "Нет ПК"; } return NetNamePk; } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TSysBko.cs
C#
bsd
3,098
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; using System.Reflection; namespace Zzva.ESB { public class TSysBuhuch { private static TSysBuhuch mvarSysBuhuch; private object mvarConnect; protected TSysBuhuch(object pConnect) { try { mvarConnect = pConnect; } catch (Exception e) { throw e; } finally { } } public static TSysBuhuch GetSystem() { try { if (mvarSysBuhuch == null) { mvarSysBuhuch = GetSysBuhuch(); } return mvarSysBuhuch; } catch (Exception e) { throw e; } finally { } } private static TSysBuhuch GetSysBuhuch() { object lConnect; object[] ParamSys1C = new object[3]; string lConnectStr; System.Type Sys1cType; object RMTrade; bool Result; TSysBuhuch lSysBuhuch; try { Sys1cType = Type.GetTypeFromProgID("V77.Application"); lConnect = Activator.CreateInstance(Sys1cType); RMTrade = Sys1cType.InvokeMember("RMTrade", BindingFlags.Public | BindingFlags.InvokeMethod, null, lConnect, null); ParamSys1C[0] = RMTrade; //достаем Connect из установок ////Connect = RegisterLokal.GetSetting("Common", "SysBuhuchConnect"); ////Connect = @"\\buh-srv\1C_Data\Украина2005\ZVA2007\"; ////Connect = @"\\buh-srv\1C_Data\Украина2005\ZVA2007_Test\"; lConnectStr = @"E:\1C_Data\Украина2005\ZVA2007\"; lConnectStr = @"/d" + @lConnectStr + " /n" + "SysCalcul" + " /p" + "11205"; ParamSys1C[1] = lConnectStr; ParamSys1C[2] = @"NO_SPLASH_SHOW"; Result = (bool)Sys1cType.InvokeMember(@"Initialize", BindingFlags.Public | BindingFlags.InvokeMethod, null, lConnect, ParamSys1C); if (Result == false) { throw (new Zzva.Common.CommonException("Не можем подключится к системе 1СБухгалтерия")); } lSysBuhuch = new TSysBuhuch(lConnect); return lSysBuhuch; } catch (Exception e) { throw e; } finally { } } public bool GetNomencl(string Obozn, out string Naim, out string Ei) { try { object ListNomencl; object[] ListNomenclParam = new object[1]; double ResultListNomenclItem; object ListNomenclItem; object[] ListNomenclItemParam = new object[1]; bool Result; string lNaim; string lEi; object EiC1; ListNomenclParam[0] = @"Справочник.ТМЦ"; ListNomencl = mvarConnect.GetType().InvokeMember(@"CreateObject", BindingFlags.Public | BindingFlags.InvokeMethod, null, mvarConnect, ListNomenclParam); if (ListNomencl == null) { throw (new Zzva.Common.CommonException("Не можем открыть справочник TMC")); } ListNomenclItemParam[0] = Obozn; ResultListNomenclItem = (Double)ListNomencl.GetType().InvokeMember(@"FindByCode", BindingFlags.Public | BindingFlags.InvokeMethod, null, ListNomencl, ListNomenclItemParam); if (ResultListNomenclItem == 1) { ListNomenclItem = ListNomencl.GetType().InvokeMember(@"CurrentItem", BindingFlags.Public | BindingFlags.InvokeMethod, null, ListNomencl, null); lNaim = (string)ListNomenclItem.GetType().InvokeMember(@"ПолнНаименование", BindingFlags.Public | BindingFlags.GetProperty, null, ListNomenclItem, null); Naim = lNaim.TrimEnd(); EiC1 = (object)ListNomenclItem.GetType().InvokeMember(@"БазЕдиница", BindingFlags.Public | BindingFlags.GetProperty, null, ListNomenclItem, null); lEi = (string)EiC1.GetType().InvokeMember(@"Identifier", BindingFlags.Public | BindingFlags.InvokeMethod, null, EiC1, null); Ei = lEi.TrimEnd(); Result = true; } else { Naim = ""; Ei = ""; Result = false; } return Result; } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TSysBuhuch.cs
C#
bsd
5,175
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.ESB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.ESB")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f9b3cc79-4f96-403f-99fc-01aaa647a6a2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/ESB/ESB/Zzva.ESB/Properties/AssemblyInfo.cs
C#
bsd
1,436
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using Zzva.Common; using System.Data; namespace Zzva.ESB { public class TSysWorkprogress { private static TSysWorkprogress mvarSysWorkprogress; private SqlConnection mvarConnect; protected TSysWorkprogress(SqlConnection pConnect) { try { mvarConnect = pConnect; } catch (Exception e) { throw e; } finally { } } public static TSysWorkprogress GetSystem() { try { if (mvarSysWorkprogress == null) { mvarSysWorkprogress = GetSysWorkprogress(); } return mvarSysWorkprogress; } catch (Exception e) { throw e; } finally { } } private static TSysWorkprogress GetSysWorkprogress() { string lConnectStr; SqlConnection lConnect; TSysWorkprogress lSysWorkprogress; try { //!!!!!!!!!!!!! //достаем Connect из установок ////Connect = RegisterLokal.GetSetting("Common", "SysBuhuchConnect"); //lConnectStr = "Data Source=TEH-SRV;Initial Catalog=NezavProizv;Integrated Security=True;"; //lConnectStr = lConnectStr + "User ID=" + User + ";Password=" + Password + ";"; lConnectStr = "Data Source=TEH-SRV;Initial Catalog=NezavProizv;Integrated Security=True;" + "User ID=Sergey;Password=Cl254J;"; lConnect = new SqlConnection(lConnectStr); lConnect.Open(); lSysWorkprogress = new TSysWorkprogress(lConnect); return lSysWorkprogress; } catch (Exception e) { throw e; } finally { } } public string TestConnect() { return "YesConnectWorkprogress"; } } }
zzvalib
trunk/ESB/ESB/Zzva.ESB/TSysWorkprogress.cs
C#
bsd
2,164
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.UIWin { public class TOboznAndAlias { public string Obozn; public string Alias; public TOboznAndAlias(string pObozn, string pAlias) { Obozn = pObozn; Alias = pAlias; } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/TOboznAndAlias.cs
C#
bsd
373
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.DomainObject; namespace Zzva.UIWin { public class TDirEventArgs:EventArgs { public TDirBase Dir; //новый объект справки public int Id;//ИД сохрагнненного объекта public TDirEventArgs(TDirBase pDir, int pId) { this.Dir = pDir; this.Id = pId; } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/TDirEventArgs.cs
C#
bsd
492
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Windows; using Zzva.Common; namespace Zzva.UIWin { public partial class TFrmDialBase : Form { //объявляем объект делегата public event EventHandler EventReady; protected bool mvarFlgChanch; public TFrmDialBase() { InitializeComponent(); mvarFlgChanch = false; } private void CancelWithCheckChanch() { try { if (mvarFlgChanch == true) { string caption = "Выполнена корректировка!"; string message = "Сохранить изменения?"; MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel; DialogResult result = MessageBox.Show(message, caption, buttons); switch (result) { case DialogResult.Yes: Ready(); break; case DialogResult.Cancel: break; case DialogResult.No: Cancel(); break; default: throw (new CommonException("Нет ответа диалога")); } } else{Cancel();} } catch (Exception e){MessageBox.Show(e.Message);} finally { } } protected void FireEventReady(EventArgs pEventArgs) { try { if (EventReady != null) EventReady(this, pEventArgs); } catch (Exception e) { throw e; } finally { } } protected virtual void Ready() { try { FireEventReady(EventArgs.Empty); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } private void cmdReady_Click(object sender, EventArgs e) { Ready(); } private void cmdCancel_Click(object sender, EventArgs e) { //''Cancel(); CancelWithCheckChanch(); } private void Cancel() { this.Close(); } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/TFrmDialBase.cs
C#
bsd
2,797
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.UIWin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.UIWin")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("128c7ae2-17e8-422c-9c1e-c12cd5a02cef")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Properties/AssemblyInfo.cs
C#
bsd
1,440
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.Common; using System.Collections.ObjectModel; using Zzva.DomainObjectReg; using System.Collections; namespace Zzva.UIWin { public partial class TFrmFilterByValue : TFrmDialBase { TRegDirBase mvarRegDirBase; public TFrmFilterByValue(TRegDirBase pRegDirBase, Collection<string> pListFieldAlias, string pFieldAliasDefault) : base() { try { string lId = "Id"; InitializeComponent(); mvarRegDirBase = pRegDirBase; Collection<string> lListFieldAliasWithoutId = new Collection<string>(); foreach (string lItem in pListFieldAlias) { if (lItem != lId) { lListFieldAliasWithoutId.Add(lItem); } } if (lListFieldAliasWithoutId.Count <= 0) throw (new CommonException("Отсутсвуют поля для фильтрации")); lstFieldAlias.DataSource = lListFieldAliasWithoutId; if ((pFieldAliasDefault != lId) & (pFieldAliasDefault != "")) { lstFieldAlias.Text = pFieldAliasDefault; } UpdateListFieldValue(); } catch (Exception e1) { throw e1; } finally { } } private void lstFilterValue_TextChanged(object sender, EventArgs e) { ////lstFilterValue.DroppedDown = true; } private void lstFilterValue_Enter(object sender, EventArgs e) { ////lstFilterValue.DroppedDown = true; } private void lstFieldAlias_TextChanged(object sender, EventArgs e) { UpdateListFieldValue(); } public TFrmFilterByValue(TRegDirBase pRegDirBase, Collection<string> pListFieldAlias) : base() { try { InitializeComponent(); mvarRegDirBase = pRegDirBase; Collection<string> lListFieldAliasWithoutId = new Collection<string>(); foreach (string lItem in pListFieldAlias) { if (lItem != "Id") { lListFieldAliasWithoutId.Add(lItem); } } if (lListFieldAliasWithoutId.Count <= 0) throw (new CommonException("Отсутсвуют поля для фильтрации")); lstFieldAlias.DataSource = lListFieldAliasWithoutId; UpdateListFieldValue(); } catch (Exception e1) { throw e1; } finally { } } //Обновить список значений текущего поля private void UpdateListFieldValue() { try { string lAlias; lAlias = lstFieldAlias.Text; if (lAlias == "") { throw (new CommonException("Не задано имя поля")); } Collection<string> lListValue = mvarRegDirBase.GetListUniqueValueForAliasField(lAlias); lstFilterValue.DataSource = lListValue; } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } ////public TFrmFilterByValue() ////{ //// InitializeComponent(); ////} protected override void Ready() { try { string lAlias = lstFieldAlias.Text.Trim() ; string lFilterValue = lstFilterValue.Text.Trim() ; if (lAlias == "") { throw (new CommonException("Не задано имя поля")); } if (lFilterValue == "") { throw (new CommonException("Не задано значение фильтра")); } Collection<TFieldValue> lListFieldValue = new Collection<TFieldValue>(); TFieldValue lFieldValue; lFieldValue = new TFieldValue("Alias", lAlias); lListFieldValue.Add(lFieldValue); lFieldValue = new TFieldValue("FilterValue", lFilterValue); lListFieldValue.Add(lFieldValue); TListFieldValueEventArgs lListFieldValueEventArgs = new TListFieldValueEventArgs(lListFieldValue); FireEventReady(lListFieldValueEventArgs); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/TFrmFilterByValue.cs
C#
bsd
5,197
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; ////using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.Common; using Zzva.DomainObject; namespace Zzva.UIWin { public partial class TFrmDirBase : TFrmDialBase { public TFrmDirBase():base () { InitializeComponent(); } protected override void Ready() { try { throw (new CommonException("Функция Ready не определена")); } catch (Exception e) { throw e; } finally { } } private void txtNaim_TextChanged(object sender, EventArgs e) { mvarFlgChanch = true; } private void txtObozn_TextChanged(object sender, EventArgs e) { mvarFlgChanch = true; } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmDirBase.cs
C#
bsd
1,055
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Collections.ObjectModel; using Zzva.Common; using Zzva.DomainObjectReg; using Zzva.DomainObject; using System.Reflection; using System.Collections; namespace Zzva.UIWin { public partial class TFrmRegDirBase : Form { protected int mvarFlgColumnIndexCur; //объявляем объект делегата public event EventHandler EventReady; protected bool mvarFlgStateLoadForm; //состояние загрузки формы //protected TRegDirBase mvarRegDirBase; //Возвращает алиса текущего поля ////private string GetCurColumnObozn() protected string GetCurColumnObozn() { try { DataGridViewCell lCurCell; DataGridViewColumn lCurColumn; string lCurColumnAlias; ////string lCurColumnObozn; lCurCell = dgvMain.CurrentCell; if (lCurCell != null) { lCurColumn = dgvMain.Columns[lCurCell.ColumnIndex]; lCurColumnAlias = lCurColumn.Name; ////lCurColumnObozn = lCurColumnAlias; } else //нет текущей ячейки { ////lCurColumnObozn = ""; lCurColumnAlias = ""; } ////return lCurColumnObozn; return lCurColumnAlias; } catch (Exception e1) { throw e1; } finally { } } protected void RegDirBase_FindDir(object lSender, EventArgs lEventArgs) { { try { bool lResult; TDirBase lCurDir; int lCurIndex; TDirFindEventArgs lDirFindEventArgs = (TDirFindEventArgs)lEventArgs; lResult = lDirFindEventArgs.Result; lCurDir = lDirFindEventArgs.CurDir; if (lResult == false) { ////throw (new CommonException("Ничего не найдено")); } else { lCurIndex = GetIndexForId(dgvMain.Rows, lCurDir.Id); if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); } dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur]; } } catch (Exception e1) { throw e1; } finally { } } } //Возвращает список полей для источника protected Collection<string> GetListAliasField() { try { object lDataSourse = dgvMain.DataSource; IList lListDataSource; if (lDataSourse == null) {throw (new CommonException("Нет данных"));} if (lDataSourse is IList){lListDataSource = (IList)lDataSourse;} else { throw (new CommonException("В источнике данных содержится не Ilist")); } if (lListDataSource.Count <= 0) { throw (new CommonException("Нет записей")); } object lItem; lItem = lListDataSource[0]; Type lTypeItem; PropertyInfo[] myPropertyInfo; lTypeItem = lItem.GetType(); myPropertyInfo = lTypeItem.GetProperties(); Collection<string> lListAliasField = new Collection<string>(); for (int i = 0; i < myPropertyInfo.Length; i++) { lListAliasField.Add(myPropertyInfo[i].Name); } return lListAliasField; } catch (Exception e1) { throw e1; } finally { } } protected void FrmFilterByValue_Ready(object Sender, EventArgs ArgsBase) { try { string lAlias; string lFilterValue; if (ArgsBase is TListFieldValueEventArgs) { TFieldValue lFieldValue; TListFieldValueEventArgs lListFieldValueEventArgs = (TListFieldValueEventArgs)ArgsBase; Collection<TFieldValue> lListFieldValue = lListFieldValueEventArgs.ListFieldValue; if (lListFieldValue.Count != 2) { throw (new CommonException("Не соответсвует число параметров")); } lFieldValue = lListFieldValue.SingleOrDefault(h => h.Field == "Alias"); if (lFieldValue == null) { throw (new CommonException("Отсутсвует параметр Alias")); } lAlias = (string)lFieldValue.Value; lFieldValue = lListFieldValue.SingleOrDefault(h => h.Field == "FilterValue"); if (lFieldValue == null) { throw (new CommonException("Отсутсвует параметр FilterValue")); } lFilterValue = (string)lFieldValue.Value; } else { throw (new CommonException("Не те аргументы в ответе")); } AddFilterForColumn(lFilterValue, lAlias); } catch (Exception e1) { throw e1; } finally { } } private void cmdFilterByValue_Click(object sender, EventArgs e) { FilterByValue(); } protected virtual void FilterByValue() { try { ////TFrmFilterByValue FrmFilterByValue; ////FrmFilterByValue = new TFrmFilterByValue(); ////FrmFilterByValue.EventReady += new EventHandler(FrmFilterByValue_Ready); ////FrmFilterByValue.ShowDialog(); throw (new CommonException("Метод не реализован")); } catch (Exception e1) { throw e1; } finally { } } ////private string GetCurSelectValue() ////{ //// try //// { //// string lSelectValue; //// lSelectValue = txtFilter.Text; //// return lSelectValue; //// } //// catch (Exception e1) { throw e1; } //// finally { } ////} private void FilterReadAndAdd() { try { ////TFilterValue lFilteValue; string lCurColumnObozn; string lFilterTemplate; lCurColumnObozn = GetCurColumnObozn(); ////lFilterTemplate = GetCurSelectValue().Trim(); lFilterTemplate = txtFilter.Text; ////if (lCurColumnObozn != "")//просто нажал кнопку без выделения столбца, игнорируем... ////{ //// if (lFilterTemplate != "") //// { //// lFilteValue = new TFilterValue(lCurColumnObozn, lFilterTemplate); //// FilterAdd(lFilteValue); //// } ////} AddFilterForColumn(lFilterTemplate, lCurColumnObozn); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } //Добавить фильтр для заданного столбца private void AddFilterForColumn(string pFilterTemplate, string pColumnObozn) { try { TFilterValue lFilteValue; if (pColumnObozn != "")//просто нажал кнопку без выделения столбца, игнорируем... { if (pFilterTemplate.Trim() != "") { lFilteValue = new TFilterValue(pColumnObozn, pFilterTemplate.Trim()); FilterAdd(lFilteValue); } } } catch (Exception e) { throw e;} finally { } } private void cmdFilterBySelection_Click(object sender, EventArgs e) { FilterBySelection(); } private void FilterBySelection() { try { DataGridViewTextBoxEditingControl lTextBox; DataGridViewCell lCurCell; System.Windows.Forms.Control lCurCellControl; string lSelectText; object lCurCellValue; int lCurRowIndex; DataGridViewRow lCurRow; int lCurColumnIndex; DataGridViewColumn lCurColumn; string lCurColumnAlias; lCurCell = dgvMain.CurrentCell; if (lCurCell == null) { throw (new CommonException("Выделите ячейку")); } lCurRowIndex = lCurCell.RowIndex; if (lCurRowIndex < 0) { throw (new CommonException("Выделите строку со значениями")); } lCurRow = dgvMain.Rows[lCurRowIndex]; lCurColumnIndex = lCurCell.ColumnIndex; if (lCurColumnIndex < 0) { throw (new CommonException("Выделите столбец со значениями")); } if (lCurColumnIndex == 0) { throw (new CommonException("Выделите текст предметной ячейки")); } lCurColumn = dgvMain.Columns[lCurColumnIndex]; //здесь не должен быть зрительно выделена вся строка if (lCurRow.Selected == true) { throw (new CommonException("Выделите текст в конкретной ячейке")); } Type lType; lType = lCurCell.EditType; // только в контроле есть текст (я так думаю) if (lType.Name != "DataGridViewTextBoxEditingControl") { throw (new CommonException("Это не DataGridViewTextBoxEditingControl")); } lCurCellControl = dgvMain.EditingControl;//спрашиваем состояние режима редактрования конторла if (lCurCellControl == null)//находимся не врежиме редактирования, считываем полное значение { lCurCellValue = lCurCell.Value; // это объект в ячейке lSelectText = lCurCellValue.ToString(); //а это его строковое представление } else { lTextBox = (DataGridViewTextBoxEditingControl)lCurCellControl; lSelectText = lTextBox.SelectedText; } //lSelectText = lSelectText.Trim(); //Имя столбца lCurColumnAlias = lCurColumn.Name; AddFilterForColumn(lSelectText, lCurColumnAlias); } catch (Exception e1){MessageBox.Show(e1.Message); } finally { } } private void dgvMain_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { MakeEditCell(e.RowIndex, e.ColumnIndex); } private void dgvMain_CellClick(object sender, DataGridViewCellEventArgs e) { //MakeEditCell(e.RowIndex,e.ColumnIndex); } private void MakeEditCell(int pCellRow, int pCellColumn) { try { if (pCellRow >= 0 & pCellColumn >= 0) { DataGridViewCell lCell; lCell = dgvMain.Rows[pCellRow].Cells[pCellColumn]; lCell.ReadOnly = false; } } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } private void dgvMain_CellLeave(object sender, DataGridViewCellEventArgs e) { MakeNotEditCell(e.RowIndex, e.ColumnIndex); } private void MakeNotEditCell(int pCellRow, int pCellColumn) { try { DataGridViewCell lCell; lCell = dgvMain.Rows[pCellRow].Cells[pCellColumn]; lCell.ReadOnly = true; } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } #region Report... private void cmdReport_Click(object sender, EventArgs e) { Report(); } protected virtual void Report() { throw (new CommonException("Метод не реализован")); } #endregion protected virtual void FrmDirBase_Ready(object Sender, EventArgs ArgsBase) { throw (new CommonException("Метод не реализован")); } ////protected virtual void AddDir(TDirITCompanyNew pDir) ////{ throw (new CommonException("Метод не реализован")); } #region Find... //Установить курсор на заданном объекте public virtual void FindByDir(TDirBase pDir) { throw (new CommonException("Метод не реализован")); } protected virtual void FindPrev(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } protected virtual void FindNext(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } protected virtual void Find(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } #endregion #region Constructor... public TFrmRegDirBase() { mvarFlgStateLoadForm = true; InitializeComponent(); } #endregion protected void RegDirBase_UpdateList(object lSender, EventArgs lEventArgs) { { try{ViewCurrentList();} catch (Exception e1) { throw e1; } finally { } } } protected virtual void ViewCurrentList() { throw (new CommonException("Метод не реализован")); } //Возвратить индекс строки ДатаГрид по ИД protected int GetIndexForId(DataGridViewRowCollection lGridViewRowCollection, int pId) { try { int lIndex; lIndex = -1; foreach (DataGridViewRow dr in lGridViewRowCollection) { if ((int)(dr.Cells["Id"].Value) == pId) { lIndex = dr.Index; break; } } return lIndex; } catch (Exception e1) { throw e1; } finally { } } #region Find... #region FindPrev... private void cmdFindPrev_Click(object sender, EventArgs e) { FindPrevReadAndSearch(); } private void FindPrevReadAndSearch() { try { TFilterValue lFindValue; lFindValue = GetFindValue(); if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); } FindPrev(lFindValue); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } //// protected virtual void FindPrev(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } #endregion #region FindNext... private void cmdFindNext_Click(object sender, EventArgs e) { FindNextReadAndSearch(); } private void FindNextReadAndSearch() { try { TFilterValue lFindValue; lFindValue = GetFindValue(); if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); } FindNext(lFindValue); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } //// protected virtual void FindNext(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } #endregion #region FindWith0... private void cmdFind_Click(object sender, EventArgs e) { FindReadAndSearch(); } private void FindReadAndSearch() { try { TFilterValue lFindValue; lFindValue = GetFindValue(); if (lFindValue == null) { throw (new CommonException("Не возможно определить критерии поиска")); } Find(lFindValue); } catch (Exception e1){MessageBox.Show(e1.Message);} finally { } } //// protected virtual void Find(TFilterValue pFindValue) { throw (new CommonException("Метод не реализован")); } #endregion //Возвращает критерий поиска //Возвращает null, если //1.критерий поиска пустая строка //2.не возможно определить поле по которому искать private TFilterValue GetFindValue() { try { string lCurColumnObozn; TFilterValue lFindValue; string lFindTemplate; lFindValue = null; lCurColumnObozn = GetCurColumnObozn(); if (lCurColumnObozn != "") { lFindTemplate = txtFind.Text.Trim(); if (lFindTemplate != "") { lFindValue = new TFilterValue(lCurColumnObozn, lFindTemplate); } else { lFindValue = null; } } else { lFindValue = null; } return lFindValue; } catch (Exception e1) { throw e1; } finally { } } #endregion private void dgvMain_CellEnter(object sender, DataGridViewCellEventArgs e) { if (mvarFlgStateLoadForm == false) { mvarFlgColumnIndexCur = dgvMain.CurrentCell.ColumnIndex; } } #region Filter... private void cmdFilterAdd_Click(object sender, EventArgs e) { FilterReadAndAdd(); } protected virtual void FilterAdd(TFilterValue pFilterValue) { throw (new CommonException("Метод не реализован")); } private void cmdFilterDel_Click(object sender, EventArgs e) { FilterDel(); } protected virtual void FilterDel() { throw (new CommonException("Метод не реализован")); } #endregion #region Sort... private void cmdSortasc_Click(object sender, EventArgs e) { SortAcs(); } private void cmdSortdes_Click(object sender, EventArgs e) { SortDes(); } private void SortDes() { try { TSortValue lSortValue; string lCurColumnObozn; lCurColumnObozn = GetCurColumnObozn(); if (lCurColumnObozn != "") { lSortValue = new TSortValue(lCurColumnObozn, ESortType.OrderBackward); Sort(lSortValue); } } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } private void SortAcs() { try { TSortValue lSortValue; string lCurColumnObozn; lCurColumnObozn = GetCurColumnObozn(); if (lCurColumnObozn != "") { lSortValue = new TSortValue(lCurColumnObozn, ESortType.OrderForward); Sort(lSortValue); } } catch (Exception e){MessageBox.Show(e.Message);} finally { } } protected virtual void Sort(TSortValue pSortValue) { throw (new CommonException("Метод не реализован")); } #endregion #region OboznAndAlias... //// private string GetColumnOboznByAlias(string pAlias) //// { //// try //// { //// TOboznAndAlias lOboznAndAlias; //// string lObozn; //// Collection<TOboznAndAlias> lListOboznAndAlias = GetListOboznAndAlias(); //// lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Alias == pAlias); //// if (lOboznAndAlias != null){lObozn = lOboznAndAlias.Obozn;} //// else{lObozn = "";} //// return lObozn; //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// protected virtual Collection<TOboznAndAlias> GetListOboznAndAlias() //// { //// Collection<TOboznAndAlias> lList; //// lList = new Collection<TOboznAndAlias>(); //// lList.Add(new TOboznAndAlias("Id","Id")); //// lList.Add(new TOboznAndAlias("Obozn", "Обозначение")); //// lList.Add(new TOboznAndAlias("Naim", "Наименование")); //// return lList; //// } //// private string GetColumnAliasByObozn(string pObozn) //// { //// try //// { //// TOboznAndAlias lOboznAndAlias; //// string lAlias; //// Collection<TOboznAndAlias> lListOboznAndAlias = GetListOboznAndAlias(); //// lOboznAndAlias = lListOboznAndAlias.FirstOrDefault(d => d.Obozn == pObozn); //// if (lOboznAndAlias != null) { lAlias = lOboznAndAlias.Alias; } //// else { lAlias = ""; } //// return lAlias; //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } #endregion #region Delete... private void cmdDelete_Click(object sender, EventArgs e) { DeleteWithDialUser(); } private void DeleteWithDialUser() { try { string caption = "Удаление!"; string message = "Удалить текущую запись?"; MessageBoxButtons buttons = MessageBoxButtons.OKCancel; DialogResult result = MessageBox.Show(message, caption, buttons); switch (result) { case DialogResult.OK: Delete(); break; case DialogResult.Cancel: break; default: throw (new CommonException("Нет ответа диалога")); } } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } protected virtual void Delete(){throw (new CommonException("Метод не реализован")); } #endregion #region Edit... private void cmdEdit_Click(object sender, EventArgs e) { Edit(); } protected virtual void Edit() { throw (new CommonException("Метод не реализован")); } #endregion #region Add... private void cmdAdd_Click(object sender, EventArgs e) { Add(); } protected virtual void Add() {throw (new CommonException("Метод не реализован")); } #endregion #region Ready... protected void FireEventReady(EventArgs pEventArgs) { try { if (EventReady != null) EventReady(this, pEventArgs); } catch (Exception e) { throw e; } finally { } } protected virtual void Ready() { try { FireEventReady(EventArgs.Empty); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } private void cmdReady_Click(object sender, EventArgs e) { Ready(); } #endregion #region SetCurItem... private void dgvMain_RowEnter(object sender, DataGridViewCellEventArgs e) {RowEnter(sender, e); } private void RowEnter(object sender, DataGridViewCellEventArgs e) { try { if (mvarFlgStateLoadForm == false) { int lId; DataGridViewRow lRowCur; lRowCur = ((DataGridView)sender).Rows[e.RowIndex]; lId = (int)lRowCur.Cells["Id"].Value; SetCurItem(lId); } } catch (Exception e1) { throw e1; } finally { } } protected virtual void SetCurItem(int pCurItem) { try { throw (new CommonException("Метод не реализован")); } catch (Exception e) { throw e; } finally { } } #endregion private void TFrmRegDirBase_Shown(object sender, EventArgs e) { mvarFlgStateLoadForm = false; } #region Cancel... private void cmdCancel_Click(object sender, EventArgs e) { Cancel(); } private void Cancel() { this.Close(); } #endregion } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmRegDirBase.cs
C#
bsd
28,592
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Zzva.Common; using Zzva.DomainObject; namespace Zzva.UIWin { public partial class TFrmDirSoftType :TFrmDirBase { private TDirSoftTypeNew mvarDirSoftTypeNew; private int mvarId; //ИД корректируемого объета, если постоянный то = 0 // создание нового объекта public TFrmDirSoftType(): base() { InitializeComponent(); mvarDirSoftTypeNew = new TDirSoftTypeNew(); mvarId = 0; txtObozn.Text = mvarDirSoftTypeNew.Obozn; txtNaim.Text = mvarDirSoftTypeNew.Naim; mvarFlgChanch = false; } //на вход существующий объект public TFrmDirSoftType(TDirSoftType pDirSoftType): base() { InitializeComponent(); mvarDirSoftTypeNew = GetCopyDir(pDirSoftType); mvarId = pDirSoftType.Id; txtObozn.Text = mvarDirSoftTypeNew.Obozn; txtNaim.Text = mvarDirSoftTypeNew.Naim; mvarFlgChanch = false; } private TDirSoftTypeNew GetCopyDir(TDirSoftType pDirSoftType) { TDirSoftTypeNew lDirSoftTypeNew; string lObozn; string lNaim; lObozn = (string)pDirSoftType.GetAttrib("Obozn"); lNaim = (string)pDirSoftType.GetAttrib("Naim"); lDirSoftTypeNew = new TDirSoftTypeNew(lObozn, lNaim); return lDirSoftTypeNew; } protected override void Ready() { try { string lObozn = txtObozn.Text; string lNaim = txtNaim.Text; mvarDirSoftTypeNew.Obozn = lObozn; mvarDirSoftTypeNew.Naim = lNaim; TDirEventArgs lDirEventArgs; lDirEventArgs = new TDirEventArgs(mvarDirSoftTypeNew, mvarId); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e){MessageBox.Show(e.Message);} finally { } } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmDirSoftType.cs
C#
bsd
2,361
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Zzva.DomainObjectReg; using Zzva.Common; using Zzva.DomainObject; using System.Collections.ObjectModel; using Zzva.Report; using Zzva.ReportExcel; using System.Collections; namespace Zzva.UIWin { public partial class TFrmRegDirSoftType : TFrmRegDirBase { TRegDirSoftType mvarRegDirSoftType; protected override void FilterByValue() { try { TFrmFilterByValue FrmFilterByValue; ////FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirSoftType, GetListAliasField()); FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirSoftType, GetListAliasField(), GetCurColumnObozn()); FrmFilterByValue.EventReady += new EventHandler(FrmFilterByValue_Ready); FrmFilterByValue.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } protected override void Report() { try { TReportBase lReportBase; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаемимя класса Отчета из установок //и по технологии Позднего связывания //создаем объект Отчет //А пока так lReportBase = new TReportExcel(); lReportBase.Title = mvarRegDirSoftType.TitleFull; object lList = mvarRegDirSoftType.GetCurListView(); //lReportBase.CreateReport(lList); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаем парметр из установок: //Как мы хтим видеть поля отчета, представляющие объекты: //развернутыми по всем полям, или только строковое представление //А пока так по умолчанию lReportBase.CreateReport(lList, EReportFieldView.ExpandAsObject); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void ViewCurrentList() { try { object hhh = mvarRegDirSoftType.GetCurListView(); bool lFlgStateLoadForm; lFlgStateLoadForm = mvarFlgStateLoadForm; if (mvarFlgStateLoadForm == false) { mvarFlgStateLoadForm = true; } dgvMain.DataSource = null; dgvMain.Rows.Clear(); dgvMain.DataSource = hhh; DataGridViewColumn lDataGridViewColumn = dgvMain.Columns["Id"]; lDataGridViewColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; lDataGridViewColumn.Resizable = DataGridViewTriState.False; lDataGridViewColumn.Width = 0; mvarFlgStateLoadForm = lFlgStateLoadForm; TDirSoftType lCurItem; lCurItem = (TDirSoftType)mvarRegDirSoftType.GetCurItem(); int lCurIndex; if (lCurItem != null) { lCurIndex = GetIndexForId(dgvMain.Rows, lCurItem.Id); if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); } dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur]; } this.Text = mvarRegDirSoftType.TitleFull; } catch (Exception e) { throw e; } finally { } } #region(constructor) public TFrmRegDirSoftType(TRegDirSoftType pRegDirSoftType) : base() { InitializeComponent(); mvarRegDirSoftType = pRegDirSoftType; ViewCurrentList(); if (mvarRegDirSoftType.CheckEventUpdateListIsNull() == true) {mvarRegDirSoftType.EventUpdateList += new EventHandler(RegDirBase_UpdateList);} if (mvarRegDirSoftType.CheckEventFindDirIsNull() == true) {mvarRegDirSoftType.EventFindDir += new EventHandler(RegDirBase_FindDir);} } #endregion protected override void SetCurItem(int pCurItem) { try { mvarRegDirSoftType.SetCurItem(pCurItem); } catch (Exception e1) { throw e1; } finally { } } protected override void FrmDirBase_Ready(object Sender, EventArgs ArgsBase) { try { int lId; TDirSoftTypeNew lDir; TDirEventArgs lDirEventArgs; lDirEventArgs = (TDirEventArgs)ArgsBase; lId = lDirEventArgs.Id; lDir = (TDirSoftTypeNew)lDirEventArgs.Dir; if (lId == 0) { AddDir(lDir); } else { EditDir(lDir); } } catch (Exception e) { throw e; } finally { } } #region Find... //Установить курсор на заданном объекте public override void FindByDir(TDirBase pDir) { try{mvarRegDirSoftType.FindByDir(pDir);} catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void FindPrev(TFilterValue pFindValue) { try{mvarRegDirSoftType.FindPrev(pFindValue);} catch (Exception e1) { throw e1; } finally { } } protected override void FindNext(TFilterValue pFindValue) { try{mvarRegDirSoftType.FindNext(pFindValue);} catch (Exception e1) { throw e1; } finally { } } protected override void Find(TFilterValue pFindValue) { try{mvarRegDirSoftType.Find(pFindValue);} catch (Exception e1) { throw e1; } finally { } } #endregion #region Filter... protected override void FilterAdd(TFilterValue pFilterValue) { try{mvarRegDirSoftType.FilterAdd(pFilterValue);} catch (Exception e1) { throw e1; } finally { } } protected override void FilterDel() { try{mvarRegDirSoftType.FilterDel();} catch (Exception e1) { throw e1; } finally { } } #endregion protected override void Sort(TSortValue pSortValue) { try{mvarRegDirSoftType.Sort(pSortValue);} catch (Exception e1) { throw e1; } finally { } } protected override void Delete() { try{mvarRegDirSoftType.Delete();} catch (Exception e1) { throw e1; } finally { } } #region(Edit) private void EditDir(TDirSoftTypeNew pDir) { try{mvarRegDirSoftType.Edit(pDir);} catch (Exception e1) { throw e1; } finally { } } protected override void Edit() { try { TFrmDirSoftType FrmDirSoftType; TDirSoftType lCurDir = (TDirSoftType)mvarRegDirSoftType.GetCurItem(); FrmDirSoftType = new TFrmDirSoftType(lCurDir); FrmDirSoftType.EventReady += new EventHandler(FrmDirBase_Ready); FrmDirSoftType.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } #endregion protected void AddDir(TDirSoftTypeNew pDir) { try{mvarRegDirSoftType.Add(pDir);} catch (Exception e1) { throw e1; } finally { } } protected override void Ready() { try { TDirSoftType lDirSoftType = (TDirSoftType)mvarRegDirSoftType.GetCurItem(); TDirEventArgs lDirEventArgs; lDirEventArgs = new TDirEventArgs(lDirSoftType, lDirSoftType.Id); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } #region(Add) protected override void Add() { try { TFrmDirSoftType FrmDirSoftType; FrmDirSoftType = new TFrmDirSoftType(); FrmDirSoftType.EventReady += new EventHandler(FrmDirBase_Ready); FrmDirSoftType.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } #endregion //// public TFrmRegDirSoftType() //// { //// InitializeComponent(); //// } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmRegDirSoftType.cs
C#
bsd
9,745
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; ////using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.Common; using Zzva.DomainObject; namespace Zzva.UIWin { public partial class TFrmDirITCompany:TFrmDirBase { private TDirITCompanyNew mvarDirITCompanyNew; private int mvarId; //ИД корректируемого объета, если постоянный то = 0 // создание нового объекта public TFrmDirITCompany():base() { InitializeComponent(); mvarDirITCompanyNew = new TDirITCompanyNew(); mvarId = 0; txtObozn.Text = mvarDirITCompanyNew.Obozn; txtNaim.Text = mvarDirITCompanyNew.Naim; mvarFlgChanch = false; } //на вход существующий объект public TFrmDirITCompany(TDirITCompany pDirITCompany):base() { InitializeComponent(); mvarDirITCompanyNew = GetCopyDir(pDirITCompany); mvarId = pDirITCompany.Id; txtObozn.Text = mvarDirITCompanyNew.Obozn; txtNaim.Text = mvarDirITCompanyNew.Naim; mvarFlgChanch = false; } private TDirITCompanyNew GetCopyDir(TDirITCompany pDirITCompany) { TDirITCompanyNew lDirITCompanyNew; string lObozn; string lNaim; lObozn = (string)pDirITCompany.GetAttrib("Obozn"); lNaim = (string)pDirITCompany.GetAttrib("Naim"); lDirITCompanyNew = new TDirITCompanyNew(lObozn, lNaim); return lDirITCompanyNew; } protected override void Ready() { try { string lObozn = txtObozn.Text; string lNaim = txtNaim.Text; mvarDirITCompanyNew.Obozn = lObozn; mvarDirITCompanyNew.Naim = lNaim; TDirEventArgs lDirEventArgs; lDirEventArgs = new TDirEventArgs(mvarDirITCompanyNew, mvarId); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmDirITCompany.cs
C#
bsd
2,460
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; ////using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.DomainObjectReg; using Zzva.Common; using Zzva.DomainObject; using System.Collections.ObjectModel; using Zzva.Report; using Zzva.ReportExcel; using System.Collections; namespace Zzva.UIWin { public partial class TFrmRegDirITCompany : TFrmRegDirBase { TRegDirITCompany mvarRegDirITCompany; protected override void FilterByValue() { try { TFrmFilterByValue FrmFilterByValue; ////FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirITCompany, GetListAliasField()); FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirITCompany, GetListAliasField(),GetCurColumnObozn()); FrmFilterByValue.EventReady += new EventHandler(FrmFilterByValue_Ready); FrmFilterByValue.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } protected override void Report() { try { TReportBase lReportBase; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаемимя класса Отчета из установок //и по технологии Позднего связывания //создаем объект Отчет //А пока так lReportBase = new TReportExcel(); ////lReportBase.Title = mvarRegDirITCompany.Title; lReportBase.Title = mvarRegDirITCompany.TitleFull; object lList = mvarRegDirITCompany.GetCurListView(); //lReportBase.CreateReport(lList); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаем парметр из установок: //Как мы хтим видеть поля отчета, представляющие объекты: //развернутыми по всем полям, или только строковое представление //А пока так по умолчанию lReportBase.CreateReport(lList, EReportFieldView.ExpandAsObject); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void ViewCurrentList() { try { object hhh = mvarRegDirITCompany.GetCurListView(); bool lFlgStateLoadForm; lFlgStateLoadForm = mvarFlgStateLoadForm; if (mvarFlgStateLoadForm == false) { mvarFlgStateLoadForm = true; } dgvMain.DataSource = null; dgvMain.Rows.Clear(); dgvMain.DataSource = hhh; DataGridViewColumn lDataGridViewColumn = dgvMain.Columns["Id"]; lDataGridViewColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; lDataGridViewColumn.Resizable = DataGridViewTriState.False; //lDataGridViewColumn.ReadOnly = true; lDataGridViewColumn.Width = 0; //lDataGridViewColumn.Visible = false; mvarFlgStateLoadForm = lFlgStateLoadForm; TDirITCompany lCurItem; lCurItem = (TDirITCompany)mvarRegDirITCompany.GetCurItem(); int lCurIndex; if (lCurItem != null) { lCurIndex = GetIndexForId(dgvMain.Rows, lCurItem.Id); if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); } //dgvMain.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //dgvMain.MultiSelect = false; //dgvMain.Rows[lCurIndex].Selected = true; //dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[1]; dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur]; } //// this.Text = mvarRegDirITCompany.TitleFull; } catch (Exception e) { throw e; } finally { } } #region(constructor) public TFrmRegDirITCompany(TRegDirITCompany pRegDirITCompany) : base() { InitializeComponent(); mvarRegDirITCompany = pRegDirITCompany; ViewCurrentList(); if (mvarRegDirITCompany.CheckEventUpdateListIsNull() == true) { mvarRegDirITCompany.EventUpdateList += new EventHandler(RegDirBase_UpdateList); } if (mvarRegDirITCompany.CheckEventFindDirIsNull() == true) { mvarRegDirITCompany.EventFindDir += new EventHandler(RegDirBase_FindDir); } } #endregion //// protected override void SetCurItem(int pId) //// { //// ////try{mvarRegDirITCompany.SetCurItem(pId);} //// try { mvarRegDirITCompany.SetCurItem(pId); } //// catch (Exception e1) { throw e1; } //// finally { } //// } protected override void SetCurItem(int pCurItem) { try { mvarRegDirITCompany.SetCurItem(pCurItem); } catch (Exception e1) { throw e1; } finally { } } //// private void FrmDirITCompany_Ready(object Sender, EventArgs ArgsBase) //// { //// try //// { //// int lId; //// TDirITCompanyNew lDir; //// TDirEventArgs lDirEventArgs; //// //// lDirEventArgs = (TDirEventArgs)ArgsBase; //// lId = lDirEventArgs.Id; //// lDir = (TDirITCompanyNew)lDirEventArgs.Dir; //// //// if (lId == 0) { AddDir(lDir); } //// else { EditDir(lDir); } //// } //// catch (Exception e) { throw e; } //// finally { } //// } protected override void FrmDirBase_Ready(object Sender, EventArgs ArgsBase) { try { int lId; TDirITCompanyNew lDir; TDirEventArgs lDirEventArgs; lDirEventArgs = (TDirEventArgs)ArgsBase; lId = lDirEventArgs.Id; lDir = (TDirITCompanyNew)lDirEventArgs.Dir; if (lId == 0) { AddDir(lDir); } else { EditDir(lDir); } } catch (Exception e) { throw e; } finally { } } //// private void RegDirBase_FindDir(object lSender, EventArgs lEventArgs) //// { //// { //// try //// { //// bool lResult; //// TDirBase lCurDir; //// int lCurIndex; //// //// TDirFindEventArgs lDirFindEventArgs = (TDirFindEventArgs)lEventArgs; //// //// lResult = lDirFindEventArgs.Result; //// lCurDir = lDirFindEventArgs.CurDir; //// //// if (lResult == false) //// { //// ////throw (new CommonException("Ничего не найдено")); //// } //// else //// { //// lCurIndex = GetIndexForId(dgvMain.Rows, lCurDir.Id); //// if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); } //// dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur]; //// } //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } //// } //// private void RegDirBase_UpdateList(object lSender, EventArgs lEventArgs) //// { //// { //// try //// { //// ViewCurrentList(); //// } //// catch (Exception e1) { throw e1; } //// finally { } //// } //// } //// //Возвратить индекс строки ДатаГрид по ИД //// private int GetIndexForId(DataGridViewRowCollection lGridViewRowCollection, int pId) //// { //// try //// { //// int lIndex; //// lIndex = -1; //// //// foreach (DataGridViewRow dr in lGridViewRowCollection) //// { //// if ((int)(dr.Cells["Id"].Value) == pId) //// { //// lIndex = dr.Index; //// break; //// } //// } //// //// return lIndex; //// } //// //// catch (Exception e1) { throw e1; } //// finally { } //// } #region Find... //Установить курсор на заданном объекте public override void FindByDir(TDirBase pDir) { try { mvarRegDirITCompany.FindByDir(pDir); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void FindPrev(TFilterValue pFindValue) { try { ////mvarRegDirITCompany.FindPrev(pFindValue); mvarRegDirITCompany.FindPrev(pFindValue); } catch (Exception e1) { throw e1; } finally { } } protected override void FindNext(TFilterValue pFindValue) { try { ////mvarRegDirITCompany.FindNext(pFindValue); mvarRegDirITCompany.FindNext(pFindValue); } catch (Exception e1) { throw e1; } finally { } } protected override void Find(TFilterValue pFindValue) { try { ////mvarRegDirITCompany.Find(pFindValue); mvarRegDirITCompany.Find(pFindValue); } catch (Exception e1) { throw e1; } finally { } } #endregion #region Filter... protected override void FilterAdd(TFilterValue pFilterValue) { try { ////mvarRegDirITCompany.FilterAdd(pFilterValue); mvarRegDirITCompany.FilterAdd(pFilterValue); } catch (Exception e1) { throw e1; } finally { } } protected override void FilterDel() { try { ////mvarRegDirITCompany.FilterDel(); mvarRegDirITCompany.FilterDel(); } catch (Exception e1) { throw e1; } finally { } } #endregion protected override void Sort(TSortValue pSortValue) { try { ////mvarRegDirITCompany.Sort(pSortValue); mvarRegDirITCompany.Sort(pSortValue); } catch (Exception e1) { throw e1; } finally { } } protected override void Delete() { try { ////mvarRegDirITCompany.Delete(); mvarRegDirITCompany.Delete(); } catch (Exception e1) { throw e1; } finally { } } #region(Edit) private void EditDir(TDirITCompanyNew pDir) { try { ////mvarRegDirITCompany.Edit(pDir); mvarRegDirITCompany.Edit(pDir); } catch (Exception e1) { throw e1; } finally { } } protected override void Edit() { try { TFrmDirITCompany FrmDirITCompany; ////TDirITCompany lCurDir = mvarRegDirITCompany.GetCurItem(); TDirITCompany lCurDir = (TDirITCompany)mvarRegDirITCompany.GetCurItem(); FrmDirITCompany = new TFrmDirITCompany(lCurDir); ////FrmDirITCompany.EventReady += new EventHandler(FrmDirITCompany_Ready); FrmDirITCompany.EventReady += new EventHandler(FrmDirBase_Ready); ////FrmDirITCompany.Show(); FrmDirITCompany.ShowDialog(); //frmSub1.Visible = true; //frmSub1.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } #endregion protected void AddDir(TDirITCompanyNew pDir) { try { ////mvarRegDirITCompany.Add(pDir); mvarRegDirITCompany.Add(pDir); } catch (Exception e1) { throw e1; } finally { } } protected override void Ready() { try { ////TDirITCompany lDirITCompany = mvarRegDirITCompany.GetCurItem(); TDirITCompany lDirITCompany = (TDirITCompany)mvarRegDirITCompany.GetCurItem(); TDirEventArgs lDirEventArgs; lDirEventArgs = new TDirEventArgs(lDirITCompany, lDirITCompany.Id); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e){MessageBox.Show(e.Message);} finally { } } #region(Add) protected override void Add() { try { TFrmDirITCompany FrmDirITCompany; FrmDirITCompany = new TFrmDirITCompany(); ////FrmDirITCompany.EventReady += new EventHandler(FrmDirITCompany_Ready); FrmDirITCompany.EventReady += new EventHandler(FrmDirBase_Ready); ////FrmDirITCompany.Show(); FrmDirITCompany.ShowDialog(); //frmSub1.Visible = true; //frmSub1.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } #endregion } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmRegDirITCompany.cs
C#
bsd
16,026
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.DomainObjectReg; using Zzva.DomainObject; using Zzva.Common; using Zzva.Report; using Zzva.ReportExcel; using System.Collections; namespace Zzva.UIWin { public partial class TFrmRegDirSoftware : TFrmRegDirBase { TRegDirSoftware mvarRegDirSoftware; protected override void FilterByValue() { try { TFrmFilterByValue FrmFilterByValue; ////FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirSoftware, GetListAliasField()); FrmFilterByValue = new TFrmFilterByValue((TRegDirBase)mvarRegDirSoftware, GetListAliasField(), GetCurColumnObozn()); FrmFilterByValue.EventReady += new EventHandler(FrmFilterByValue_Ready); FrmFilterByValue.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } protected override void Report() { try { TReportBase lReportBase; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаемимя класса Отчета из установок //и по технологии Позднего связывания //создаем объект Отчет //А пока так lReportBase = new TReportExcel(); ////lReportBase.Title = mvarRegDirSoftware.Title; lReportBase.Title = mvarRegDirSoftware.TitleFull; object lList = mvarRegDirSoftware.GetCurListView(); //lReportBase.CreateReport(lList); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь достаем парметр из установок: //Как мы хтим видеть поля отчета, представляющие объекты: //развернутыми по всем полям, или только строковое представление //А пока так по умолчанию lReportBase.CreateReport(lList, EReportFieldView.ViewAsString); //lReportBase.CreateReport(lList, EReportFieldView.ExpandAsObject); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void ViewCurrentList() { try { object hhh = mvarRegDirSoftware.GetCurListView(); bool lFlgStateLoadForm; lFlgStateLoadForm = mvarFlgStateLoadForm; if (mvarFlgStateLoadForm == false) { mvarFlgStateLoadForm = true; } dgvMain.DataSource = null; dgvMain.Rows.Clear(); dgvMain.DataSource = hhh; DataGridViewColumn lDataGridViewColumn = dgvMain.Columns["Id"]; lDataGridViewColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None; lDataGridViewColumn.Resizable = DataGridViewTriState.False; //lDataGridViewColumn.ReadOnly = true; lDataGridViewColumn.Width = 0; //lDataGridViewColumn.Visible = false; mvarFlgStateLoadForm = lFlgStateLoadForm; TDirSoftware lCurItem; lCurItem = (TDirSoftware)mvarRegDirSoftware.GetCurItem(); int lCurIndex; if (lCurItem != null) { lCurIndex = GetIndexForId(dgvMain.Rows, lCurItem.Id); if (lCurIndex == -1) { throw (new CommonException("Текущая запись не найдена")); } dgvMain.CurrentCell = dgvMain.Rows[lCurIndex].Cells[mvarFlgColumnIndexCur]; } //// this.Text = mvarRegDirSoftware.TitleFull; } catch (Exception e) { throw e; } finally { } } #region(constructor) public TFrmRegDirSoftware(TRegDirSoftware pRegDirSoftware) : base() { InitializeComponent(); mvarRegDirSoftware = pRegDirSoftware; ViewCurrentList(); if (mvarRegDirSoftware.CheckEventUpdateListIsNull() == true) { mvarRegDirSoftware.EventUpdateList += new EventHandler(RegDirBase_UpdateList); } if (mvarRegDirSoftware.CheckEventFindDirIsNull() == true) { mvarRegDirSoftware.EventFindDir += new EventHandler(RegDirBase_FindDir); } } #endregion protected override void Add() { try { TFrmDirSoftware FrmDirSoftware; ////FrmDirSoftware = new TFrmDirSoftware(); TDirSoftwareNew lDirSoftwareNew; lDirSoftwareNew = (TDirSoftwareNew)mvarRegDirSoftware.GetTemplateNewItem(); FrmDirSoftware = new TFrmDirSoftware(lDirSoftwareNew); FrmDirSoftware.EventReady += new EventHandler(FrmDirBase_Ready); ////FrmDirSoftware.Show(); FrmDirSoftware.ShowDialog() ; } catch (Exception e1) { throw e1; } finally { } } protected override void Ready() { try { ////TDirITCompany lDirITCompany = (TDirITCompany)mvarRegDirITCompany.GetCurItem(); TDirSoftware lDirSoftware = (TDirSoftware)mvarRegDirSoftware.GetCurItem(); TDirEventArgs lDirEventArgs; ////lDirEventArgs = new TDirEventArgs(lDirITCompany, lDirITCompany.Id); lDirEventArgs = new TDirEventArgs(lDirSoftware, lDirSoftware.Id); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } protected override void FindPrev(TFilterValue pFindValue) { try{mvarRegDirSoftware.FindPrev(pFindValue);} catch (Exception e1) { throw e1; } finally { } } protected override void FindNext(TFilterValue pFindValue) { try{mvarRegDirSoftware.FindNext(pFindValue);} catch (Exception e1) { throw e1; } finally { } } protected override void Find(TFilterValue pFindValue) { try{mvarRegDirSoftware.Find(pFindValue);} catch (Exception e1) { throw e1; } finally { } } protected override void FilterAdd(TFilterValue pFilterValue) { try {mvarRegDirSoftware.FilterAdd(pFilterValue);} catch (Exception e1) { throw e1; } finally { } } protected override void FilterDel() { try {mvarRegDirSoftware.FilterDel();} catch (Exception e1) { throw e1; } finally { } } protected override void Sort(TSortValue pSortValue) { try{mvarRegDirSoftware.Sort(pSortValue);} catch (Exception e1) { throw e1; } finally { } } protected override void Delete() { try{mvarRegDirSoftware.Delete();} catch (Exception e1) { throw e1; } finally { } } protected override void FrmDirBase_Ready(object Sender, EventArgs ArgsBase) { try { int lId; TDirSoftwareNew lDir; TDirEventArgs lDirEventArgs; lDirEventArgs = (TDirEventArgs)ArgsBase; lId = lDirEventArgs.Id; lDir = (TDirSoftwareNew)lDirEventArgs.Dir; if (lId == 0) { AddDir(lDir); } else { EditDir(lDir); } } catch (Exception e) { throw e; } finally { } } private void EditDir(TDirSoftwareNew pDir) { try{mvarRegDirSoftware.Edit(pDir);} catch (Exception e1) { throw e1; } finally { } } protected override void Edit() { try { TFrmDirSoftware FrmDirSoftware; TDirSoftware lCurDir = (TDirSoftware)mvarRegDirSoftware.GetCurItem(); FrmDirSoftware = new TFrmDirSoftware(lCurDir); FrmDirSoftware.EventReady += new EventHandler(FrmDirBase_Ready); ////FrmDirSoftware.Show(); FrmDirSoftware.ShowDialog(); //frmSub1.Visible = true; //frmSub1.ShowDialog(); } catch (Exception e1) { throw e1; } finally { } } protected void AddDir(TDirSoftwareNew pDir) { try{mvarRegDirSoftware.Add(pDir);} catch (Exception e1) { throw e1; } finally { } } protected override void SetCurItem(int pCurItem) { try { mvarRegDirSoftware.SetCurItem(pCurItem); } catch (Exception e1) { throw e1; } finally { } } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmRegDirSoftware.cs
C#
bsd
10,644
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; ////using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.Common; using Zzva.DomainObject; using Zzva.DomainObjectReg; namespace Zzva.UIWin { public partial class TFrmDirSoftware: TFrmDirBase { private TDirSoftwareNew mvarDirSoftwareNew; private int mvarId; //ИД корректируемого объета, если постоянный то = 0 private void FrmRegDirSoftType_Ready(object Sender, EventArgs ArgsBase) { try { TDirEventArgs lDirEventArgs = (TDirEventArgs)ArgsBase; mvarDirSoftwareNew.SoftType = (TDirSoftTypeBase)lDirEventArgs.Dir; ////txtSoftType.Text = mvarDirSoftwareNew.SoftType.Obozn; txtSoftType.Text = mvarDirSoftwareNew.SoftType.ToString(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } private void DeleteSoftType() { TDirSoftTypeNull lDirSoftTypeNull = new TDirSoftTypeNull(); mvarDirSoftwareNew.SoftType = lDirSoftTypeNull; ////txtSoftType.Text = mvarDirSoftwareNew.SoftType.Obozn; txtSoftType.Text = mvarDirSoftwareNew.SoftType.ToString(); } private void FrmRegDirITCompany_Ready(object Sender, EventArgs ArgsBase) { try { TDirEventArgs lDirEventArgs = (TDirEventArgs)ArgsBase; mvarDirSoftwareNew.Developer = (TDirITCompanyBase)lDirEventArgs.Dir; ////txtDeveloper.Text = mvarDirSoftwareNew.Developer.Obozn; txtDeveloper.Text = mvarDirSoftwareNew.Developer.ToString(); } catch (Exception e) { MessageBox.Show(e.Message); } finally { } } private void DeleteDeveloper() { TDirITCompanyNull lDirITCompanyNull = new TDirITCompanyNull(); mvarDirSoftwareNew.Developer = lDirITCompanyNull; ////txtDeveloper.Text = mvarDirSoftwareNew.Developer.Obozn; txtDeveloper.Text = mvarDirSoftwareNew.Developer.ToString(); } private void DeleteHolder() { TDirITCompanyNull lDirITCompanyNull = new TDirITCompanyNull(); mvarDirSoftwareNew.Holder = lDirITCompanyNull; ////txtHolder.Text = mvarDirSoftwareNew.Holder.Obozn; txtHolder.Text = mvarDirSoftwareNew.Holder.ToString() ; } // создание нового объекта public TFrmDirSoftware(): base() { InitializeComponent(); mvarDirSoftwareNew = new TDirSoftwareNew(); mvarId = 0; txtObozn.Text = mvarDirSoftwareNew.Obozn; txtNaim.Text = mvarDirSoftwareNew.Naim; ////txtHolder.Text = mvarDirSoftwareNew.Holder.Obozn; txtHolder.Text = mvarDirSoftwareNew.Holder.ToString(); ////txtDeveloper.Text = mvarDirSoftwareNew.Developer.Obozn; txtDeveloper.Text = mvarDirSoftwareNew.Developer.ToString(); ////txtSoftType.Text = mvarDirSoftwareNew.SoftType.Obozn; txtSoftType.Text = mvarDirSoftwareNew.SoftType.ToString(); mvarFlgChanch = false; } // создание нового объекта, на вход шаблон нового объекта public TFrmDirSoftware(TDirSoftwareNew pDirSoftwareNew): base() { InitializeComponent(); mvarDirSoftwareNew = pDirSoftwareNew; mvarId = 0; txtObozn.Text = mvarDirSoftwareNew.Obozn; txtNaim.Text = mvarDirSoftwareNew.Naim; ////txtHolder.Text = mvarDirSoftwareNew.Holder.Obozn; txtHolder.Text = mvarDirSoftwareNew.Holder.ToString(); ////txtDeveloper.Text = mvarDirSoftwareNew.Developer.Obozn; txtDeveloper.Text = mvarDirSoftwareNew.Developer.ToString(); ////txtSoftType.Text = mvarDirSoftwareNew.SoftType.Obozn; txtSoftType.Text = mvarDirSoftwareNew.SoftType.ToString(); mvarFlgChanch = false; } //на вход существующий объект public TFrmDirSoftware(TDirSoftware pDirSoftware): base() { InitializeComponent(); mvarDirSoftwareNew = GetCopyDir(pDirSoftware); mvarId = pDirSoftware.Id; txtObozn.Text = mvarDirSoftwareNew.Obozn; txtNaim.Text = mvarDirSoftwareNew.Naim; ////txtHolder.Text = mvarDirSoftwareNew.Holder.Obozn; txtHolder.Text = mvarDirSoftwareNew.Holder.ToString() ; ////txtDeveloper.Text = mvarDirSoftwareNew.Developer.Obozn; txtDeveloper.Text = mvarDirSoftwareNew.Developer.ToString() ; ////txtSoftType.Text = mvarDirSoftwareNew.SoftType.Obozn; txtSoftType.Text = mvarDirSoftwareNew.SoftType.ToString() ; mvarFlgChanch = false; } private void cmdDeleteSoftType_Click(object sender, EventArgs e) { DeleteSoftType(); } private void txtSoftType_TextChanged(object sender, EventArgs e) { mvarFlgChanch = true; } private TDirSoftwareNew GetCopyDir(TDirSoftware pDirSoftware) { TDirSoftwareNew lDirSoftwareNew; string lObozn; string lNaim; TDirITCompanyBase lHolder; TDirITCompanyBase lDeveloper; //// TDirSoftTypeBase lSoftType; lObozn = (string)pDirSoftware.GetAttrib("Obozn"); lNaim = (string)pDirSoftware.GetAttrib("Naim"); lHolder = (TDirITCompanyBase)pDirSoftware.GetAttrib("Holder"); lDeveloper = (TDirITCompanyBase)pDirSoftware.GetAttrib("Developer"); //// lSoftType = (TDirSoftTypeBase)pDirSoftware.GetAttrib("SoftType"); lDirSoftwareNew = new TDirSoftwareNew(lObozn, lNaim); lDirSoftwareNew.Holder = lHolder; lDirSoftwareNew.Developer = lDeveloper; //// lDirSoftwareNew.SoftType = lSoftType; return lDirSoftwareNew; } private void cmdOpenFrmRegDirSoftType_Click(object sender, EventArgs e) { OpenFrmRegDirSoftType(); } private void OpenFrmRegDirSoftType() { try { TFrmRegDirSoftType lFrmRegDirSoftType; TRegDirSoftType lRegDirSoftType; lRegDirSoftType = TRegDirSoftType.GetObject(); lFrmRegDirSoftType = new TFrmRegDirSoftType(lRegDirSoftType); lFrmRegDirSoftType.EventReady += new EventHandler(FrmRegDirSoftType_Ready); lFrmRegDirSoftType.FindByDir((TDirBase)mvarDirSoftwareNew.SoftType); lFrmRegDirSoftType.ShowDialog(); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } private void cmdOpenFrmRegDirITCompany2_Click(object sender, EventArgs e) { OpenFrmRegDirITCompany(); } private void OpenFrmRegDirITCompany() { try { TFrmRegDirITCompany lFrmRegDirITCompany; TRegDirITCompany lRegDirITCompany; lRegDirITCompany = TRegDirITCompany.GetObject(); lFrmRegDirITCompany = new TFrmRegDirITCompany(lRegDirITCompany); lFrmRegDirITCompany.EventReady += new EventHandler(FrmRegDirITCompany_Ready); lFrmRegDirITCompany.FindByDir((TDirBase)mvarDirSoftwareNew.Developer); ////lFrmRegDirITCompany.Show(); lFrmRegDirITCompany.ShowDialog(); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } protected override void Ready() { try { string lObozn = txtObozn.Text; string lNaim = txtNaim.Text; mvarDirSoftwareNew.Obozn = lObozn; mvarDirSoftwareNew.Naim = lNaim; TDirEventArgs lDirEventArgs; lDirEventArgs = new TDirEventArgs(mvarDirSoftwareNew, mvarId); FireEventReady(lDirEventArgs); this.Close(); } catch (Exception e){MessageBox.Show(e.Message);} finally { } } private void txtHolder_TextChanged(object sender, EventArgs e) { mvarFlgChanch = true ; } private void txtDeveloper_TextChanged(object sender, EventArgs e) { mvarFlgChanch = true; } private void cmdDeleteHolder_Click(object sender, EventArgs e) { DeleteHolder(); } private void cmdDeleteDeveloper_Click(object sender, EventArgs e) { DeleteDeveloper(); } private void cmdOpenFrmRegDirITCompany_Click(object sender, EventArgs e) { } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin/Directory/TFrmDirSoftware.cs
C#
bsd
10,199
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Zzva.UIWin.Test { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TFrmTest()); } } }
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin.Test/Program.cs
C#
bsd
510
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.UIWin.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.UIWin.Test")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cd4b4529-c0da-4c4c-8288-47829d40ea96")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/UIWin/UIWin/Zzva.UIWin.Test/Properties/AssemblyInfo.cs
C#
bsd
1,450
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.Report { public class TConfigReport { } }
zzvalib
trunk/Report/Report/Zzva.Report/TConfigReport.cs
C#
bsd
170
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.Report { // Описывает поле - значение public class TReportFieldValue: TReportFieldBase { private bool mvarTotalSum; private bool mvarRotate90; private float mvarColumnWidth; private byte mvarFontSize; private string mvarNumberFormat; private int mvarColumnExcel; private int mvarNumberInTraversal; public override TReportFieldBase GetField(string pOboznFull) { try { int lPozFirstPoint; lPozFirstPoint = pOboznFull.IndexOf('.'); if (lPozFirstPoint == -1) { if (pOboznFull == Obozn) { return this; } else { throw (new CommonException("Поле не найдено")); } } else {throw (new CommonException("Ошибка поиска поля"));} } catch (Exception e1) { throw e1; } finally { } } public override int GetColFieldValue() { return 1; } public override int GetColLevel() { return 0; } public int NumberInTraversal { get { return mvarNumberInTraversal;} set{mvarNumberInTraversal = value;} } public bool TotalSum { get { return mvarTotalSum; } set { mvarTotalSum = value; } } public bool Rotate90 { get { return mvarRotate90; } set { mvarRotate90 = value; } } public float ColumnWidth { get { return mvarColumnWidth; } set { mvarColumnWidth = value; } } public byte FontSize { get{return mvarFontSize;} set{mvarColumnExcel = value;} } public string NumberFormat { get{return mvarNumberFormat;} set { if (value == "") { mvarNumberFormat = "General"; } else{mvarNumberFormat = value;} //Здесь можно еще сделать проверку Преобрауется ли строка в десятичное число } } public int ColumnExcel { get{return mvarColumnExcel;} set{mvarColumnExcel = value;} } public TReportFieldValue(string pObozn,string pOboznFull, string pNaim, bool pTotalSum, bool pRotate90, float pColumnWidth, byte pFontSize, string pNumberFormat) : base(pObozn, pOboznFull, pNaim) { mvarNumberInTraversal = 0; mvarTotalSum = pTotalSum; mvarRotate90 = pRotate90; mvarColumnWidth = pColumnWidth; mvarFontSize = pFontSize; ////mvarNumberFormat = pNumberFormat; if (pNumberFormat == "") { mvarNumberFormat = "General"; } else { mvarNumberFormat = pNumberFormat; } } } }
zzvalib
trunk/Report/Report/Zzva.Report/TReportFieldValue.cs
C#
bsd
3,427
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.Report")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.Report")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ee25da8d-1e39-4bd2-82c2-f8e44fe33055")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/Report/Report/Zzva.Report/Properties/AssemblyInfo.cs
C#
bsd
1,442
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.Report { //описвает поле сущность public class TReportFieldEntity:TReportFieldBase { private TReportListField mvarReportListField; public override TReportFieldBase GetField(string pOboznFull) { try { int lPozFirstPoint; TReportFieldBase lReportFieldBase = null; int lPozSecondPoint; string lChildObozn; string lChildOboznFull; ////string lObozn; if (pOboznFull == "") { throw (new CommonException("Не задано обозначение поля")); } //ищем точку lPozFirstPoint = pOboznFull.IndexOf('.'); if (lPozFirstPoint == -1)//это узел { if (pOboznFull == Obozn) { lReportFieldBase = this; } else { throw (new CommonException("Поле не найдено")); } } else // ищем нижележащий узел { //отделяем оставшуюся строку и ищем в ней точку lPozSecondPoint = pOboznFull.IndexOf('.', lPozFirstPoint + 1); if (lPozSecondPoint == -1) { lChildObozn = pOboznFull.Substring(lPozFirstPoint + 1); lChildOboznFull = lChildObozn; //// lReportFieldBase = mvarReportListField.FirstOrDefault(h => h.Obozn == lChildObozn); //// //// if (lReportFieldBase != null){lReportFieldBase = lReportFieldBase.GetField(lChildOboznFull); } //// else{throw (new CommonException("Поле не найдено"));} } else { lChildObozn = pOboznFull.Substring(lPozFirstPoint + 1, lPozSecondPoint - lPozFirstPoint - 1); lChildOboznFull = pOboznFull.Substring(lPozFirstPoint + 1); //// lReportFieldBase = mvarReportListField.FirstOrDefault(h => h.Obozn == lChildObozn); //// //// if (lReportFieldBase != null) { lReportFieldBase = lReportFieldBase.GetField(lChildOboznFull); } //// else { throw (new CommonException("Поле не найдено")); } } lReportFieldBase = mvarReportListField.FirstOrDefault(h => h.Obozn == lChildObozn); if (lReportFieldBase != null) { lReportFieldBase = lReportFieldBase.GetField(lChildOboznFull); } else { throw (new CommonException("Поле не найдено")); } } return lReportFieldBase; } catch (Exception e1) { throw e1; } finally { } } public override int GetColFieldValue() { try { int lColFieldValue = 0; int lColFieldValueCur; foreach (TReportFieldBase lReportField in mvarReportListField) { lColFieldValueCur = lReportField.GetColFieldValue(); lColFieldValue = lColFieldValue + lColFieldValueCur; } return lColFieldValue; } catch (Exception e1) { throw e1; } finally { } } public override int GetColLevel() { try { int lColLevel = 0; int lColLevelCur; foreach (TReportFieldBase lReportField in mvarReportListField) { lColLevelCur = lReportField.GetColLevel(); if (lColLevelCur > lColLevel) { lColLevel = lColLevelCur; } } lColLevel = lColLevel + 1;//добавляем свой уровень return lColLevel; } catch (Exception e1) { throw e1; } finally { } } public TReportFieldEntity(string pObozn, string pOboznFull, string pNaim, TReportListField pReportListField) : base(pObozn,pOboznFull,pNaim) { mvarReportListField = pReportListField; } public TReportListField ReportListField { get{return mvarReportListField;} set{mvarReportListField = value;} } } }
zzvalib
trunk/Report/Report/Zzva.Report/TReportFieldEntity.cs
C#
bsd
4,877
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; using Zzva.Common; namespace Zzva.Report { public abstract class TReportBase { private string mvarTitle; private TConfigReport mvarConfigReport; //возвращает иеархическую структуру метаданных для заданного объекта protected TReportFieldEntity GetReportFieldEntity(object pItem, string pParentFieldObozn, EReportFieldView pReportFieldView) { try { TReportFieldEntity lReportFieldEntity; ////TReportListField lReportListField; lReportFieldEntity = new TReportFieldEntity(pParentFieldObozn, pParentFieldObozn, pParentFieldObozn, GetReportListField(pItem, pParentFieldObozn + ".", pReportFieldView)); return lReportFieldEntity; } catch (Exception e1) { throw e1; } finally { } } //возвращает иеархическую структуру метаданных для заданного объекта protected TReportListField GetReportListField(object pItem, string pParentFieldObozn, EReportFieldView pReportFieldView) { try { Type lTypeItem; PropertyInfo[] myPropertyInfo; string lFieldObozn; lFieldObozn = ""; string lFullFieldObozn; lFullFieldObozn = ""; TReportListField lReportListField; lReportListField = new TReportListField(); TReportFieldEntity lReportFieldEntity; TReportFieldValue lReportFieldValue; Type lTypeProperty; bool lPropertyIsClass; bool lPropertyIsPrimitive; bool lPropertyIsValueType; string lPropertyName; object lPropertyEntity; lTypeItem = pItem.GetType(); myPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < myPropertyInfo.Length; i++) { lFieldObozn = myPropertyInfo[i].Name; lFullFieldObozn = pParentFieldObozn + lFieldObozn; lTypeProperty = myPropertyInfo[i].PropertyType; lPropertyIsClass = lTypeProperty.IsClass; lPropertyIsPrimitive = lTypeProperty.IsPrimitive; lPropertyIsValueType = lTypeProperty.IsValueType; lPropertyName = lTypeProperty.Name; if ((lPropertyIsClass == true) & (lPropertyName != "String"))//здесь вызываем рекрусивно себя { lPropertyEntity = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, pItem, null); switch (pReportFieldView) { case EReportFieldView.ExpandAsObject : lReportFieldEntity = new TReportFieldEntity(lFieldObozn, lFullFieldObozn, lFieldObozn, GetReportListField(lPropertyEntity, lFullFieldObozn + ".")); lReportListField.Add(lReportFieldEntity); break; case EReportFieldView.ViewAsString: //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь параметры достаем из класса конфигураации, а пока так lReportFieldValue = new TReportFieldValue(lFieldObozn, lFullFieldObozn, lFieldObozn, false, false, 20, 10, ""); lReportListField.Add(lReportFieldValue); break; default: throw (new CommonException("Проверка пользовательской ошибки")); } } else if ((lPropertyIsPrimitive = true) & (lPropertyIsValueType = true) | (lPropertyName == "String")) //здесь присваиваеим значения { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь параметры достаем из класса конфигураации, а пока так lReportFieldValue = new TReportFieldValue(lFieldObozn, lFullFieldObozn, lFieldObozn, false, false, 20, 10, ""); lReportListField.Add(lReportFieldValue); } else { throw (new CommonException("Нет типа у свойства")); } } return lReportListField; } catch (Exception e1) { throw e1; } finally { } } // объект pDokument должен реализовывать один из интерфейсов //IList, IList<>, ICollection<>, //TDocument - будущий документ с шапкой и списком итемов, // и т.д. public void CreateReport(object pDocument, EReportFieldView pReportFieldView) { try { if (pDocument is IList) { CreateReport((IList)pDocument, pReportFieldView); } else if (pDocument is ICollection) { CreateReport((ICollection)pDocument, pReportFieldView); }//для примера else { throw (new CommonException("Нет совместимых интерфейсов для источника отчета ")); } } catch (Exception e1) { throw e1; } finally { } } protected virtual void CreateReport(ICollection pDocument, EReportFieldView pReportFieldView) { throw (new CommonException("Метод не реализован")); } protected virtual void CreateReport(IList pDokument, EReportFieldView pReportFieldView) { throw (new CommonException("Метод не реализован")); } //возвращает иеархическую структуру метаданных для заданного объекта protected TReportFieldEntity GetReportFieldEntity(object pItem, string pParentFieldObozn) { try { TReportFieldEntity lReportFieldEntity; ////TReportListField lReportListField; lReportFieldEntity = new TReportFieldEntity(pParentFieldObozn, pParentFieldObozn, pParentFieldObozn, GetReportListField(pItem, pParentFieldObozn + ".")); return lReportFieldEntity; } catch (Exception e1) { throw e1; } finally { } } //возвращает иеархическую структуру метаданных для заданного объекта protected TReportListField GetReportListField(object pItem, string pParentFieldObozn) { try { Type lTypeItem; PropertyInfo[] myPropertyInfo; string lFieldObozn; lFieldObozn = ""; string lFullFieldObozn; lFullFieldObozn = ""; TReportListField lReportListField; lReportListField = new TReportListField(); TReportFieldEntity lReportFieldEntity; TReportFieldValue lReportFieldValue; Type lTypeProperty; bool lPropertyIsClass; bool lPropertyIsPrimitive; bool lPropertyIsValueType; string lPropertyName; object lPropertyEntity; lTypeItem = pItem.GetType(); myPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < myPropertyInfo.Length; i++) { lFieldObozn = myPropertyInfo[i].Name; lFullFieldObozn = pParentFieldObozn + lFieldObozn; lTypeProperty = myPropertyInfo[i].PropertyType; lPropertyIsClass = lTypeProperty.IsClass; lPropertyIsPrimitive = lTypeProperty.IsPrimitive; lPropertyIsValueType = lTypeProperty.IsValueType; lPropertyName = lTypeProperty.Name; if ((lPropertyIsClass == true) & (lPropertyName != "String"))//здесь вызываем рекрусивно себя { lPropertyEntity = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, pItem, null); lReportFieldEntity = new TReportFieldEntity(lFieldObozn, lFullFieldObozn, lFieldObozn, GetReportListField(lPropertyEntity, lFullFieldObozn + ".")); lReportListField.Add(lReportFieldEntity); } else if ((lPropertyIsPrimitive = true)& (lPropertyIsValueType = true)| (lPropertyName == "String")) //здесь присваиваеим значения { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь параметры достаем из класса конфигураации, а пока так lReportFieldValue = new TReportFieldValue(lFieldObozn, lFullFieldObozn, lFieldObozn, false, false, 20, 10,""); lReportListField.Add(lReportFieldValue); } else { throw (new CommonException("Нет типа у свойства")); } } return lReportListField; } catch (Exception e1) { throw e1; } finally { } } public TConfigReport ConfigReport { get { return mvarConfigReport; } set { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь сохранить в конфигурационном файле //и в памяти mvarConfigReport = value; } } protected TReportBase() { //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //Здесь сосчитать данные Конфигурации отчета //из конфигурационного файла в память mvarConfigReport mvarTitle = ""; } public string Title { get { return mvarTitle; } set { mvarTitle = value; } } // объект pDokument должен реализовывать один из интерфейсов //IList, IList<>, ICollection<>, //TDocument - будущий документ с шапкой и списком итемов, // и т.д. public void CreateReport(object pDocument) { try { if (pDocument is IList){CreateReport((IList)pDocument);} else if (pDocument is ICollection){CreateReport((ICollection)pDocument);}//для примера else{throw (new CommonException("Нет совместимых интерфейсов для источника отчета "));} } catch (Exception e1) { throw e1; } finally { } } protected virtual void CreateReport(IList pDokument) { throw (new CommonException("Метод не реализован")); } protected virtual void CreateReport(ICollection pDocument) { throw (new CommonException("Метод не реализован")); } } }
zzvalib
trunk/Report/Report/Zzva.Report/TReportBase.cs
C#
bsd
13,095
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; using System.Collections; namespace Zzva.Report { public class TReportListField:Collection<TReportFieldBase> { } }
zzvalib
trunk/Report/Report/Zzva.Report/TReportListField.cs
C#
bsd
282
using System; namespace Zzva.Report { // Как представляь в отчете поля, содержащие объекты public enum EReportFieldView { // текстовое представленеи (Object.ToString()) ViewAsString = 0, //разворачивать поля представляющие объеты ExpandAsObject = 1, } }
zzvalib
trunk/Report/Report/Zzva.Report/EReportView.cs
C#
bsd
436
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.Report { public abstract class TReportFieldBase : IComparable { private string mvarObozn; private string mvarNaim; private string mvarOboznFull; // возвращает Поле внутри дерева по полному Обозначению Report.Developer.Naim public virtual TReportFieldBase GetField(string pOboznFull) { throw (new CommonException("Метод не реализован")); } //Возвращает количество полей - значений public virtual int GetColFieldValue() { throw (new CommonException("Метод не реализован")); } //Возвращает количество уровней поля public virtual int GetColLevel() { throw (new CommonException("Метод не реализован")); } protected TReportFieldBase(string pObozn, string pOboznFull, string pNaim) { mvarObozn = pObozn; mvarOboznFull = pOboznFull; mvarNaim = pNaim; } public string OboznFull { get { return mvarOboznFull; } set { if (mvarOboznFull != value) { throw (new CommonException("Обозначение в постояяном объекте нельзя изменять")); } } } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; TReportFieldBase lReportFieldBase = (TReportFieldBase)obj; return (this.Obozn == lReportFieldBase.Obozn); } public override int GetHashCode() {return this.Obozn.GetHashCode();} public int CompareTo(object obj) { try { TReportFieldBase lOtherReportFieldBase = obj as TReportFieldBase; if (lOtherReportFieldBase != null) { return this.Obozn.CompareTo(lOtherReportFieldBase.Obozn); } else { throw (new CommonException("Object is not a TDirBase")); } } catch (Exception e1) { throw e1; } finally { } } public string Obozn { get { return mvarObozn; } set { if (mvarObozn != value) { throw (new CommonException("Обозначение в постояяном объекте нельзя изменять")); } } } public string Naim { get { return mvarNaim; } set { mvarNaim = value; } } } }
zzvalib
trunk/Report/Report/Zzva.Report/TReportFieldBase.cs
C#
bsd
2,880
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Report; namespace Zzva.ReportExcel { //Позднее связывание через COM public class TReportExcelRuntime:TReportBase { } }
zzvalib
trunk/Report.Excel/Report.Excel/Zzva.Report.Excel/TReportExcelRuntime.cs
C#
bsd
274
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Excel; using Zzva.Report; using System.Reflection; using Zzva.Common; namespace Zzva.ReportExcel { public class TReportExcel:TReportBase { private void ScanListReportMen(System.Collections.IList pDokument, TOneTableExcel pOneTableExcel, EReportFieldView pReportFieldView) { try { Type lTypeItem; PropertyInfo[] lPropertyInfo; string lFieldObozn; string lFieldOboznFull; Type lTypeProperty; bool lPropertyIsClass; bool lPropertyIsPrimitive; bool lPropertyIsValueType; string lPropertyObozn; object lFieldValue; foreach (object lItem in pDokument) { lTypeItem = lItem.GetType(); lPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < lPropertyInfo.Length; i++) { lFieldObozn = lPropertyInfo[i].Name; lFieldOboznFull = "Report." + lFieldObozn; lTypeProperty = lPropertyInfo[i].PropertyType; lPropertyIsClass = lTypeProperty.IsClass; lPropertyIsPrimitive = lTypeProperty.IsPrimitive; lPropertyIsValueType = lTypeProperty.IsValueType; lPropertyObozn = lTypeProperty.Name; if ((lPropertyIsClass == true) & (lPropertyObozn != "String"))//здесь вызываем рекрусивно себя { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, lItem, null); switch (pReportFieldView) { case EReportFieldView.ExpandAsObject : ScanReportFieldEntity(lFieldValue, pOneTableExcel, lFieldOboznFull); break; case EReportFieldView.ViewAsString : pOneTableExcel.SetValue(lFieldOboznFull, lFieldValue.ToString()); break; default: ////break; throw (new CommonException("Нет константы для EReportFieldView")); } } else if ((lPropertyIsPrimitive = true) & (lPropertyIsValueType = true) | (lPropertyObozn == "String")) //здесь присваиваеим значения { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, lItem, null); pOneTableExcel.SetValue(lFieldOboznFull, lFieldValue); } else { throw (new CommonException("Нет типа у свойства")); } } pOneTableExcel.NewLine(); } } catch (Exception e1) { throw e1; } finally { } } protected override void CreateReport(System.Collections.IList pDokument, EReportFieldView pReportFieldView) { try { if (pDokument.Count == 0) { throw (new CommonException("Документ пустой")); } Excel.ApplicationClass lExcel; lExcel = GetExcel(); Excel.Workbook lWkb; lWkb = lExcel.Workbooks.Add(1); Type lTypeItem; object lItem; PropertyInfo[] myPropertyInfo; string lFildObozn; lFildObozn = ""; lItem = pDokument[0]; lTypeItem = lItem.GetType(); myPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < myPropertyInfo.Length; i++) { lFildObozn = myPropertyInfo[i].Name; } TReportListField lReportListField = GetReportListField(lItem, "", pReportFieldView); TReportFieldEntity lReportFieldEntity = GetReportFieldEntity(lItem, "Report", pReportFieldView); int lColLevel = lReportFieldEntity.GetColLevel(); int lColFieldValue = lReportFieldEntity.GetColFieldValue(); TReportFieldBase lReportFieldBase = lReportFieldEntity.GetField("Report"); lExcel.Visible = true; Excel.Worksheet lSht; lSht = (Excel.Worksheet)lWkb.Worksheets[1]; TOneTableExcel lOneTableExcel = new TOneTableExcel(lSht, lReportFieldEntity); lOneTableExcel.Title = Title; ////ScanListReportMen(pDokument, lOneTableExcel); ScanListReportMen(pDokument, lOneTableExcel,pReportFieldView); } catch (Exception e1) { throw e1; } finally { } } private void ScanReportFieldEntity(object pFieldEntity, TOneTableExcel pOneTableExcel, string pFieldOboznFullParent) { try { Type lTypeItem; PropertyInfo[] lPropertyInfo; string lFieldObozn; string lFieldOboznFull; Type lTypeProperty; bool lPropertyIsClass; bool lPropertyIsPrimitive; bool lPropertyIsValueType; string lPropertyObozn; object lFieldValue; lTypeItem = pFieldEntity.GetType(); lPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < lPropertyInfo.Length; i++) { lFieldObozn = lPropertyInfo[i].Name; lFieldOboznFull = pFieldOboznFullParent + "." + lFieldObozn; lTypeProperty = lPropertyInfo[i].PropertyType; lPropertyIsClass = lTypeProperty.IsClass; lPropertyIsPrimitive = lTypeProperty.IsPrimitive; lPropertyIsValueType = lTypeProperty.IsValueType; lPropertyObozn = lTypeProperty.Name; if ((lPropertyIsClass == true) & (lPropertyObozn != "String"))//здесь вызываем рекрусивно себя { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, pFieldEntity, null); ScanReportFieldEntity(lFieldValue, pOneTableExcel, lFieldOboznFull); } else if ((lPropertyIsPrimitive = true) & (lPropertyIsValueType = true) | (lPropertyObozn == "String")) //здесь присваиваеим значения { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, pFieldEntity, null); pOneTableExcel.SetValue(lFieldOboznFull, lFieldValue); } else { throw (new CommonException("Нет типа у свойства")); } } } catch (Exception e1) { throw e1; } finally { } } private void ScanListReportMen(System.Collections.IList pDokument, TOneTableExcel pOneTableExcel) { try { Type lTypeItem; PropertyInfo[] lPropertyInfo; string lFieldObozn; string lFieldOboznFull; Type lTypeProperty; bool lPropertyIsClass; bool lPropertyIsPrimitive; bool lPropertyIsValueType; string lPropertyObozn; object lFieldValue; foreach (object lItem in pDokument) { lTypeItem = lItem.GetType(); lPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < lPropertyInfo.Length; i++) { lFieldObozn = lPropertyInfo[i].Name; lFieldOboznFull = "Report." + lFieldObozn; lTypeProperty = lPropertyInfo[i].PropertyType; lPropertyIsClass = lTypeProperty.IsClass; lPropertyIsPrimitive = lTypeProperty.IsPrimitive; lPropertyIsValueType = lTypeProperty.IsValueType; lPropertyObozn = lTypeProperty.Name; if ((lPropertyIsClass == true) & (lPropertyObozn != "String"))//здесь вызываем рекрусивно себя { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, lItem, null); ScanReportFieldEntity(lFieldValue, pOneTableExcel, lFieldOboznFull); } else if ((lPropertyIsPrimitive = true) & (lPropertyIsValueType = true) | (lPropertyObozn == "String")) //здесь присваиваеим значения { lFieldValue = lTypeItem.InvokeMember(lFieldObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, lItem, null); pOneTableExcel.SetValue(lFieldOboznFull, lFieldValue); } else { throw (new CommonException("Нет типа у свойства")); } } pOneTableExcel.NewLine(); } } catch (Exception e1) { throw e1; } finally { } } protected override void CreateReport(System.Collections.IList pDokument) { try { if (pDokument.Count == 0) { throw (new CommonException("Документ пустой")); } Excel.ApplicationClass lExcel; lExcel = GetExcel(); Excel.Workbook lWkb; lWkb = lExcel.Workbooks.Add(1); Type lTypeItem; object lItem; PropertyInfo[] myPropertyInfo; string lFildObozn; lFildObozn = ""; lItem = pDokument[0]; lTypeItem = lItem.GetType(); myPropertyInfo = lTypeItem.GetProperties(); for (int i = 0; i < myPropertyInfo.Length; i++) { lFildObozn = myPropertyInfo[i].Name; } TReportListField lReportListField = GetReportListField(lItem,""); TReportFieldEntity lReportFieldEntity = GetReportFieldEntity(lItem, "Report"); int lColLevel = lReportFieldEntity.GetColLevel(); int lColFieldValue = lReportFieldEntity.GetColFieldValue(); TReportFieldBase lReportFieldBase = lReportFieldEntity.GetField("Report"); lExcel.Visible = true; Excel.Worksheet lSht; lSht = (Excel.Worksheet)lWkb.Worksheets[1]; TOneTableExcel lOneTableExcel = new TOneTableExcel(lSht, lReportFieldEntity); ////lOneTableExcel.DrawTitleTable(lSht, lReportFieldEntity, 2, 3); ////lOneTableExcel.DrawFrame(lSht, lReportFieldEntity); lOneTableExcel.Title = Title; ScanListReportMen(pDokument, lOneTableExcel); } catch (Exception e1) { throw e1; } finally { } } public Excel.ApplicationClass GetExcel() { try { Excel.ApplicationClass lExcel; lExcel = new ApplicationClass(); return lExcel; } catch (Exception e1) { throw e1; } finally { } } public TReportExcel() : base() { } } }
zzvalib
trunk/Report.Excel/Report.Excel/Zzva.Report.Excel/TReportExcel.cs
C#
bsd
14,139
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Excel; using Zzva.Report; using System.Reflection; using Zzva.Common; namespace Zzva.ReportExcel { public class TOneTableExcel { private int mvarColumnBegin; //начало точки сканипрвания первого этапа таблицы private int mvarRowBegin; private int mvarColumnBeginCur;//начало точки сканирования очередного этапа таблицы private int mvarRowBeginCur; private TReportFieldEntity mvarReportFieldEntity; private Excel.Worksheet mvarSheet; private int mvarTitleColumn; private int mvarTitleRow; public TOneTableExcel(Excel.Worksheet pSheet, TReportFieldEntity pReportFieldEntity) { try { mvarTitleColumn = 1; mvarTitleRow = 2; mvarColumnBegin = 1; mvarRowBegin = 3; mvarColumnBeginCur = mvarColumnBegin; mvarRowBeginCur = mvarRowBegin; mvarReportFieldEntity = pReportFieldEntity; mvarSheet = pSheet; DrawFrame(mvarSheet, mvarReportFieldEntity); } catch (Exception e1) { throw e1; } finally { } } public string Title { set { string lTitle = value; Range lRange; lRange = (Range)mvarSheet.Cells[mvarTitleRow, mvarTitleColumn]; lRange.Formula = lTitle; } } private void DrawFrame(Excel.Worksheet pSht, TReportFieldEntity pReportFieldEntity) { try { int lColumnBegin = mvarColumnBegin; int lRowBegin = mvarRowBegin; TCell lCellEnd; int lColumnEnd; int lRowEnd; int lColumnCur; int lRowCur; //lCellEnd = DrawTitleTable(pSht, pReportFieldEntity, lColumnBegin, lRowBegin); lCellEnd = DrawTitleTableMen(pSht, pReportFieldEntity, lColumnBegin, lRowBegin); //пробежимся проставим номера столбцов int lNumCur = 0; Range lRngCur; lRowCur = lCellEnd.Row + 1; lRowEnd = lRowCur; lColumnCur = lColumnBegin; lColumnEnd = lCellEnd.Column; for (int i = lColumnCur; i <= lColumnEnd; i++) { lNumCur = lNumCur + 1; lRngCur = (Range)pSht.Cells[lRowCur, i]; lRngCur.Formula = lNumCur; lRngCur.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; lRngCur.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; } //сетку и фон шапки заголовков ////lRngCur = pSht.get_Range(pSht.Cells[lRowBegin, lColumnBegin], //// pSht.Cells[lRowEnd, lColumnEnd]); lRngCur = pSht.get_Range(pSht.Cells[lRowBegin + 1, lColumnBegin], pSht.Cells[lRowEnd, lColumnEnd]); //не рисуем на корневом "Report" lRngCur.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous; lRngCur.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous; lRngCur.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous; lRngCur.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous; lRngCur.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous; lRngCur.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous; lRngCur.Interior.ColorIndex = 15; mvarColumnBeginCur = mvarColumnBegin; mvarRowBeginCur = lRowEnd + 1; } catch (Exception e1) { throw e1; } finally { } } //Возвращает последнюю ячейку после прорисовки private TCell DrawTitleTableMen(Excel.Worksheet pSht, TReportFieldEntity pReportFieldEntity, int pColumnBegin, int pRowBegin) { try { int lColFieldValue; int lColLevel; Range lRng; TReportListField lReportListField; TReportFieldValue lReportFieldValue; TReportFieldEntity lReportFieldEntity; int lColumnCur; int lRowCur; int lDeltaRow; int lDeltaColumn; int lColumnEnd; int lRowEnd; TCell lCellEnd; TCell lCellEndChild; lColumnCur = pColumnBegin; lRowCur = pRowBegin; lColLevel = pReportFieldEntity.GetColLevel(); lDeltaRow = lColLevel - 1; lRowEnd = pRowBegin + lDeltaRow + 1; lColFieldValue = pReportFieldEntity.GetColFieldValue(); lDeltaColumn = lColFieldValue - 1; lColumnEnd = pColumnBegin + lDeltaColumn; lCellEnd = new TCell() { Row = lRowEnd, Column = lColumnEnd }; lRng = pSht.get_Range(pSht.Cells[lRowCur, lColumnCur], pSht.Cells[lRowCur, lColumnCur + lDeltaColumn]); //Не показываем название виртуального корневого объекта "Report" ////lRng.MergeCells = true; ////lRng.Formula = pReportFieldEntity.Naim; ////lRng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; ////lRng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; lRowCur = lRowCur + 1; lReportListField = pReportFieldEntity.ReportListField; foreach (TReportFieldBase lReportField in lReportListField) { if (lReportField is TReportFieldValue) { lReportFieldValue = (TReportFieldValue)lReportField; lRng = pSht.get_Range(pSht.Cells[lRowCur, lColumnCur], pSht.Cells[lRowCur + lDeltaRow, lColumnCur]); lRng.MergeCells = true; lRng.Formula = lReportFieldValue.Naim; lRng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; lRng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; lRng.ColumnWidth = lReportFieldValue.ColumnWidth; lReportFieldValue.NumberInTraversal = lColumnCur; lColumnCur = lColumnCur + 1; } else if (lReportField is TReportFieldEntity) { lReportFieldEntity = (TReportFieldEntity)lReportField; lCellEndChild = DrawTitleTable(pSht, lReportFieldEntity, lColumnCur, lRowCur, lColumnEnd, lRowEnd); //lColumnCur = lColumnCur + lReportFieldEntity.GetColFieldValue(); lColumnCur = lCellEndChild.Column + 1; } else { throw (new CommonException("Нет такого класса")); } } return lCellEnd; } catch (Exception e1) { throw e1; } finally { } } public void SetValue(string pOboznFull, object pValueField) { try { TReportFieldValue lReportFieldValue; TReportFieldBase lReportFieldBase; lReportFieldBase = mvarReportFieldEntity.GetField(pOboznFull); if (lReportFieldBase is TReportFieldValue){lReportFieldValue = (TReportFieldValue)lReportFieldBase;} else{throw (new CommonException("Это не объект TReportFieldValue")); } Range lRange; ////lRange = mvarSheet.get_Range(mvarSheet.Cells[lRowBegin, lColumnBegin], //// mvarSheet.Cells[lRowEnd, lColumnEnd]); lRange = (Range)mvarSheet.Cells[mvarRowBeginCur, lReportFieldValue.NumberInTraversal]; ////lRange.NumberFormat = lReportFieldValue.NumberFormat; lRange.Font.Size = lReportFieldValue.FontSize; lRange.Formula = pValueField; } catch (Exception e1) { throw e1; } finally { } } public void NewLine() { try { mvarRowBeginCur = mvarRowBeginCur + 1; } catch (Exception e1) { throw e1; } finally { } } private class TCell { public int Row { get; set;} public int Column { get; set; } } //Возвращает последнюю ячейку после прорисовки private TCell DrawTitleTable(Excel.Worksheet pSht, TReportFieldEntity pReportFieldEntity, int pColumnBegin, int pRowBegin, int pColumnMax,int pRowMax) { try { int lColFieldValue; int lColLevel; Range lRng; TReportListField lReportListField; TReportFieldValue lReportFieldValue; TReportFieldEntity lReportFieldEntity; int lColumnCur; int lRowCur; int lDeltaRow; int lDeltaColumn; int lColumnEnd; int lRowEnd; TCell lCellEnd; TCell lCellEndChild; lColumnCur = pColumnBegin; lRowCur = pRowBegin; lColLevel = pReportFieldEntity.GetColLevel(); lDeltaRow = lColLevel - 1; lRowEnd = pRowBegin + lDeltaRow +1; lColFieldValue = pReportFieldEntity.GetColFieldValue(); lDeltaColumn = lColFieldValue - 1; lColumnEnd = pColumnBegin + lDeltaColumn; lCellEnd = new TCell() { Row = lRowEnd, Column = lColumnEnd }; //// lRng = pSht.get_Range(pSht.Cells[pRowCur, pColumnCur], //// pSht.Cells[pRowCur, pColumnCur + lColFieldValue -1]); lRng = pSht.get_Range(pSht.Cells[lRowCur, lColumnCur], pSht.Cells[lRowCur, lColumnCur + lDeltaColumn]); lRng.MergeCells = true; lRng.Formula = pReportFieldEntity.Naim; lRng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; lRng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; lRowCur = lRowCur + 1; lReportListField = pReportFieldEntity.ReportListField; foreach (TReportFieldBase lReportField in lReportListField) { if (lReportField is TReportFieldValue) { lReportFieldValue = (TReportFieldValue)lReportField; //// lRng = pSht.get_Range(pSht.Cells[lRowCur, lColumnCur], //// pSht.Cells[lRowCur + lDeltaRow, lColumnCur]); lRng = pSht.get_Range(pSht.Cells[lRowCur, lColumnCur], pSht.Cells[pRowMax, lColumnCur]); lRng.MergeCells = true; lRng.Formula = lReportFieldValue.Naim; lRng.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; lRng.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; lReportFieldValue.NumberInTraversal = lColumnCur; lColumnCur = lColumnCur + 1; } else if (lReportField is TReportFieldEntity) { lReportFieldEntity = (TReportFieldEntity)lReportField; ////DrawTitleTable(pSht, lReportFieldEntity, lColumnCur, lRowCur); lCellEndChild = DrawTitleTable(pSht, lReportFieldEntity, lColumnCur, lRowCur,pColumnMax,pRowMax); ////lColumnCur = lColumnCur + lReportFieldEntity.GetColFieldValue(); lColumnCur = lCellEndChild.Column + 1; } else{throw (new CommonException("Нет такого класса"));} } return lCellEnd; } catch (Exception e1) { throw e1; } finally { } } } }
zzvalib
trunk/Report.Excel/Report.Excel/Zzva.Report.Excel/TOneTableExcel.cs
C#
bsd
14,007
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.Report.Excel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.Report.Excel")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d36cfdfb-6f24-43db-bbdd-37ebbc662843")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/Report.Excel/Report.Excel/Zzva.Report.Excel/Properties/AssemblyInfo.cs
C#
bsd
1,454
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Zzva.UIWin; using Zzva.DomainObjectReg; namespace Zzva.AppWin.SoftLicense { public partial class TFrmMain : Form { private void cmdDirectorySoftType_Click(object sender, EventArgs e) { DirectorySoftType(); } private void DirectorySoftType() { try { TFrmRegDirSoftType lFrmRegDirSoftType; TRegDirSoftType lRegDirSoftType; lRegDirSoftType = TRegDirSoftType.GetObject(); lFrmRegDirSoftType = new TFrmRegDirSoftType(lRegDirSoftType); //lFrmRegDirSoftType.EventReady += new EventHandler(FrmRegDirSoftType_Ready); lFrmRegDirSoftType.ShowDialog(); lFrmRegDirSoftType.MdiParent = this; } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } public TFrmMain() { InitializeComponent(); } private void cmdDirectoryITCompany_Click(object sender, EventArgs e) { DirectoryITCompany(); } private void DirectoryITCompany() { try { TFrmRegDirITCompany lFrmRegDirITCompany; TRegDirITCompany lRegDirITCompany; lRegDirITCompany = TRegDirITCompany.GetObject(); lFrmRegDirITCompany = new TFrmRegDirITCompany(lRegDirITCompany); ////lFrmRegDirITCompany.EventReady += new EventHandler(FrmRegDirITCompany_Ready); lFrmRegDirITCompany.ShowDialog(); lFrmRegDirITCompany.MdiParent = this; ////lFrmRegDirITCompany.Show(); } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } private void cmdDirectorySoft_Click(object sender, EventArgs e) { DirectorySoft(); } private void DirectorySoft() { try { TFrmRegDirSoftware lFrmRegDirSoftware; TRegDirSoftware lRegDirSoftware; lRegDirSoftware = TRegDirSoftware.GetObject(); lFrmRegDirSoftware = new TFrmRegDirSoftware(lRegDirSoftware); ////lFrmRegDirSoftware.EventReady += new EventHandler(FrmRegDirSoftware_Ready); lFrmRegDirSoftware.ShowDialog(); lFrmRegDirSoftware.MdiParent = this; } catch (Exception e1) { MessageBox.Show(e1.Message); } finally { } } private void cmdHelp_Click(object sender, EventArgs e) { Help(); } private void Help() { try { String dir; dir = Environment.CurrentDirectory;//получаем текущую рабочую папку приложения dir = Application.StartupPath;//получаем папку из которой произошел запуск приложения /////dir = Directory.GetCurrentDirectory(); dir = AppDomain.CurrentDomain.BaseDirectory; ////System.Diagnostics.Process.Start(@"E:\Project\Exemple\TestWordDoc.doc"); System.Diagnostics.Process.Start(dir + @"\ВЛИЕ_238_7_078_ИП.doc"); } catch (Exception e){MessageBox.Show(e.Message);} finally { } } } }
zzvalib
trunk/AppWin.SoftLicense/AppWin.SoftLicense/Zzva.AppWin.SoftLicense/TFrmMain.cs
C#
bsd
3,941
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Zzva.AppWin.SoftLicense { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TFrmMain()); } } }
zzvalib
trunk/AppWin.SoftLicense/AppWin.SoftLicense/Zzva.AppWin.SoftLicense/Program.cs
C#
bsd
518
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.AppWin.SoftLicense")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.AppWin.SoftLicense")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f4dc41d0-215b-4497-91c4-b6c798e8161f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/AppWin.SoftLicense/AppWin.SoftLicense/Zzva.AppWin.SoftLicense/Properties/AssemblyInfo.cs
C#
bsd
1,466
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public abstract class TEsbDomainObject { //protected TEsbDomainObject() { } public virtual TDirSoftType GetSoftType(int pId) { try { throw (new CommonException("Метод не реализован")); } catch (Exception e) { throw e; } finally { } } public virtual TDirITCompany GetITCompany(int pId) { try { throw (new CommonException("Метод не реализован")); } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/TEsbDomainObject.cs
C#
bsd
798
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.DomainObject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.DomainObject")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0005b262-c483-40ba-9c7b-3d78f6b0f191")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Properties/AssemblyInfo.cs
C#
bsd
1,454
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; using System.Reflection; namespace Zzva.DomainObject { public abstract class TDirBase:IComparable { protected string mvarObozn; protected string mvarNaim; private Type mvarTypeObject ; public override string ToString() { try{return this.Obozn;} catch (Exception e1) { throw e1; } finally { } } //public static TDirBase operator =(Complex c1, Complex c2) //// public static bool operator ==(TDirBase pDirBase1,TDirBase pDirBase2) //// { //// bool lResult; //// lResult = pDirBase1.Equals(pDirBase2); //// if (lResult == true) { return true; } //// else { return false; } //// } //// public static bool operator !=(TDirBase pDirBase1, TDirBase pDirBase2) //// { //// bool lResult; //// lResult = pDirBase1.Equals(pDirBase2); //// if (lResult == true) { return false ; } //// else { return true ; } //// } public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; TDirBase lDirBase = (TDirBase)obj; return (this.Obozn == lDirBase.Obozn); } public override int GetHashCode() { return this.Obozn.GetHashCode(); } public int CompareTo(object obj) { try { TDirBase lOtherTDirBase = obj as TDirBase; if (lOtherTDirBase != null) { return this.Obozn.CompareTo(lOtherTDirBase.Obozn); } else{throw (new CommonException("Object is not a TDirBase"));} } catch (Exception e1) { throw e1; } finally { } } protected TDirBase() { mvarTypeObject = this.GetType(); } public virtual int Id { get { try { throw (new CommonException("Свойство не реализовано")); } catch (Exception e1) { throw e1; } finally { } } } public abstract string Obozn { get; set; } public abstract string Naim { get; set; } public object GetAttrib(string pObozn) { try { object lAttrib; object[] lParametrs = new object[1]; lParametrs = null; lAttrib = mvarTypeObject.InvokeMember(pObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty, null, this, lParametrs); return lAttrib; } catch (Exception e) { throw e; } finally { } } public void SetAttrib(string pObozn, object pValue) { try { object lAttrib; object[] lParametrs = new object[1]; lParametrs[0] = pValue; lAttrib = mvarTypeObject.InvokeMember(pObozn, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, this, lParametrs); } catch (Exception e) { throw e; } finally { } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/TDirBase.cs
C#
bsd
4,170
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirSoftwareNew:TDirSoftwareBase { public TDirSoftwareNew() : base() { mvarObozn = ""; mvarNaim = ""; mvarDeveloper = new TDirITCompanyNull(); mvarHolder = new TDirITCompanyNull(); //// mvarSoftType = new TDirSoftTypeNull(); } public TDirSoftwareNew(string pObozn, string pNaim) : base() { Obozn = pObozn; Naim = pNaim; mvarDeveloper = new TDirITCompanyNull(); mvarHolder = new TDirITCompanyNull(); //// mvarSoftType = new TDirSoftTypeNull(); } public override TDirSoftTypeBase SoftType { get { return mvarSoftType; } set { try { Type lTypeObject; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirSoftTypeNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirSoftType": case "TDirSoftTypeNull": mvarSoftType = value; break; default: throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } public override string Obozn { get { return mvarObozn; } set { try { string lObozn; lObozn = value.TrimEnd(); if (lObozn == "") { throw (new CommonException("Обозначение не должно быть пустым")); } mvarObozn = lObozn; } catch (Exception e) { throw e; } finally { } } } public override string Naim { get{return mvarNaim;} set{mvarNaim = value;} } public override TDirITCompanyBase Developer { get { return mvarDeveloper ; } set { try { Type lTypeObject ; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirITCompanyNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirITCompany": case "TDirITCompanyNull": mvarDeveloper = value; break; default:throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } public override TDirITCompanyBase Holder { get { return mvarHolder ; } set { try { Type lTypeObject; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirITCompanyNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirITCompany": case "TDirITCompanyNull": mvarHolder = value; break; default:throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/Software/TDirSoftwareNew.cs
C#
bsd
4,551
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObject { public abstract class TDirSoftwareBase:TDirBase { protected TDirITCompanyBase mvarHolder; //компания правообладатель ПО protected TDirITCompanyBase mvarDeveloper; // компания разработчик ПО protected TDirSoftTypeBase mvarSoftType; // Категория ПО public abstract TDirSoftTypeBase SoftType { get; set; } public override string ToString() { try { return this.Naim; } catch (Exception e1) { throw e1; } finally { } } protected TDirSoftwareBase() : base() { } public abstract TDirITCompanyBase Developer {get;set;} public abstract TDirITCompanyBase Holder { get; set; } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/Software/TDirSoftwareBase.cs
C#
bsd
1,098
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirSoftwareNull:TDirSoftwareBase { public TDirSoftwareNull(): base() { ////mvarObozn = "НеопределеннаяSoftware"; ////mvarNaim = "Software Planet Venera"; mvarObozn = "Нет"; mvarNaim = "Отсутсвует"; mvarHolder = new TDirITCompanyNull(); mvarDeveloper = new TDirITCompanyNull(); //// mvarSoftType = new TDirSoftTypeNull(); } public override TDirSoftTypeBase SoftType { get { return mvarSoftType; } set { throw (new CommonException("Нельзя изменять")); } } public override string Obozn { get {return mvarObozn;} set { throw (new CommonException("Обозначение нельзя изменять")); } } public override string Naim { get{return mvarNaim;} set { throw (new CommonException("Наименование нельзя изменять")); } } public override TDirITCompanyBase Developer { get{return mvarDeveloper;} set { throw (new CommonException("Разработчика нельзя изменять")); } } public override TDirITCompanyBase Holder { get { return mvarHolder; } set { throw (new CommonException("Правообладателя нельзя изменять")); } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/Software/TDirSoftwareNull.cs
C#
bsd
1,755
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirSoftware: TDirSoftwareBase { private TEsbDomainObject mvarEsbDomainObject; private int mvarId; private int mvarHolderId; private int mvarDeveloperId; //// private int mvarSoftTypeId; public override TDirSoftTypeBase SoftType { get { try { if (mvarSoftType == null) { if (mvarSoftTypeId == 0) { mvarSoftType = new TDirSoftTypeNull(); } else { mvarSoftType = Esb.GetSoftType(mvarSoftTypeId); } } return mvarSoftType; } catch (Exception e) { throw e; } finally { } } set { try { Type lTypeObject; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirSoftTypeNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirSoftType": case "TDirSoftTypeNull": mvarSoftType = value; break; default: throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } //// public TDirSoftware(TEsbDomainObject EsbDomainObject, int pId, string pObozn, string pNaim, int pHolderId, int pDeveloperId, int pSoftTypeId) : base() { mvarEsbDomainObject = EsbDomainObject; mvarId = pId; mvarObozn = pObozn; mvarNaim = pNaim; mvarHolderId = pHolderId; mvarDeveloperId = pDeveloperId; mvarSoftTypeId = pSoftTypeId; } public override string Obozn { get { return mvarObozn; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоночального заполнения справочника ////set { if (mvarObozn != value) { throw (new CommonException("Обозначение нельзя изменять")); } } set { mvarObozn = value; } } public TDirSoftware(TEsbDomainObject EsbDomainObject, int pId, string pObozn, string pNaim, int pHolderId, int pDeveloperId) : base() { mvarEsbDomainObject = EsbDomainObject; mvarId = pId; mvarObozn = pObozn; mvarNaim = pNaim; mvarHolderId = pHolderId; mvarDeveloperId = pDeveloperId; } public override int Id { get { return mvarId; } } private TEsbDomainObject Esb { get { try { return mvarEsbDomainObject; } catch (Exception e) { throw e; } finally { } } } public override string Naim { get{return mvarNaim;} set{mvarNaim = value;} } public override TDirITCompanyBase Developer { get { try { if (mvarDeveloper == null) { if (mvarDeveloperId == 0) { mvarDeveloper = new TDirITCompanyNull(); } else { mvarDeveloper = Esb.GetITCompany(mvarDeveloperId );} } return mvarDeveloper; } catch (Exception e) { throw e; } finally { } } set { try { Type lTypeObject; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirITCompanyNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirITCompany": case "TDirITCompanyNull": mvarDeveloper = value; break; default: throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } public override TDirITCompanyBase Holder { get { try { if (mvarHolder == null) { if (mvarHolderId == 0) { mvarHolder = new TDirITCompanyNull() ; } else { mvarHolder = Esb.GetITCompany(mvarHolderId); } } return mvarHolder; } catch (Exception e) { throw e; } finally { } } set { try { Type lTypeObject; lTypeObject = value.GetType(); switch (lTypeObject.Name) { case "TDirITCompanyNew": throw (new CommonException("Ссылка должна быть на постоянный или нулевой объект")); case "TDirITCompany": case "TDirITCompanyNull": mvarHolder = value; break; default: throw (new CommonException("Не существует объекта")); } } catch (Exception e) { throw e; } finally { } } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/Software/TDirSoftware.cs
C#
bsd
7,112
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirITCompanyNull:TDirITCompanyBase { public TDirITCompanyNull() : base() { ////mvarObozn = "НеопределеннаяITCompany"; ////mvarNaim = "ITCompany Planet Venera"; mvarObozn = "Нет"; mvarNaim = "Отсутсвует"; } public override int Id {get { return 0; }} public override string Obozn { get { return mvarObozn; } set {throw (new CommonException("Обозначение нельзя изменять"));} } public override string Naim { get { return mvarNaim; } set { throw (new CommonException("Наименование нельзя изменять")); } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/ITCompany/TDirITCompanyNull.cs
C#
bsd
1,155
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirITCompanyNew:TDirITCompanyBase { public TDirITCompanyNew() : base() { mvarObozn = ""; mvarNaim = ""; } public TDirITCompanyNew(string pObozn, string pNaim) : base() { //mvarObozn = pObozn; //mvarNaim = pNaim; Obozn = pObozn; Naim = pNaim; } public override string Obozn { get{return mvarObozn;} set { try { string lObozn; lObozn = value.TrimEnd(); if (lObozn == "") { throw (new CommonException("Обозначение не должно быть пустым")); } mvarObozn = lObozn; } catch (Exception e) { throw e; } finally { } } } public override string Naim { get { return mvarNaim; } set { mvarNaim = value;} } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/ITCompany/TDirITCompanyNew.cs
C#
bsd
1,313
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirITCompany: TDirITCompanyBase { private TEsbDomainObject mvarEsbDomainObject; private int mvarId; public override string Obozn { get { return mvarObozn; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоначального заполнения справочника ////set { if (mvarObozn != value) { throw (new CommonException("Обозначение в постояяном объекте нельзя изменять")); } } set { mvarObozn = value; } } public TDirITCompany(TEsbDomainObject pEsbDomainObject, int pId, string pObozn, string pNaim): base() { mvarObozn = pObozn; mvarNaim = pNaim; mvarEsbDomainObject = pEsbDomainObject; mvarId = pId; } public override int Id { get { return mvarId; } } private TEsbDomainObject Esb { get { try { return mvarEsbDomainObject; } catch (Exception e) { throw e; } finally { } } } public override string Naim { get { return mvarNaim; } set { mvarNaim = value; } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/ITCompany/TDirITCompany.cs
C#
bsd
1,750
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObject { public abstract class TDirITCompanyBase: TDirBase { protected TDirITCompanyBase() : base() { } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/ITCompany/TDirITCompanyBase.cs
C#
bsd
252
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObject { public abstract class TDirSoftTypeBase : TDirBase { //// public override string ToString() { try{return this.Naim;} catch (Exception e1) { throw e1; } finally { } } protected TDirSoftTypeBase() : base() { } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/SoftType/TDirSoftTypeBase.cs
C#
bsd
512
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObject { public class TDirSoftType : TDirSoftTypeBase { private TEsbDomainObject mvarEsbDomainObject; private int mvarId; public override string Obozn { get { return mvarObozn; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //На время первоначального заполнения справочника ////set { if (mvarObozn != value) { throw (new CommonException("Обозначение в постояяном объекте нельзя изменять")); } } set { mvarObozn = value; } } public TDirSoftType(TEsbDomainObject pEsbDomainObject, int pId, string pObozn, string pNaim) : base() { mvarObozn = pObozn; mvarNaim = pNaim; mvarEsbDomainObject = pEsbDomainObject; mvarId = pId; } public override int Id { get { return mvarId; } } private TEsbDomainObject Esb { get { try{return mvarEsbDomainObject;} catch (Exception e) { throw e; } finally { } } } public override string Naim { get { return mvarNaim; } set { mvarNaim = value; } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/SoftType/TDirSoftType.cs
C#
bsd
1,584
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirSoftTypeNull : TDirSoftTypeBase { public override int Id { get { return 0; } } public TDirSoftTypeNull() : base() { mvarObozn = "Нет"; mvarNaim = "Отсутсвует"; } public override string Obozn { get { return mvarObozn; } set { throw (new CommonException("Обозначение нельзя изменять")); } } public override string Naim { get { return mvarNaim; } set { throw (new CommonException("Наименование нельзя изменять")); } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/SoftType/TDirSoftTypeNull.cs
C#
bsd
869
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Zzva.Common; namespace Zzva.DomainObject { public class TDirSoftTypeNew : TDirSoftTypeBase { public TDirSoftTypeNew() : base() { mvarObozn = ""; mvarNaim = ""; } public TDirSoftTypeNew(string pObozn, string pNaim) : base() { Obozn = pObozn; Naim = pNaim; } public override string Obozn { get { return mvarObozn; } set { try { string lObozn; lObozn = value.TrimEnd(); if (lObozn == "") { throw (new CommonException("Обозначение не должно быть пустым")); } mvarObozn = lObozn; } catch (Exception e) { throw e; } finally { } } } public override string Naim { get { return mvarNaim; } set { mvarNaim = value; } } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/Directory/SoftType/TDirSoftTypeNew.cs
C#
bsd
1,215
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zzva.DomainObject { public class TEqualityComparerDirBase : EqualityComparer<TDirBase> { public override bool Equals(TDirBase x, TDirBase y) {if (x.Obozn == y.Obozn) { return true; } else { return false; }} public override int GetHashCode(TDirBase obj) { return obj.Obozn.GetHashCode(); } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject/TEqualityComparerDirBase.cs
C#
bsd
456
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Zzva.DomainObject.Test { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TFrmTest()); } } }
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject.Test/Program.cs
C#
bsd
517
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Zzva.DomainObject.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("zzva")] [assembly: AssemblyProduct("Zzva.DomainObject.Test")] [assembly: AssemblyCopyright("Copyright © zzva 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("248b639b-5c1b-43f3-99aa-290aac702156")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzvalib
trunk/DomainObject/DomainObject/Zzva.DomainObject.Test/Properties/AssemblyInfo.cs
C#
bsd
1,464
package cn.com.widemex.test; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import cn.com.widemex.core.vo.PageVO; /** * XX 维护 controller类 * * @author 张中原 * */ @Controller("模块名/功能名") public class TmpController { /** * 初始化界面 * @return */ @RequestMapping public String init(){ return "demo/form/combo"; //jsp所在的模块文件夹的相关路径, //注:路径最后是jsp不要加.jsp后缀 } /** * 查询 * @param request * @return */ @RequestMapping("list") public Object list(HttpServletRequest request){ PageVO page = PageVO.valueOf(request); // 查询处理... return page; } /** * 保存或更新值 * @param pojo * @return */ @RequestMapping("save") public Object save(Object pojo){ //保存... return pojo; } /** * 删除 * @param pojo * @return */ @RequestMapping("remove") public Object remove(Object pojo){ // 删除。。。 return pojo; } }
zzyapps
trunk/JqFw/test/cn/com/widemex/test/TmpController.java
Java
asf20
1,172
package cn.com.widemex.service.system; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.stereotype.Service; import cn.com.widemex.dao.system.SmFunctionDao; import cn.com.widemex.dao.system.SmUserDao; import cn.com.widemex.domain.system.SmFunction; import cn.com.widemex.domain.system.SmRole; import cn.com.widemex.domain.system.SmUser; /** * 登录service * * @author 张中原 * */ @Service("loginService") public class LoginService { /**用户dao*/ private SmUserDao smUserDao; /**功能dao*/ private SmFunctionDao smFunctionDao; /** * 获取用户,根据账号、密码 * @param acc 账号 * @param pwd 密码 * @return */ public SmUser getUser(String acc, String pwd){ List<SmUser> list = this.smUserDao.find("select distinct a from SmUser a " + "left join fetch a.smRoles b " + "left join fetch a.smOrg c " + "where a.acc=? and a.pwd=? and b.status=1 and c.status=1", acc, pwd ); if(list.size() == 0){ return null; }else{ return list.get(0); } } /** * 根据用户获取相关功能(List集合) * @param user 用户 * @return */ public List<SmFunction> getUserFunList(SmUser user){ // 用户所有权限 List<SmFunction> userFunList = new ArrayList<SmFunction>(); // 用户所有有权限功能菜单 Map<String, SmFunction> userFunMap = this.getMapFun(user); // 一级菜单 List<SmFunction> firstFunList = this.getFirstFun(); for (SmFunction fun : firstFunList) { if(fun.getStatus()==1 && (userFunMap.get(fun.getId()) != null || "admin".equals(user.getAcc())) ){ this.fetchUserFun(fun, userFunMap, user.getAcc()); userFunList.add(fun); } } return userFunList; } /** * 抓取当前菜单的相关叶子节点 * @param fun 要抓取的菜单 * @param userFunMap 用户所有的菜单map * @param acc 账号, 如果是admin则抓取全部有效记录 */ private void fetchUserFun(SmFunction fun, Map<String, SmFunction> userFunMap, String acc){ Set<SmFunction> childrenFunSet = fun.getChildrenFuns(); if(childrenFunSet.isEmpty()){ return; }else{ for (SmFunction childFun : childrenFunSet) { if("admin".equals(acc)){ // 如果是admin if(childFun.getStatus() == 0){ childrenFunSet.remove(childFun); }else{ this.fetchUserFun(childFun, userFunMap, acc); } }else{ if(userFunMap.get(childFun.getId()) == null || childFun.getStatus()==0){ childrenFunSet.remove(childFun); }else{ this.fetchUserFun(childFun, userFunMap, acc); } } } } } /** * 获取一级菜单 * @return */ private List<SmFunction> getFirstFun(){ return this.smFunctionDao.find("select a from SmFunction a where a.status=1 and a.parentFun is null order by a.orderInd"); } /** * 根据用户获取相关功能(Map集合) * @param user 用户 * @return */ public Map<String, SmFunction> getMapFun(SmUser user){ Map<String, SmFunction> funMap = new HashMap<String, SmFunction>(); Set<SmRole> roleSet = user.getSmRoles(); for (SmRole smRole : roleSet) { Set<SmFunction> funSet = smRole.getSmFuns(); for (SmFunction smFunction : funSet) { if(smFunction.getStatus() == 1 && funMap.get(smFunction.getId())!=null){ funMap.put(smFunction.getId(), smFunction); } } } return funMap; } public SmUserDao getSmUserDao() { return smUserDao; } public void setSmUserDao(SmUserDao smUserDao) { this.smUserDao = smUserDao; } public SmFunctionDao getSmFunctionDao() { return smFunctionDao; } public void setSmFunctionDao(SmFunctionDao smFunctionDao) { this.smFunctionDao = smFunctionDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/LoginService.java
Java
asf20
3,942
package cn.com.widemex.service.system; import org.springframework.stereotype.Service; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.dao.system.SmOrgDao; import cn.com.widemex.domain.system.SmOrg; /** * 组织机构管理 * * @author 张中原 * */ @Service("smOrgService") public class SmOrgService { /**组织结构dao*/ private SmOrgDao smOrgDao; /** * 查询组织机构 * @param page 页面信息 * @return */ public PageVO list(PageVO page){ String id = page.getParams().getString("id", null); String status = page.getParams().getString("status", ""); if(!"".equals(status)){ status = " and a.status =" + status; } if(id == null){ page.setWhere("select a from SmOrg a left join fetch a.smOrgType where a.smOrg is null " + status); }else{ page.setWhere("select a from SmOrg a left join fetch a.smOrgType where a.smOrg.id=? " + status); page.setWhereParams(new Object[]{id}); } return this.smOrgDao.findPage( page ); } /** * 保存或者更新组织机构 * @param org * @return */ public SmOrg save(SmOrg org){ this.smOrgDao.saveOrUpdate(org); return org; } /** * 删除组织机构 * @param org * @return */ public SmOrg remove(SmOrg org){ org = this.smOrgDao.get(org.getId()); this.smOrgDao.remove(org); return org; } /** * 是否已经存在当中新增的记录id * @param id * @return */ public boolean isHasRecord(String id){ SmOrg org = this.smOrgDao.get(id); return org != null; } public SmOrgDao getSmOrgDao() { return smOrgDao; } public void setSmOrgDao(SmOrgDao smOrgDao) { this.smOrgDao = smOrgDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/SmOrgService.java
Java
asf20
1,751
package cn.com.widemex.service.system; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.stereotype.Service; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.dao.system.SmRoleDao; import cn.com.widemex.dao.system.SmUserDao; import cn.com.widemex.domain.system.SmOrg; import cn.com.widemex.domain.system.SmRole; import cn.com.widemex.domain.system.SmUser; /** * 角色维护service * * @author 张中原 * */ @Service("smRoleService") public class SmRoleService { /**角色dao **/ private SmRoleDao smRoleDao; /**用户dao*/ private SmUserDao smUserDao; /** * 查询 * @param page * @return */ public PageVO list(PageVO page){ String orgId = page.getParams().getString("orgId", null); String status = page.getParams().getString("status", ""); if(!"".equals(status)){ status = " and a.status = "+status; } if(orgId != null){ page.setWhere("select distinct a " + " from SmRole a " + " left join fetch a.smOrg b " + " left join fetch a.smUsers c " + " left join fetch c.smOrg d " + " left join fetch a.smFuns e " + " where b.id=? " + status); page.setWhereParams(new Object[]{orgId}); } return this.smRoleDao.findPage(page); } /** * 根据账号,获取相关角色,包括相关公共角色 * @param acc 账号 * @return */ public List<SmRole> listByUser(String acc){ List<SmRole> list = new ArrayList<SmRole>(); SmUser user = this.smUserDao.get(acc); // 当前用户拥有的普通角色 Set<SmRole> roleSet = user.getSmRoles(); for (SmRole smRole : roleSet) { list.add(smRole); } // 当前用户拥有的公共角色 //TODO... return list; } // /** // * 获取当前用户部门的所有公共角色,包括父部门 // * @param org 部门 // * @param roleList 角色集合 // * @return // */ // private List<SmRole> getPublicRoleByOrg(SmOrg org, List<SmRole> roleList){ // Set<SmRole> roleSet = org.getSmRoles(); // for (SmRole smRole : roleSet) { // if(smRole.getType().equals("PUB")){ // // } // } // } /** * 保存、更新 * @param pojo * @return */ public SmRole save(SmRole pojo){ // for (SmFunction fun : pojo.getSmFuns()) { // Bean.printValues(pojo); // } this.smRoleDao.saveOrUpdate(pojo); return pojo; } /** * 删除 * @param pojo * @return */ public SmRole remove(SmRole pojo){ pojo = this.smRoleDao.get(pojo.getId()); this.smRoleDao.remove(pojo); return pojo; } public SmRoleDao getSmRoleDao() { return smRoleDao; } public void setSmRoleDao(SmRoleDao smRoleDao) { this.smRoleDao = smRoleDao; } public SmUserDao getSmUserDao() { return smUserDao; } public void setSmUserDao(SmUserDao smUserDao) { this.smUserDao = smUserDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/SmRoleService.java
Java
asf20
2,967
package cn.com.widemex.service.system; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.stereotype.Service; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.dao.system.SmFunctionDao; import cn.com.widemex.domain.system.SmFunction; import cn.com.widemex.domain.system.SmRole; /** * 功能维护 service * * @author 张中原 * */ @Service("smFunctionService") public class SmFunctionService { /**功能dao*/ private SmFunctionDao smFunctionDao; /** * 查询 * @param page * @return */ public PageVO list(PageVO page){ String id = page.getParams().getString("id", ""); String status = page.getParams().getString("status", ""); if(!"".equals(status)){ status = " and status="+status; } String hql = "select distinct a from SmFunction a " + " left join fetch a.smRoles b " + " left join fetch b.smOrg c "; if("".equals(id)){ page.setWhere(hql + "where a.parentFun is null" + status); }else{ page.setWhere(hql + "where a.parentFun.id = ?" + status); page.setWhereParams(new Object[]{id}); } page.setWhere(page.getWhere() + " order by a.orderInd asc"); return this.smFunctionDao.findPage(page); } /** * 一次性查询加载 * @return */ public PageVO listOnce(PageVO page){ String id = page.getParams().getString("id", ""); /* String status = page.getParams().getString("status", ""); if("".equals(id)){ page.setWhere("where status=1"); }else{ page.setWhere("where parentFun.id = ? and status=1"); page.setWhereParams(new Object[]{id}); }*/ List<SmFunction> list = this.smFunctionDao.find(" from SmFunction a where a.status=? order by a.orderInd ASC ", (short)1); for (SmFunction fun : list) { if(fun.getParentFun() != null){ fun.setParentId(fun.getParentFun().getId()); } // if(fun.getChildrenFuns().size() == 0){ // fun.setState("open"); // } fun.setLoaded(true); } page.setRows(list); return this.smFunctionDao.findPage(page); } // /** // * 根据用户获取允许访问的所有菜单 // * @param acc 用户账号 // * @return // */ // public List<SmFunction> listFunByUser(String acc){ // List<SmFunction> funList = new ArrayList<SmFunction>(); // // List<SmRole> roleList = this.smRoleService.listByUser(acc); // for (SmRole smRole : roleList) { // Set<SmFunction> funSet = smRole.getSmFuns(); // for (SmFunction smFun : funSet) { // funList.add(smFun); // } // } // // return funList; // } // // /** // * 根据用户及一级菜单id获取二级菜单信息 // * @param acc 当前账号 // * @param firstFunId 一级功能菜单Id // * @return // */ // public List<SmFunction> listBySecondFunUser(String acc, String firstFunId){ // return this.smFunctionDao.find("select distinct a from SmFunction a " + // "left join a.smRoles b " + // "left join b.smUsers c " + // "left join a.parentFun d " + // "where c.acc =? and d.id = ? ", acc, firstFunId); // } /** * 保存、更新 * @param pojo * @return */ public SmFunction save(SmFunction pojo){ this.smFunctionDao.saveOrUpdate(pojo); return pojo; } /** * 删除 * @param pojo * @return */ public SmFunction remove(SmFunction pojo){ pojo = this.smFunctionDao.get(pojo.getId()); this.smFunctionDao.remove(pojo); return pojo; } /** * 是否已经存在相同编码的记录 * @param pojo * @return */ public boolean isHasRecord(SmFunction pojo){ return this.smFunctionDao.get(pojo.getId()) != null; } public SmFunctionDao getSmFunctionDao() { return smFunctionDao; } public void setSmFunctionDao(SmFunctionDao smFunctionDao) { this.smFunctionDao = smFunctionDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/SmFunctionService.java
Java
asf20
3,909
package cn.com.widemex.service.system; import java.util.HashSet; import java.util.Set; import org.springframework.stereotype.Service; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.dao.system.SmRoleDao; import cn.com.widemex.dao.system.SmUserDao; import cn.com.widemex.domain.system.SmRole; import cn.com.widemex.domain.system.SmUser; /** * 用户维护service * * @author 张中原 * */ @Service("smUserService") public class SmUserService { /**用户dao**/ private SmUserDao smUserDao; /**角色dao*/ private SmRoleDao smRoleDao; /** * 查询信息 * @param page * @return */ public PageVO list(PageVO page){ page.setWhere("select distinct a from SmUser a " + "left join fetch a.smRoles b " + "left join fetch a.smOrg c " + "where a.smOrg.id=? order by a.acc"); page.setWhereParams(new Object[]{page.getParams().getString("orgId", null)}); return this.smUserDao.findPage(page); } /** * 保存更新信息 * @param pojo * @return */ public SmUser save(SmUser pojo){ this.smUserDao.saveOrUpdate(pojo); return pojo; } /** * 删除信息 * @param pojo * @return */ public SmUser remove(SmUser pojo){ pojo = this.smUserDao.get(pojo.getId()); this.smUserDao.remove(pojo); return pojo; } /** * 是否已经存在相同的记录 * @param pojo * @return */ public boolean isHasRecord(String id){ return this.smUserDao.get(id) != null; } public SmUserDao getSmUserDao() { return smUserDao; } public void setSmUserDao(SmUserDao smUserDao) { this.smUserDao = smUserDao; } public SmRoleDao getSmRoleDao() { return smRoleDao; } public void setSmRoleDao(SmRoleDao smRoleDao) { this.smRoleDao = smRoleDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/SmUserService.java
Java
asf20
1,825
package cn.com.widemex.service.system; import java.util.List; import org.springframework.stereotype.Service; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.dao.system.SmOrgTypeDao; import cn.com.widemex.domain.system.SmOrgType; /** * 组织机构类型维护 * * @author 张中原 * */ @Service("smOrgTypeService") public class SmOrgTypeService { /**组织结构类型 dao*/ private SmOrgTypeDao smOrgTypeDao; /** * 查询 * @param page * @return */ public PageVO list(PageVO page){ return this.smOrgTypeDao.findPage(page); } /** * 查询有效数据 * @return */ public List<SmOrgType> list4ValidData(){ return this.smOrgTypeDao.findBy("status", 1); } /** * 保存 * @param orgType * @return */ public SmOrgType save(SmOrgType orgType){ this.smOrgTypeDao.saveOrUpdate(orgType); return orgType; } /** * 删除 * @param orgType * @return */ public SmOrgType remove(SmOrgType orgType){ this.smOrgTypeDao.remove(orgType); return orgType; } /** * 是否存在记录 * @param id 主键 * @return */ public boolean isHasRecord(String id){ SmOrgType type = this.smOrgTypeDao.get(id); return type!=null; } public SmOrgTypeDao getSmOrgTypeDao() { return smOrgTypeDao; } public void setSmOrgTypeDao(SmOrgTypeDao smOrgTypeDao) { this.smOrgTypeDao = smOrgTypeDao; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/service/system/SmOrgTypeService.java
Java
asf20
1,455
package cn.com.widemex.dao.system; import org.springframework.stereotype.Repository; import cn.com.widemex.core.db.HibernateDao; import cn.com.widemex.domain.system.SmFunction; /** * 功能 dao * * @author 张中原 * */ @Repository("smFunctionDao") public class SmFunctionDao extends HibernateDao<SmFunction> { }
zzyapps
trunk/JqFw/src/cn/com/widemex/dao/system/SmFunctionDao.java
Java
asf20
338
package cn.com.widemex.dao.system; import org.springframework.stereotype.Repository; import cn.com.widemex.core.db.HibernateDao; import cn.com.widemex.domain.system.SmOrg; /** * 组织机构 dao * * @author 张中原 * */ @Repository("smOrgDao") public class SmOrgDao extends HibernateDao<SmOrg> { }
zzyapps
trunk/JqFw/src/cn/com/widemex/dao/system/SmOrgDao.java
Java
asf20
324
package cn.com.widemex.dao.system; import org.springframework.stereotype.Repository; import cn.com.widemex.core.db.HibernateDao; import cn.com.widemex.domain.system.SmUser; /** * 用户 dao * * @author 张中原 * */ @Repository("smUserDao") public class SmUserDao extends HibernateDao<SmUser> { }
zzyapps
trunk/JqFw/src/cn/com/widemex/dao/system/SmUserDao.java
Java
asf20
322
package cn.com.widemex.dao.system; import org.springframework.stereotype.Repository; import cn.com.widemex.core.db.HibernateDao; import cn.com.widemex.domain.system.SmRole; /** * 角色dao * * @author 张中原 * */ @Repository("smRoleDao") public class SmRoleDao extends HibernateDao<SmRole> { }
zzyapps
trunk/JqFw/src/cn/com/widemex/dao/system/SmRoleDao.java
Java
asf20
321
package cn.com.widemex.dao.system; import org.springframework.stereotype.Repository; import cn.com.widemex.core.db.HibernateDao; import cn.com.widemex.domain.system.SmOrgType; /** * 组织机构类型dao * * @author 张中原 * */ @Repository("smOrgTypeDao") public class SmOrgTypeDao extends HibernateDao<SmOrgType> { }
zzyapps
trunk/JqFw/src/cn/com/widemex/dao/system/SmOrgTypeDao.java
Java
asf20
345
package cn.com.widemex.action.system; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import cn.com.widemex.service.system.SmFunctionService; @Controller @RequestMapping("sys") public class HomeController { /**功能service*/ private SmFunctionService smFunctionService; /** * 初始化首页 * @param model * @return */ @RequestMapping("home") public String initHome(Model model){ return "home"; } public SmFunctionService getSmFunctionService() { return smFunctionService; } public void setSmFunctionService(SmFunctionService smFunctionService) { this.smFunctionService = smFunctionService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/HomeController.java
Java
asf20
770
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.core.vo.MsgVO; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.domain.system.SmFunction; import cn.com.widemex.service.system.SmFunctionService; /** * 功能维护controller * * @author 张中原 * */ @Controller @RequestMapping("sys/fun") public class FunctionController { /**日志*/ private Logger logger = Logger.getLogger(FunctionController.class); /**功能维护service**/ private SmFunctionService smFunctionService; /** * 初始化界面 * @return */ @RequestMapping public String init(){ return "system/function/fun"; } /** * 初始化功能排序界面 * @return */ @RequestMapping("initFunOrder") public String initFunOrderPage(){ return "system/function/funOrder"; } /** * 查询 * @param request * @return */ @RequestMapping("list") @ResponseBody public Object list(HttpServletRequest request){ return this.smFunctionService.list(PageVO.valueOf(request)); } /** * 一次性查询(在业务中,有需要) * @param request * @return */ @RequestMapping("listOnce") @ResponseBody public Object listOnce(HttpServletRequest request){ return this.smFunctionService.listOnce(PageVO.valueOf(request)); } /** * 保存记录 * @param pojo * @return */ @RequestMapping("save") @ResponseBody public Object save(SmFunction pojo){ return this.smFunctionService.save(pojo); } /** * 删除 * @param pojo * @return */ @RequestMapping("remove") @ResponseBody public Object remove(SmFunction pojo){ MsgVO msg = MsgVO.valueOf(true); try { return this.smFunctionService.remove(pojo); } catch (Exception e) { e.printStackTrace(); String mess = "当前记录被相关业务表使用,请先确认!"; logger.error(mess); msg.setMessage(mess); msg.setSuccess(false); } return msg; } /** * 是否已经存在相同编码的记录 * @param pojo * @return */ @RequestMapping("isHasRecord") @ResponseBody public Object isHasRecord(SmFunction pojo){ return MsgVO.valueOf(this.smFunctionService.isHasRecord(pojo)); } public SmFunctionService getSmFunctionService() { return smFunctionService; } public void setSmFunctionService(SmFunctionService smFunctionService) { this.smFunctionService = smFunctionService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/FunctionController.java
Java
asf20
2,741
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.core.vo.MsgVO; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.domain.system.SmOrg; import cn.com.widemex.service.system.SmOrgService; import cn.com.widemex.service.system.SmOrgTypeService; /** * 组织机构维护 * @author 张中原 * */ @Controller @RequestMapping("sys/org") public class OrgController { /**日志*/ Logger logger = Logger.getLogger(OrgController.class); /**机构维护service*/ private SmOrgService smOrgService; /**机构类型service**/ private SmOrgTypeService smOrgTypeService; /** * 初始化 * @return */ @RequestMapping public String init(Model model){ model.addAttribute("orgTypeList", this.smOrgTypeService.list4ValidData()); return "system/org/org"; } /** * 查询 * @return */ @RequestMapping("list") public @ResponseBody Object list(HttpServletRequest request){ return this.smOrgService.list(PageVO.valueOf(request)); } /** * 保存 * @param org * @param oldId * @return */ @RequestMapping("save") public @ResponseBody Object save(SmOrg org, String oldId){ this.smOrgService.save(org); return org; } /** * 删除 * @param org * @return */ @RequestMapping("remove") public @ResponseBody Object remove(SmOrg org){ MsgVO msg = MsgVO.valueOf(true, null, org); try { this.smOrgService.remove(org); } catch (Exception e) { String mess = "当前记录以及被相关子表使用,请确定!"; logger.error(mess); msg.setSuccess(false); msg.setMessage(mess); } return msg; } /** * 是否已经存在当前新增的编码 * @param id * @return */ @RequestMapping("isHasRecord") public @ResponseBody Object isHasRecord(SmOrg org){ return MsgVO.valueOf(this.smOrgService.isHasRecord(org.getId())); } public SmOrgService getSmOrgService() { return smOrgService; } public void setSmOrgService(SmOrgService smOrgService) { this.smOrgService = smOrgService; } public SmOrgTypeService getSmOrgTypeService() { return smOrgTypeService; } public void setSmOrgTypeService(SmOrgTypeService smOrgTypeService) { this.smOrgTypeService = smOrgTypeService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/OrgController.java
Java
asf20
2,598
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.core.vo.MsgVO; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.domain.system.SmUser; import cn.com.widemex.service.system.SmUserService; /** * 用户维护 * @author 张中原 * */ @Controller @RequestMapping("sys/user") public class UserController { /**日志**/ private static Logger logger = Logger.getLogger(UserController.class); /**用户维护service**/ private SmUserService smUserService; /** * 初始化用户维护界面 * @return */ @RequestMapping public String init(){ return "system/user/user"; } /** * 查询 * @return */ @RequestMapping("list") public @ResponseBody Object list(HttpServletRequest request){ return this.smUserService.list(PageVO.valueOf(request)); } /** * 保存 * @return */ @RequestMapping("save") public @ResponseBody Object save(SmUser pojo){ return this.smUserService.save(pojo); } /** * 删除 * @return */ @RequestMapping("remove") public @ResponseBody Object remove(SmUser pojo){ MsgVO msg = MsgVO.valueOf(true, null, pojo); try { this.smUserService.remove(pojo); } catch (Exception e) { String mess = "当前用户已经其他子表或者业务表使用,不能直接删除,请确定!"; e.printStackTrace(); logger.error(mess); msg.setSuccess(false); msg.setMessage(mess); } return msg; } /** * 是否已经存在相同的记录 * @param pojo * @return */ @RequestMapping("isHasRecord") public @ResponseBody boolean isHasRecord(SmUser pojo){ return this.smUserService.isHasRecord(pojo.getId()); } public SmUserService getSmUserService() { return smUserService; } public void setSmUserService(SmUserService smUserService) { this.smUserService = smUserService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/UserController.java
Java
asf20
2,150
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.domain.system.SmRole; import cn.com.widemex.service.system.SmRoleService; /** *角色维护 controller类 * * @author 张中原 * */ @Controller @RequestMapping("sys/role") public class RoleController { /**日志*/ private static Logger logger = Logger.getLogger(RoleController.class); /**角色维护service*/ private SmRoleService smRoleService; /** * 初始化界面 * @return */ @RequestMapping public String init(){ return "system/role/role"; } /** * 查询 * @param request * @return */ @RequestMapping("list") @ResponseBody public Object list(HttpServletRequest request){ return this.smRoleService.list(PageVO.valueOf(request)); } /** * 保存、更新 * @param pojo * @return */ @RequestMapping("save") @ResponseBody public Object save(SmRole pojo){ return this.smRoleService.save(pojo); } /** * 删除 * @param pojo * @return */ @RequestMapping("remove") @ResponseBody public Object remove(SmRole pojo){ return this.smRoleService.remove(pojo); } public SmRoleService getSmRoleService() { return smRoleService; } public void setSmRoleService(SmRoleService smRoleService) { this.smRoleService = smRoleService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/RoleController.java
Java
asf20
1,644
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.core.vo.MsgVO; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.domain.system.SmOrgType; import cn.com.widemex.service.system.SmOrgTypeService; /** * 组织机构类型维护 controller * * @author 张中原 * */ @Controller @RequestMapping("sys/orgType") public class OrgTypeController { /**日志*/ Logger logger = Logger.getLogger(OrgTypeController.class); /**组织结构类型 service*/ private SmOrgTypeService smOrgTypeService; /** * 初始化界面 * @return */ @RequestMapping public String init(){ return "system/orgType/orgType"; } /** * 查询 * @param request * @return */ @RequestMapping("list") public @ResponseBody Object list(HttpServletRequest request){ PageVO page = PageVO.valueOf(request); return this.smOrgTypeService.list(page); } /** * 获取有效机构类别信息 * @param request * @return */ @RequestMapping("list4ValidData") public @ResponseBody Object list4ValidData(){ return this.smOrgTypeService.list4ValidData(); } /** * 保存或更新值 * @param pojo * @return */ @RequestMapping("save") public @ResponseBody Object save(SmOrgType pojo){ this.smOrgTypeService.save(pojo); return pojo; } /** * 删除 * @param pojo * @return */ @RequestMapping("remove") public @ResponseBody Object remove(SmOrgType pojo){ MsgVO msg = new MsgVO(); msg.setRows(pojo); try { this.smOrgTypeService.remove(pojo); msg.setSuccess(true); } catch (Exception e) { String mess = "当前记录以及被相关子表使用,请确定!"; logger.error(mess); msg.setSuccess(false); msg.setMessage(mess); } return msg; } /** * 是否已经已经存在当前记录 * @param id 主键 * @return */ @RequestMapping("isHasRecord") public @ResponseBody Object isHasRecord(HttpServletRequest request){ MsgVO msg = MsgVO.valueOf(request); msg.setSuccess(this.smOrgTypeService.isHasRecord(msg.getParams().getString("orgTypeId"))); return msg; } public SmOrgTypeService getSmOrgTypeService() { return smOrgTypeService; } public void setSmOrgTypeService(SmOrgTypeService smOrgTypeService) { this.smOrgTypeService = smOrgTypeService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/OrgTypeController.java
Java
asf20
2,633
package cn.com.widemex.action.system; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import cn.com.widemex.domain.system.SmUser; import cn.com.widemex.service.system.LoginService; /** * 登录 * @author 张中原 * */ @Controller @RequestMapping("sys") public class LoginController { /**登录service*/ private LoginService loginService; @RequestMapping("checkLogin") public @ResponseBody Object checkLogin(@RequestParam String acc, @RequestParam String pwd, HttpServletRequest request){ boolean flag = false; SmUser user = this.loginService.getUser(acc, pwd); if(user != null){ // Map<String, SmFunction> funMap = this.loginService.getMapFun(user); HttpSession session = request.getSession(); session.setAttribute("USER_INFO", user); // session.setAttribute("USER_FUN_MAP", funMap); session.setAttribute("USER_FUN_LIST", this.loginService.getUserFunList(user)); flag = true; } return flag; } /** * 退出登录 * @param request * @return */ @RequestMapping("logout") public @ResponseBody boolean logout(HttpServletRequest request){ HttpSession session = request.getSession(); if(session != null){ session.invalidate(); } return true; } public LoginService getLoginService() { return loginService; } public void setLoginService(LoginService loginService) { this.loginService = loginService; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/action/system/LoginController.java
Java
asf20
1,721
package cn.com.widemex.domain.system; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * SmOrgType entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "sm_org_type", catalog = "wm_sys") public class SmOrgType implements java.io.Serializable { // Fields private String orgTypeId; private String typeName; private Integer orgLevel; private Integer status; private Set<SmOrg> smOrgs = new HashSet<SmOrg>(0); // Constructors /** default constructor */ public SmOrgType() { } /** minimal constructor */ public SmOrgType(String orgTypeId, String typeName, Integer orgLevel, Integer status) { this.orgTypeId = orgTypeId; this.typeName = typeName; this.orgLevel = orgLevel; this.status = status; } /** full constructor */ public SmOrgType(String orgTypeId, String typeName, Integer orgLevel, Integer status, Set<SmOrg> smOrgs) { this.orgTypeId = orgTypeId; this.typeName = typeName; this.orgLevel = orgLevel; this.status = status; this.smOrgs = smOrgs; } // Property accessors @Id @Column(name = "ORG_TYPE_ID", unique = true, nullable = false, length = 32) public String getOrgTypeId() { return this.orgTypeId; } public void setOrgTypeId(String orgTypeId) { this.orgTypeId = orgTypeId; } @Column(name = "TYPE_NAME", nullable = false, length = 40) public String getTypeName() { return this.typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } @Column(name = "ORG_LEVEL", nullable = false) public Integer getOrgLevel() { return this.orgLevel; } public void setOrgLevel(Integer orgLevel) { this.orgLevel = orgLevel; } @Column(name = "STATUS", nullable = false) public Integer getStatus() { return this.status; } public void setStatus(Integer status) { this.status = status; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smOrgType") public Set<SmOrg> getSmOrgs() { return this.smOrgs; } public void setSmOrgs(Set<SmOrg> smOrgs) { this.smOrgs = smOrgs; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/domain/system/SmOrgType.java
Java
asf20
2,268
package cn.com.widemex.domain.system; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.codehaus.jackson.annotate.JsonBackReference; import org.codehaus.jackson.annotate.JsonManagedReference; import cn.com.widemex.core.vo.TreeVO; /** * SmFunction entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "sm_function", catalog = "wm_sys") public class SmFunction extends TreeVO implements java.io.Serializable { // Fields private String id; @JsonBackReference private SmFunction parentFun; private String code; private String name; private String type; private String funPath; private Integer orderInd; private String iconCls; private String remark; private Short status; private String uiPath; private Set<SmRole> smRoles = new HashSet<SmRole>(0); private Set<SmFunction> childrenFuns = new HashSet<SmFunction>(0); // Constructors /** default constructor */ public SmFunction() { } /** minimal constructor */ public SmFunction(String id, String code, String name, String type, Short status) { this.id = id; this.code = code; this.name = name; this.type = type; this.status = status; } /** full constructor */ public SmFunction(String id, SmFunction smFunction, String code, String name, String type, String funPath, Integer orderInd, String iconCls, String remark, Short status, String uiPath, Set<SmFunction> smFunctions) { this.id = id; // this.smFunction = smFunction; this.code = code; this.name = name; this.type = type; this.funPath = funPath; this.orderInd = orderInd; this.iconCls = iconCls; this.remark = remark; this.status = status; this.uiPath = uiPath; // this.smRoleFunMaps = smRoleFunMaps; // this.smFunctions = smFunctions; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "P_ID") public SmFunction getParentFun() { return parentFun; } public void setParentFun(SmFunction parentFun) { this.parentFun = parentFun; } @Column(name = "CODE", nullable = false, length = 20) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "NAME", nullable = false, length = 40) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "TYPE", nullable = false, length = 32) public String getType() { return this.type; } public void setType(String type) { this.type = type; if("BASE".equals(this.type)){ this.setLeaf(true); this.setState("open"); }else{ this.setState("closed"); } } @Column(name = "FUN_PATH", length = 2000) public String getFunPath() { return this.funPath; } public void setFunPath(String funPath) { this.funPath = funPath; } @Column(name = "ORDER_IND") public Integer getOrderInd() { return this.orderInd; } public void setOrderInd(Integer orderInd) { this.orderInd = orderInd; } @Column(name = "ICON_CLS", length = 20) public String getIconCls() { return this.iconCls; } public void setIconCls(String iconCls) { this.iconCls = iconCls; } @Column(name = "REMARK", length = 400) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "STATUS", nullable = false) public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } @Column(name = "UI_PATH", length = 2000) public String getUiPath() { return this.uiPath; } public void setUiPath(String uiPath) { this.uiPath = uiPath; } @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.LAZY) @JoinTable(name = "sm_role_fun_map", catalog = "wm_sys", joinColumns = @JoinColumn(name = "FUN_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID")) public Set<SmRole> getSmRoles() { return smRoles; } public void setSmRoles(Set<SmRole> smRoles) { this.smRoles = smRoles; } // @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smFunction") // public Set<SmRoleFunMap> getSmRoleFunMaps() { // return this.smRoleFunMaps; // } // // public void setSmRoleFunMaps(Set<SmRoleFunMap> smRoleFunMaps) { // this.smRoleFunMaps = smRoleFunMaps; // } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parentFun") @OrderBy(value="orderInd asc") public Set<SmFunction> getChildrenFuns() { return childrenFuns; } public void setChildrenFuns(Set<SmFunction> childrenFuns) { this.childrenFuns = childrenFuns; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/domain/system/SmFunction.java
Java
asf20
5,162
package cn.com.widemex.domain.system; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * SmRole entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "sm_role", catalog = "wm_sys") public class SmRole implements java.io.Serializable { // Fields private String id; private SmOrg smOrg; private String name; private String type; private String remark; private Short status; private Set<SmUser> smUsers = new HashSet<SmUser>(0); private Set<SmFunction> smFuns = new HashSet<SmFunction>(0); // Constructors /** default constructor */ public SmRole() { } /** minimal constructor */ public SmRole(String id, SmOrg smOrg, String name, String type, Short status) { this.id = id; this.smOrg = smOrg; this.name = name; this.type = type; this.status = status; } /** full constructor */ public SmRole(String id, SmOrg smOrg, String name, String type, String remark, Short status) { this.id = id; this.smOrg = smOrg; this.name = name; this.type = type; this.remark = remark; this.status = status; // this.smUserRoleMaps = smUserRoleMaps; // this.smRoleFunMaps = smRoleFunMaps; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, length = 32) @GeneratedValue(generator = "SmRole") @GenericGenerator(name = "SmRole", strategy = "uuid") public String getId() { return this.id; } public void setId(String id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ORG_ID", nullable = false) public SmOrg getSmOrg() { return this.smOrg; } public void setSmOrg(SmOrg smOrg) { this.smOrg = smOrg; } @Column(name = "NAME", nullable = false, length = 60) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "TYPE", nullable = false, length = 2) public String getType() { return this.type; } public void setType(String type) { this.type = type; } @Column(name = "REMARK", length = 160) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "STATUS", nullable = false) public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } //@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.REFRESH},mappedBy="smRoles",targetEntity=SmUser.class) @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinTable(name = "SM_USER_ROLE_MAP", catalog = "wm_sys", joinColumns = @JoinColumn(name = "ROLE_ID"), inverseJoinColumns = @JoinColumn(name = "USER_ID")) public Set<SmUser> getSmUsers() { return smUsers; } public void setSmUsers(Set<SmUser> smUsers) { this.smUsers = smUsers; } // @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smRole") // public Set<SmUserRoleMap> getSmUserRoleMaps() { // return this.smUserRoleMaps; // } // // public void setSmUserRoleMaps(Set<SmUserRoleMap> smUserRoleMaps) { // this.smUserRoleMaps = smUserRoleMaps; // } @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinTable(name = "sm_role_fun_map", catalog = "wm_sys", joinColumns = @JoinColumn(name = "ROLE_ID"), inverseJoinColumns = @JoinColumn(name = "FUN_ID")) public Set<SmFunction> getSmFuns() { return smFuns; } public void setSmFuns(Set<SmFunction> smFuns) { this.smFuns = smFuns; } // // @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smRole") // public Set<SmRoleFunMap> getSmRoleFunMaps() { // return this.smRoleFunMaps; // } // // public void setSmRoleFunMaps(Set<SmRoleFunMap> smRoleFunMaps) { // this.smRoleFunMaps = smRoleFunMaps; // } }
zzyapps
trunk/JqFw/src/cn/com/widemex/domain/system/SmRole.java
Java
asf20
4,201
package cn.com.widemex.domain.system; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * SmUser entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "sm_user", catalog = "wm_sys") public class SmUser implements java.io.Serializable { // Fields private String id; private SmOrg smOrg; private String acc; private String pwd; private String name; private String code; private String type; private String phone; private String email; private String remark; private Short status; private Set<SmRole> smRoles = new HashSet<SmRole>(0); // Constructors /** default constructor */ public SmUser() { //this.smRoles.add(new SmRole()); } /** minimal constructor */ public SmUser(String id, SmOrg smOrg, String acc, String pwd, String name, String type, Short status) { this.id = id; this.smOrg = smOrg; this.acc = acc; this.pwd = pwd; this.name = name; this.type = type; this.status = status; } /** full constructor */ public SmUser(String id, SmOrg smOrg, String acc, String pwd, String name, String code, String type, String phone, String email, String remark, Short status) { this.id = id; this.smOrg = smOrg; this.acc = acc; this.pwd = pwd; this.name = name; this.code = code; this.type = type; this.phone = phone; this.email = email; this.remark = remark; this.status = status; // this.smUserRoleMaps = smUserRoleMaps; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ORG_ID", nullable = false) public SmOrg getSmOrg() { return this.smOrg; } public void setSmOrg(SmOrg smOrg) { this.smOrg = smOrg; } @Column(name = "ACC", nullable = false, length = 40) public String getAcc() { return this.acc; } public void setAcc(String acc) { this.acc = acc; } @Column(name = "PWD", nullable = false, length = 128) public String getPwd() { return this.pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Column(name = "NAME", nullable = false, length = 40) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "CODE", length = 10) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "TYPE", nullable = false, length = 10) public String getType() { return this.type; } public void setType(String type) { this.type = type; } @Column(name = "PHONE", length = 20) public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "EMAIL", length = 80) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Column(name = "REMARK", length = 200) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "STATUS", nullable = false) public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.REFRESH }, fetch = FetchType.LAZY) @JoinTable(name = "SM_USER_ROLE_MAP", catalog = "wm_sys", joinColumns = @JoinColumn(name = "USER_ID"), inverseJoinColumns = @JoinColumn(name = "ROLE_ID")) public Set<SmRole> getSmRoles() { return smRoles; } public void setSmRoles(Set<SmRole> smRoles) { this.smRoles = smRoles; } // @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smUser") // public Set<SmUserRoleMap> getSmUserRoleMaps() { // return this.smUserRoleMaps; // } // // public void setSmUserRoleMaps(Set<SmUserRoleMap> smUserRoleMaps) { // this.smUserRoleMaps = smUserRoleMaps; // } }
zzyapps
trunk/JqFw/src/cn/com/widemex/domain/system/SmUser.java
Java
asf20
4,313
package cn.com.widemex.domain.system; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * SmOrg entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "sm_org", catalog = "wm_sys") public class SmOrg implements java.io.Serializable { // Fields private String id; private SmOrgType smOrgType; private SmOrg smOrg; private String name; private String code; private String fullName; private String remark; private Integer status; private Set<SmRole> smRoles = new HashSet<SmRole>(0); private Set<SmOrg> smOrgs = new HashSet<SmOrg>(0); private Set<SmUser> smUsers = new HashSet<SmUser>(0); // Constructors /** default constructor */ public SmOrg() { } /** minimal constructor */ public SmOrg(String id, SmOrgType smOrgType, String name, Integer status) { this.id = id; this.smOrgType = smOrgType; this.name = name; this.status = status; } /** full constructor */ public SmOrg(String id, SmOrgType smOrgType, SmOrg smOrg, String name, String code, String fullName, String remark, Integer status, Set<SmRole> smRoles, Set<SmOrg> smOrgs, Set<SmUser> smUsers) { this.id = id; this.smOrgType = smOrgType; this.smOrg = smOrg; this.name = name; this.code = code; this.fullName = fullName; this.remark = remark; this.status = status; this.smRoles = smRoles; this.smOrgs = smOrgs; this.smUsers = smUsers; } // Property accessors @Id @Column(name = "ID", unique = true, nullable = false, length = 32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "TYPE_ID", nullable = false) public SmOrgType getSmOrgType() { return this.smOrgType; } public void setSmOrgType(SmOrgType smOrgType) { this.smOrgType = smOrgType; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PID") public SmOrg getSmOrg() { return this.smOrg; } public void setSmOrg(SmOrg smOrg) { this.smOrg = smOrg; } @Column(name = "NAME", nullable = false, length = 60) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "CODE", length = 20) public String getCode() { return this.code; } public void setCode(String code) { this.code = code; } @Column(name = "FULL_NAME", length = 200) public String getFullName() { return this.fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Column(name = "REMARK", length = 160) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "STATUS", nullable = false) public Integer getStatus() { return this.status; } public void setStatus(Integer status) { this.status = status; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smOrg") public Set<SmRole> getSmRoles() { return this.smRoles; } public void setSmRoles(Set<SmRole> smRoles) { this.smRoles = smRoles; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smOrg") public Set<SmOrg> getSmOrgs() { return this.smOrgs; } public void setSmOrgs(Set<SmOrg> smOrgs) { this.smOrgs = smOrgs; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "smOrg") public Set<SmUser> getSmUsers() { return this.smUsers; } public void setSmUsers(Set<SmUser> smUsers) { this.smUsers = smUsers; } }
zzyapps
trunk/JqFw/src/cn/com/widemex/domain/system/SmOrg.java
Java
asf20
3,777
/* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import java.beans.PropertyChangeEvent; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.CollectionFactory; import org.springframework.core.GenericCollectionTypeResolver; import org.springframework.core.MethodParameter; import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.Property; import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import cn.com.widemex.core.utils.reflection.Bean; import cn.com.widemex.core.utils.reflection.GenericsUtils; /** * Default {@link BeanWrapper} implementation that should be sufficient * for all typical use cases. Caches introspection results for efficiency. * * <p>Note: Auto-registers default property editors from the * <code>org.springframework.beans.propertyeditors</code> package, which apply * in addition to the JDK's standard PropertyEditors. Applications can call * the {@link #registerCustomEditor(Class, java.beans.PropertyEditor)} method * to register an editor for a particular instance (i.e. they are not shared * across the application). See the base class * {@link PropertyEditorRegistrySupport} for details. * * <p><code>BeanWrapperImpl</code> will convert collection and array values * to the corresponding target collections or arrays, if necessary. Custom * property editors that deal with collections or arrays can either be * written via PropertyEditor's <code>setValue</code>, or against a * comma-delimited String via <code>setAsText</code>, as String arrays are * converted in such a format if the array itself is not assignable. * * <p><b>NOTE: As of Spring 2.5, this is - for almost all purposes - an * internal class.</b> It is just public in order to allow for access from * other framework packages. For standard application access purposes, use the * {@link PropertyAccessorFactory#forBeanPropertyAccess} factory method instead. * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @since 15 April 2001 * @see #registerCustomEditor * @see #setPropertyValues * @see #setPropertyValue * @see #getPropertyValue * @see #getPropertyType * @see BeanWrapper * @see PropertyEditorRegistrySupport */ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWrapper { /** * We'll create a lot of these objects, so we don't want a new logger every time. */ private static final Log logger = LogFactory.getLog(BeanWrapperImpl.class); /** The wrapped object */ private Object object; private String nestedPath = ""; private Object rootObject; private TypeConverterDelegate typeConverterDelegate; /** * The security context used for invoking the property methods */ private AccessControlContext acc; /** * Cached introspections results for this object, to prevent encountering * the cost of JavaBeans introspection every time. */ private CachedIntrospectionResults cachedIntrospectionResults; /** * Map with cached nested BeanWrappers: nested path -> BeanWrapper instance. */ private Map<String, BeanWrapperImpl> nestedBeanWrappers; private boolean autoGrowNestedPaths = false; private int autoGrowCollectionLimit = Integer.MAX_VALUE; /** * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. * Registers default editors. * @see #setWrappedInstance */ public BeanWrapperImpl() { this(true); } /** * Create new empty BeanWrapperImpl. Wrapped instance needs to be set afterwards. * @param registerDefaultEditors whether to register default editors * (can be suppressed if the BeanWrapper won't need any type conversion) * @see #setWrappedInstance */ public BeanWrapperImpl(boolean registerDefaultEditors) { if (registerDefaultEditors) { registerDefaultEditors(); } this.typeConverterDelegate = new TypeConverterDelegate(this); } /** * Create new BeanWrapperImpl for the given object. * @param object object wrapped by this BeanWrapper */ public BeanWrapperImpl(Object object) { registerDefaultEditors(); setWrappedInstance(object); } /** * Create new BeanWrapperImpl, wrapping a new instance of the specified class. * @param clazz class to instantiate and wrap */ public BeanWrapperImpl(Class<?> clazz) { registerDefaultEditors(); setWrappedInstance(BeanUtils.instantiateClass(clazz)); } /** * Create new BeanWrapperImpl for the given object, * registering a nested path that the object is in. * @param object object wrapped by this BeanWrapper * @param nestedPath the nested path of the object * @param rootObject the root object at the top of the path */ public BeanWrapperImpl(Object object, String nestedPath, Object rootObject) { registerDefaultEditors(); setWrappedInstance(object, nestedPath, rootObject); } /** * Create new BeanWrapperImpl for the given object, * registering a nested path that the object is in. * @param object object wrapped by this BeanWrapper * @param nestedPath the nested path of the object * @param superBw the containing BeanWrapper (must not be <code>null</code>) */ private BeanWrapperImpl(Object object, String nestedPath, BeanWrapperImpl superBw) { setWrappedInstance(object, nestedPath, superBw.getWrappedInstance()); setExtractOldValueForEditor(superBw.isExtractOldValueForEditor()); setAutoGrowNestedPaths(superBw.isAutoGrowNestedPaths()); setAutoGrowCollectionLimit(superBw.getAutoGrowCollectionLimit()); setConversionService(superBw.getConversionService()); setSecurityContext(superBw.acc); } //--------------------------------------------------------------------- // Implementation of BeanWrapper interface //--------------------------------------------------------------------- /** * Switch the target object, replacing the cached introspection results only * if the class of the new object is different to that of the replaced object. * @param object the new target object */ public void setWrappedInstance(Object object) { setWrappedInstance(object, "", null); } /** * Switch the target object, replacing the cached introspection results only * if the class of the new object is different to that of the replaced object. * @param object the new target object * @param nestedPath the nested path of the object * @param rootObject the root object at the top of the path */ public void setWrappedInstance(Object object, String nestedPath, Object rootObject) { Assert.notNull(object, "Bean object must not be null"); this.object = object; this.nestedPath = (nestedPath != null ? nestedPath : ""); this.rootObject = (!"".equals(this.nestedPath) ? rootObject : object); this.nestedBeanWrappers = null; this.typeConverterDelegate = new TypeConverterDelegate(this, object); setIntrospectionClass(object.getClass()); } public final Object getWrappedInstance() { return this.object; } public final Class getWrappedClass() { return (this.object != null ? this.object.getClass() : null); } /** * Return the nested path of the object wrapped by this BeanWrapper. */ public final String getNestedPath() { return this.nestedPath; } /** * Return the root object at the top of the path of this BeanWrapper. * @see #getNestedPath */ public final Object getRootInstance() { return this.rootObject; } /** * Return the class of the root object at the top of the path of this BeanWrapper. * @see #getNestedPath */ public final Class getRootClass() { return (this.rootObject != null ? this.rootObject.getClass() : null); } /** * Set whether this BeanWrapper should attempt to "auto-grow" a nested path that contains a null value. * <p>If "true", a null path location will be populated with a default object value and traversed * instead of resulting in a {@link NullValueInNestedPathException}. Turning this flag on also * enables auto-growth of collection elements when accessing an out-of-bounds index. * <p>Default is "false" on a plain BeanWrapper. */ public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths) { this.autoGrowNestedPaths = autoGrowNestedPaths; } /** * Return whether "auto-growing" of nested paths has been activated. */ public boolean isAutoGrowNestedPaths() { return this.autoGrowNestedPaths; } /** * Specify a limit for array and collection auto-growing. * <p>Default is unlimited on a plain BeanWrapper. */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Set the security context used during the invocation of the wrapped instance methods. * Can be null. */ public void setSecurityContext(AccessControlContext acc) { this.acc = acc; } /** * Return the security context used during the invocation of the wrapped instance methods. * Can be null. */ public AccessControlContext getSecurityContext() { return this.acc; } /** * Set the class to introspect. * Needs to be called when the target object changes. * @param clazz the class to introspect */ protected void setIntrospectionClass(Class clazz) { if (this.cachedIntrospectionResults != null && !clazz.equals(this.cachedIntrospectionResults.getBeanClass())) { this.cachedIntrospectionResults = null; } } /** * Obtain a lazily initializted CachedIntrospectionResults instance * for the wrapped object. */ private CachedIntrospectionResults getCachedIntrospectionResults() { Assert.state(this.object != null, "BeanWrapper does not hold a bean instance"); if (this.cachedIntrospectionResults == null) { this.cachedIntrospectionResults = CachedIntrospectionResults.forClass(getWrappedClass()); } return this.cachedIntrospectionResults; } public PropertyDescriptor[] getPropertyDescriptors() { return getCachedIntrospectionResults().getPropertyDescriptors(); } public PropertyDescriptor getPropertyDescriptor(String propertyName) throws BeansException { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd == null) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "No property '" + propertyName + "' found"); } return pd; } /** * Internal version of {@link #getPropertyDescriptor}: * Returns <code>null</code> if not found rather than throwing an exception. * @param propertyName the property to obtain the descriptor for * @return the property descriptor for the specified property, * or <code>null</code> if not found * @throws BeansException in case of introspection failure */ protected PropertyDescriptor getPropertyDescriptorInternal(String propertyName) throws BeansException { Assert.notNull(propertyName, "Property name must not be null"); BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); return nestedBw.getCachedIntrospectionResults().getPropertyDescriptor(getFinalPath(nestedBw, propertyName)); } @Override public Class getPropertyType(String propertyName) throws BeansException { try { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { return pd.getPropertyType(); } else { // Maybe an indexed/mapped property... Object value = getPropertyValue(propertyName); if (value != null) { return value.getClass(); } // Check to see if there is a custom editor, // which might give an indication on the desired target type. Class editorType = guessPropertyTypeFromEditors(propertyName); if (editorType != null) { return editorType; } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; } public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException { try { BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); String finalPath = getFinalPath(nestedBw, propertyName); PropertyTokenHolder tokens = getPropertyNameTokens(finalPath); PropertyDescriptor pd = nestedBw.getCachedIntrospectionResults().getPropertyDescriptor(tokens.actualName); if (pd != null) { if (tokens.keys != null) { if (pd.getReadMethod() != null || pd.getWriteMethod() != null) { return TypeDescriptor.nested(property(pd), tokens.keys.length); } } else { if (pd.getReadMethod() != null || pd.getWriteMethod() != null) { return new TypeDescriptor(property(pd)); } } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; } public boolean isReadableProperty(String propertyName) { try { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { if (pd.getReadMethod() != null) { return true; } } else { // Maybe an indexed/mapped property... getPropertyValue(propertyName); return true; } } catch (InvalidPropertyException ex) { // Cannot be evaluated, so can't be readable. } return false; } public boolean isWritableProperty(String propertyName) { try { PropertyDescriptor pd = getPropertyDescriptorInternal(propertyName); if (pd != null) { if (pd.getWriteMethod() != null) { return true; } } else { // Maybe an indexed/mapped property... getPropertyValue(propertyName); return true; } } catch (InvalidPropertyException ex) { // Cannot be evaluated, so can't be writable. } return false; } public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam) throws TypeMismatchException { try { return this.typeConverterDelegate.convertIfNecessary(value, requiredType, methodParam); } catch (ConverterNotFoundException ex) { throw new ConversionNotSupportedException(value, requiredType, ex); } catch (ConversionException ex) { throw new TypeMismatchException(value, requiredType, ex); } catch (IllegalStateException ex) { throw new ConversionNotSupportedException(value, requiredType, ex); } catch (IllegalArgumentException ex) { throw new TypeMismatchException(value, requiredType, ex); } } private Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<?> requiredType, TypeDescriptor td) throws TypeMismatchException { try { return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td); } catch (ConverterNotFoundException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new ConversionNotSupportedException(pce, td.getType(), ex); } catch (ConversionException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, requiredType, ex); } catch (IllegalStateException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new ConversionNotSupportedException(pce, requiredType, ex); } catch (IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, requiredType, ex); } } /** * Convert the given value for the specified property to the latter's type. * <p>This method is only intended for optimizations in a BeanFactory. * Use the <code>convertIfNecessary</code> methods for programmatic conversion. * @param value the value to convert * @param propertyName the target property * (note that nested or indexed properties are not supported here) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ public Object convertForProperty(Object value, String propertyName) throws TypeMismatchException { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(propertyName); if (pd == null) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "No property '" + propertyName + "' found"); } return convertForProperty(propertyName, null, value, pd); } private Object convertForProperty(String propertyName, Object oldValue, Object newValue, PropertyDescriptor pd) throws TypeMismatchException { GenericTypeAwarePropertyDescriptor gpd = (GenericTypeAwarePropertyDescriptor) pd; Class<?> beanClass = gpd.getBeanClass(); return convertIfNecessary(propertyName, oldValue, newValue, pd.getPropertyType(), new TypeDescriptor(property(pd))); } //--------------------------------------------------------------------- // Implementation methods //--------------------------------------------------------------------- /** * Get the last component of the path. Also works if not nested. * @param bw BeanWrapper to work on * @param nestedPath property path we know is nested * @return last component of the path (the property on the target bean) */ private String getFinalPath(BeanWrapper bw, String nestedPath) { if (bw == this) { return nestedPath; } return nestedPath.substring(PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(nestedPath) + 1); } /** * Recursively navigate to return a BeanWrapper for the nested property path. * @param propertyPath property property path, which may be nested * @return a BeanWrapper for the target bean */ protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); // Handle nested properties recursively. if (pos > -1) { String nestedProperty = propertyPath.substring(0, pos); String nestedPath = propertyPath.substring(pos + 1); BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty); return nestedBw.getBeanWrapperForPropertyPath(nestedPath); } else { return this; } } /** * Retrieve a BeanWrapper for the given nested property. * Create a new one if not found in the cache. * <p>Note: Caching nested BeanWrappers is necessary now, * to keep registered custom editors for nested properties. * @param nestedProperty property to create the BeanWrapper for * @return the BeanWrapper instance, either cached or newly created */ private BeanWrapperImpl getNestedBeanWrapper(String nestedProperty) { if (this.nestedBeanWrappers == null) { this.nestedBeanWrappers = new HashMap<String, BeanWrapperImpl>(); } // Get value of bean property. PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty); String canonicalName = tokens.canonicalName; Object propertyValue = getPropertyValue(tokens); if (propertyValue == null) { if (this.autoGrowNestedPaths) { propertyValue = setDefaultValue(tokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + canonicalName); } } // Lookup cached sub-BeanWrapper, create new one if not found. BeanWrapperImpl nestedBw = this.nestedBeanWrappers.get(canonicalName); if (nestedBw == null || nestedBw.getWrappedInstance() != propertyValue) { if (logger.isTraceEnabled()) { logger.trace("Creating new nested BeanWrapper for property '" + canonicalName + "'"); } nestedBw = newNestedBeanWrapper(propertyValue, this.nestedPath + canonicalName + NESTED_PROPERTY_SEPARATOR); // Inherit all type-specific PropertyEditors. copyDefaultEditorsTo(nestedBw); copyCustomEditorsTo(nestedBw, canonicalName); this.nestedBeanWrappers.put(canonicalName, nestedBw); } else { if (logger.isTraceEnabled()) { logger.trace("Using cached nested BeanWrapper for property '" + canonicalName + "'"); } } return nestedBw; } private Object setDefaultValue(String propertyName) { PropertyTokenHolder tokens = new PropertyTokenHolder(); tokens.actualName = propertyName; tokens.canonicalName = propertyName; return setDefaultValue(tokens); } private Object setDefaultValue(PropertyTokenHolder tokens) { PropertyValue pv = createDefaultPropertyValue(tokens); setPropertyValue(tokens, pv); return getPropertyValue(tokens); } private PropertyValue createDefaultPropertyValue(PropertyTokenHolder tokens) { Class<?> type = getPropertyTypeDescriptor(tokens.canonicalName).getType(); if (type == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName, "Could not determine property type for auto-growing a default value"); } Object defaultValue = newValue(type, tokens.canonicalName); return new PropertyValue(tokens.canonicalName, defaultValue); } private Object newValue(Class<?> type, String name) { try { if (type.isArray()) { Class<?> componentType = type.getComponentType(); // TODO - only handles 2-dimensional arrays if (componentType.isArray()) { Object array = Array.newInstance(componentType, 1); Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0)); return array; } else { return Array.newInstance(componentType, 0); } } else if (Collection.class.isAssignableFrom(type)) { return CollectionFactory.createCollection(type, 16); } else if (Map.class.isAssignableFrom(type)) { return CollectionFactory.createMap(type, 16); } else { return type.newInstance(); } } catch (Exception ex) { // TODO Root cause exception context is lost here... should we throw another exception type that preserves context instead? throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name, "Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path: " + ex); } } /** * Create a new nested BeanWrapper instance. * <p>Default implementation creates a BeanWrapperImpl instance. * Can be overridden in subclasses to create a BeanWrapperImpl subclass. * @param object object wrapped by this BeanWrapper * @param nestedPath the nested path of the object * @return the nested BeanWrapper instance */ protected BeanWrapperImpl newNestedBeanWrapper(Object object, String nestedPath) { return new BeanWrapperImpl(object, nestedPath, this); } /** * Parse the given property name into the corresponding property name tokens. * @param propertyName the property name to parse * @return representation of the parsed property tokens */ private PropertyTokenHolder getPropertyNameTokens(String propertyName) { PropertyTokenHolder tokens = new PropertyTokenHolder(); String actualName = null; List<String> keys = new ArrayList<String>(2); int searchIndex = 0; while (searchIndex != -1) { int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex); searchIndex = -1; if (keyStart != -1) { int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length()); if (keyEnd != -1) { if (actualName == null) { actualName = propertyName.substring(0, keyStart); } String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd); if ((key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { key = key.substring(1, key.length() - 1); } keys.add(key); searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length(); } } } tokens.actualName = (actualName != null ? actualName : propertyName); tokens.canonicalName = tokens.actualName; if (!keys.isEmpty()) { tokens.canonicalName += PROPERTY_KEY_PREFIX + StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) + PROPERTY_KEY_SUFFIX; tokens.keys = StringUtils.toStringArray(keys); } return tokens; } //--------------------------------------------------------------------- // Implementation of PropertyAccessor interface //--------------------------------------------------------------------- @Override public Object getPropertyValue(String propertyName) throws BeansException { BeanWrapperImpl nestedBw = getBeanWrapperForPropertyPath(propertyName); PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); return nestedBw.getPropertyValue(tokens); } private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getReadMethod() == null) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); } final Method readMethod = pd.getReadMethod(); try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } Object value; if (System.getSecurityManager() != null) { try { value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return readMethod.invoke(object, (Object[]) null); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { value = readMethod.invoke(object, (Object[]) null); } if (tokens.keys != null) { if (value == null) { if (this.autoGrowNestedPaths) { value = setDefaultValue(tokens.actualName); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } String indexedPropertyName = tokens.actualName; // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName); value = Array.get(value, index); } else if (value instanceof List) { int index = Integer.parseInt(key); List list = (List) value; growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1); value = list.get(index); } else if (value instanceof Set) { // Apply index to Iterator in case of a Set. Set set = (Set) value; int index = Integer.parseInt(key); if (index < 0) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Set of size " + set.size() + ", accessed using property path '" + propertyName + "'"); } //zzy+ 解决set没有实例化,导致空指针异常的问题 Type[] types = GenericsUtils.getMethodGenericReturnType(readMethod); Class colletionCls = null; if(types != null){ colletionCls = (Class)types[0]; } value = colletionCls.newInstance(); set.add(value); // if(index >= set.size()){ // //zzy+ // Type[] types = GenericsUtils.getMethodGenericReturnType(readMethod); // Class colletionCls = null; // if(types != null){ // colletionCls = (Class)types[0]; // } // value = colletionCls.newInstance(); // set.add(value); // }else{ // Iterator it = set.iterator(); // for (int j = 0; it.hasNext(); j++) { // Object elem = it.next(); // if (j == index) { // value = elem; // break; // } // } // } } else if (value instanceof Map) { Map map = (Map) value; Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(), i + 1); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = mapKeyType != null ? TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Set nor a Map; returned value was [" + value + "]"); } indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX; } } return value; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } } private Object growArrayIfNecessary(Object array, int index, String name) { if (!this.autoGrowNestedPaths) { return array; } int length = Array.getLength(array); if (index >= length && index < this.autoGrowCollectionLimit) { Class<?> componentType = array.getClass().getComponentType(); Object newArray = Array.newInstance(componentType, index + 1); System.arraycopy(array, 0, newArray, 0, length); for (int i = length; i < Array.getLength(newArray); i++) { Array.set(newArray, i, newValue(componentType, name)); } // TODO this is not efficient because conversion may create a copy ... set directly because we know it is assignable. setPropertyValue(name, newArray); return getPropertyValue(name); } else { return array; } } @SuppressWarnings("unchecked") private void growCollectionIfNecessary( Collection collection, int index, String name, PropertyDescriptor pd, int nestingLevel) { if (!this.autoGrowNestedPaths) { return; } int size = collection.size(); if (index >= size && index < this.autoGrowCollectionLimit) { Class elementType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(), nestingLevel); if (elementType != null) { for (int i = collection.size(); i < index + 1; i++) { collection.add(newValue(elementType, name)); } } } } @Override public void setPropertyValue(String propertyName, Object value) throws BeansException { BeanWrapperImpl nestedBw; try { nestedBw = getBeanWrapperForPropertyPath(propertyName); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Nested property in path '" + propertyName + "' does not exist", ex); } PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); nestedBw.setPropertyValue(tokens, new PropertyValue(propertyName, value)); } @Override public void setPropertyValue(PropertyValue pv) throws BeansException { PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens; if (tokens == null) { String propertyName = pv.getName(); BeanWrapperImpl nestedBw; try { nestedBw = getBeanWrapperForPropertyPath(propertyName); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Nested property in path '" + propertyName + "' does not exist", ex); } tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName)); if (nestedBw == this) { pv.getOriginalPropertyValue().resolvedTokens = tokens; } nestedBw.setPropertyValue(tokens, pv); } else { setPropertyValue(tokens, pv); } } @SuppressWarnings("unchecked") private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; if (tokens.keys != null) { // Apply indexes and map keys: fetch value for all keys but the last one. PropertyTokenHolder getterTokens = new PropertyTokenHolder(); getterTokens.canonicalName = tokens.canonicalName; getterTokens.actualName = tokens.actualName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue; try { propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "'", ex); } // Set value for last key. String key = tokens.keys[tokens.keys.length - 1]; if (propValue == null) { // null map value case if (this.autoGrowNestedPaths) { // TODO: cleanup, this is pretty hacky int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex); propValue = setDefaultValue(getterTokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value in property referenced " + "in indexed property path '" + propertyName + "': returned null"); } } if (propValue.getClass().isArray()) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class requiredType = propValue.getClass().getComponentType(); int arrayIndex = Integer.parseInt(key); Object oldValue = null; try { if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid array index in property path '" + propertyName + "'", ex); } } else if (propValue instanceof List) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType( pd.getReadMethod(), tokens.keys.length); List list = (List) propValue; int index = Integer.parseInt(key); int size = list.size(); Object oldValue = null; if (isExtractOldValueForEditor() && index < size) { oldValue = list.get(index); } Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length)); if (index >= size && index < this.autoGrowCollectionLimit) { for (int i = size; i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot set element with index " + index + " in List of size " + size + ", accessed using property path '" + propertyName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } else { try { list.set(index, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid list index in property path '" + propertyName + "'", ex); } } } else if (propValue instanceof Map) { PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType( pd.getReadMethod(), tokens.keys.length); Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType( pd.getReadMethod(), tokens.keys.length); Map map = (Map) propValue; // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = mapKeyType != null ? TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } // Pass full property name and old value in here, since we want full // conversion ability for map values. Object convertedMapValue = convertIfNecessary( propertyName, oldValue, pv.getValue(), mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length)); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]"); } } else { PropertyDescriptor pd = pv.resolvedDescriptor; if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) { pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); if (pd == null || pd.getWriteMethod() == null) { if (pv.isOptional()) { logger.debug("Ignoring optional value for property '" + actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); return; } else { PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass()); throw new NotWritablePropertyException( getRootClass(), this.nestedPath + propertyName, matches.buildErrorMessage(), matches.getPossibleMatches()); } } pv.getOriginalPropertyValue().resolvedDescriptor = pd; } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.conversionNecessary)) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && pd.getReadMethod() != null) { final Method readMethod = pd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) && !readMethod.isAccessible()) { if (System.getSecurityManager()!= null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { readMethod.setAccessible(true); return null; } }); } else { readMethod.setAccessible(true); } } try { if (System.getSecurityManager() != null) { oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { return readMethod.invoke(object); } }, acc); } else { oldValue = readMethod.invoke(object); } } catch (Exception ex) { if (ex instanceof PrivilegedActionException) { ex = ((PrivilegedActionException) ex).getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + propertyName + "'", ex); } } } valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd); } pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue); } final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() : pd.getWriteMethod()); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) { if (System.getSecurityManager()!= null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { writeMethod.setAccessible(true); return null; } }); } else { writeMethod.setAccessible(true); } } final Object value = valueToApply; if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { public Object run() throws Exception { writeMethod.invoke(object, value); return null; } }, acc); } catch (PrivilegedActionException ex) { throw ex.getException(); } } else { writeMethod.invoke(this.object, value); } } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException()); } else { throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException()); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getName()); if (this.object != null) { sb.append(": wrapping object [").append(ObjectUtils.identityToString(this.object)).append("]"); } else { sb.append(": no wrapped object set"); } return sb.toString(); } //--------------------------------------------------------------------- // Inner class for internal use //--------------------------------------------------------------------- private static class PropertyTokenHolder { public String canonicalName; public String actualName; public String[] keys; } private Property property(PropertyDescriptor pd) { GenericTypeAwarePropertyDescriptor typeAware = (GenericTypeAwarePropertyDescriptor) pd; return new Property(typeAware.getBeanClass(), typeAware.getReadMethod(), typeAware.getWriteMethod()); } }
zzyapps
trunk/JqFw/core/org/springframework/beans/BeanWrapperImpl.java
Java
asf20
46,814
/* * Copyright 2002-2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.bind.annotation.support; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.BridgeMethodResolver; import org.springframework.core.Conventions; import org.springframework.core.GenericTypeResolver; import org.springframework.core.MethodParameter; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.ReflectionUtils; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ValueConstants; import org.springframework.web.bind.support.DefaultSessionAttributeStore; import org.springframework.web.bind.support.SessionAttributeStore; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.bind.support.SimpleSessionStatus; import org.springframework.web.bind.support.WebArgumentResolver; import org.springframework.web.bind.support.WebBindingInitializer; import org.springframework.web.bind.support.WebRequestDataBinder; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartRequest; /** * Support class for invoking an annotated handler method. Operates on the introspection results of a {@link * HandlerMethodResolver} for a specific handler type. * * <p>Used by {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter} and {@link * org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter}. * * @author Juergen Hoeller * @author Arjen Poutsma * @since 2.5.2 * @see #invokeHandlerMethod */ public class HandlerMethodInvoker { private static final String MODEL_KEY_PREFIX_STALE = SessionAttributeStore.class.getName() + ".STALE."; /** We'll create a lot of these objects, so we don't want a new logger every time. */ private static final Log logger = LogFactory.getLog(HandlerMethodInvoker.class); private final HandlerMethodResolver methodResolver; private final WebBindingInitializer bindingInitializer; private final SessionAttributeStore sessionAttributeStore; private final ParameterNameDiscoverer parameterNameDiscoverer; private final WebArgumentResolver[] customArgumentResolvers; private final HttpMessageConverter[] messageConverters; private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus(); public HandlerMethodInvoker(HandlerMethodResolver methodResolver) { this(methodResolver, null); } public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer) { this(methodResolver, bindingInitializer, new DefaultSessionAttributeStore(), null, null, null); } public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer, SessionAttributeStore sessionAttributeStore, ParameterNameDiscoverer parameterNameDiscoverer, WebArgumentResolver[] customArgumentResolvers, HttpMessageConverter[] messageConverters) { this.methodResolver = methodResolver; this.bindingInitializer = bindingInitializer; this.sessionAttributeStore = sessionAttributeStore; this.parameterNameDiscoverer = parameterNameDiscoverer; this.customArgumentResolvers = customArgumentResolvers; this.messageConverters = messageConverters; } public final Object invokeHandlerMethod(Method handlerMethod, Object handler, NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); try { boolean debug = logger.isDebugEnabled(); for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName); if (attrValue != null) { implicitModel.addAttribute(attrName, attrValue); } } for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); } String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value(); if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { continue; } ReflectionUtils.makeAccessible(attributeMethodToInvoke); Object attrValue = attributeMethodToInvoke.invoke(handler, args); if ("".equals(attrName)) { Class resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType, attrValue); } if (!implicitModel.containsAttribute(attrName)) { implicitModel.addAttribute(attrName, attrValue); } } Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel); if (debug) { logger.debug("Invoking request handler method: " + handlerMethodToInvoke); } ReflectionUtils.makeAccessible(handlerMethodToInvoke); return handlerMethodToInvoke.invoke(handler, args); } catch (IllegalStateException ex) { // Internal assertion failed (e.g. invalid signature): // throw exception with full handler method context... throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex); } catch (InvocationTargetException ex) { // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception... ReflectionUtils.rethrowException(ex.getTargetException()); return null; } } public final void updateModelAttributes(Object handler, Map<String, Object> mavModel, ExtendedModelMap implicitModel, NativeWebRequest webRequest) throws Exception { if (this.methodResolver.hasSessionAttributes() && this.sessionStatus.isComplete()) { for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { this.sessionAttributeStore.cleanupAttribute(webRequest, attrName); } } // Expose model attributes as session attributes, if required. // Expose BindingResults for all attributes, making custom editors available. Map<String, Object> model = (mavModel != null ? mavModel : implicitModel); if (model != null) { try { String[] originalAttrNames = model.keySet().toArray(new String[model.size()]); for (String attrName : originalAttrNames) { Object attrValue = model.get(attrName); boolean isSessionAttr = this.methodResolver.isSessionAttribute( attrName, (attrValue != null ? attrValue.getClass() : null)); if (isSessionAttr) { if (this.sessionStatus.isComplete()) { implicitModel.put(MODEL_KEY_PREFIX_STALE + attrName, Boolean.TRUE); } else if (!implicitModel.containsKey(MODEL_KEY_PREFIX_STALE + attrName)) { this.sessionAttributeStore.storeAttribute(webRequest, attrName, attrValue); } } if (!attrName.startsWith(BindingResult.MODEL_KEY_PREFIX) && (isSessionAttr || isBindingCandidate(attrValue))) { String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attrName; if (mavModel != null && !model.containsKey(bindingResultKey)) { WebDataBinder binder = createBinder(webRequest, attrValue, attrName); initBinder(handler, attrName, binder, webRequest); mavModel.put(bindingResultKey, binder.getBindingResult()); } } } } catch (InvocationTargetException ex) { // User-defined @InitBinder method threw an exception... ReflectionUtils.rethrowException(ex.getTargetException()); } } } private Object[] resolveHandlerArguments(Method handlerMethod, Object handler, NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Class[] paramTypes = handlerMethod.getParameterTypes(); Object[] args = new Object[paramTypes.length]; for (int i = 0; i < args.length; i++) { MethodParameter methodParam = new MethodParameter(handlerMethod, i); methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(methodParam, handler.getClass()); String paramName = null; String headerName = null; boolean requestBodyFound = false; String cookieName = null; String pathVarName = null; String attrName = null; boolean required = false; String defaultValue = null; boolean validate = false; int annotationsFound = 0; Annotation[] paramAnns = methodParam.getParameterAnnotations(); for (Annotation paramAnn : paramAnns) { if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; paramName = requestParam.value(); required = requestParam.required(); defaultValue = parseDefaultValueAttribute(requestParam.defaultValue()); annotationsFound++; } else if (RequestHeader.class.isInstance(paramAnn)) { RequestHeader requestHeader = (RequestHeader) paramAnn; headerName = requestHeader.value(); required = requestHeader.required(); defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue()); annotationsFound++; } else if (RequestBody.class.isInstance(paramAnn)) { requestBodyFound = true; annotationsFound++; } else if (CookieValue.class.isInstance(paramAnn)) { CookieValue cookieValue = (CookieValue) paramAnn; cookieName = cookieValue.value(); required = cookieValue.required(); defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue()); annotationsFound++; } else if (PathVariable.class.isInstance(paramAnn)) { PathVariable pathVar = (PathVariable) paramAnn; pathVarName = pathVar.value(); annotationsFound++; } else if (ModelAttribute.class.isInstance(paramAnn)) { ModelAttribute attr = (ModelAttribute) paramAnn; attrName = attr.value(); annotationsFound++; } else if (Value.class.isInstance(paramAnn)) { defaultValue = ((Value) paramAnn).value(); } else if ("Valid".equals(paramAnn.annotationType().getSimpleName())) { validate = true; } } if (annotationsFound > 1) { throw new IllegalStateException("Handler parameter annotations are exclusive choices - " + "do not specify more than one such annotation on the same parameter: " + handlerMethod); } if (annotationsFound == 0) { Object argValue = resolveCommonArgument(methodParam, webRequest); if (argValue != WebArgumentResolver.UNRESOLVED) { args[i] = argValue; } else if (defaultValue != null) { args[i] = resolveDefaultValue(defaultValue); } else { Class paramType = methodParam.getParameterType(); if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) { args[i] = implicitModel; } else if (SessionStatus.class.isAssignableFrom(paramType)) { args[i] = this.sessionStatus; } else if (HttpEntity.class.isAssignableFrom(paramType)) { args[i] = resolveHttpEntityRequest(methodParam, webRequest); } else if (Errors.class.isAssignableFrom(paramType)) { throw new IllegalStateException("Errors/BindingResult argument declared " + "without preceding model attribute. Check your handler method signature!"); } else if (BeanUtils.isSimpleProperty(paramType)) { paramName = ""; } else { attrName = ""; } } } if (paramName != null) { args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler); } else if (headerName != null) { args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler); } else if (requestBodyFound) { args[i] = resolveRequestBody(methodParam, webRequest, handler); } else if (cookieName != null) { args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler); } else if (pathVarName != null) { args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler); } else if (attrName != null) { WebDataBinder binder = resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler); boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1])); if (binder.getTarget() != null) { doBind(binder, webRequest, validate, !assignBindingResult); } args[i] = binder.getTarget(); if (assignBindingResult) { args[i + 1] = binder.getBindingResult(); i++; } implicitModel.putAll(binder.getBindingResult().getModel()); } } return args; } protected void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest) throws Exception { if (this.bindingInitializer != null) { this.bindingInitializer.initBinder(binder, webRequest); } if (handler != null) { Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods(); if (!initBinderMethods.isEmpty()) { boolean debug = logger.isDebugEnabled(); for (Method initBinderMethod : initBinderMethods) { Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod); String[] targetNames = AnnotationUtils.findAnnotation(initBinderMethod, InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder, webRequest); if (debug) { logger.debug("Invoking init-binder method: " + methodToInvoke); } ReflectionUtils.makeAccessible(methodToInvoke); Object returnValue = methodToInvoke.invoke(handler, initBinderArgs); if (returnValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + methodToInvoke); } } } } } } private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod, WebDataBinder binder, NativeWebRequest webRequest) throws Exception { Class[] initBinderParams = initBinderMethod.getParameterTypes(); Object[] initBinderArgs = new Object[initBinderParams.length]; for (int i = 0; i < initBinderArgs.length; i++) { MethodParameter methodParam = new MethodParameter(initBinderMethod, i); methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(methodParam, handler.getClass()); String paramName = null; boolean paramRequired = false; String paramDefaultValue = null; String pathVarName = null; Annotation[] paramAnns = methodParam.getParameterAnnotations(); for (Annotation paramAnn : paramAnns) { if (RequestParam.class.isInstance(paramAnn)) { RequestParam requestParam = (RequestParam) paramAnn; paramName = requestParam.value(); paramRequired = requestParam.required(); paramDefaultValue = parseDefaultValueAttribute(requestParam.defaultValue()); break; } else if (ModelAttribute.class.isInstance(paramAnn)) { throw new IllegalStateException( "@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod); } else if (PathVariable.class.isInstance(paramAnn)) { PathVariable pathVar = (PathVariable) paramAnn; pathVarName = pathVar.value(); } } if (paramName == null && pathVarName == null) { Object argValue = resolveCommonArgument(methodParam, webRequest); if (argValue != WebArgumentResolver.UNRESOLVED) { initBinderArgs[i] = argValue; } else { Class paramType = initBinderParams[i]; if (paramType.isInstance(binder)) { initBinderArgs[i] = binder; } else if (BeanUtils.isSimpleProperty(paramType)) { paramName = ""; } else { throw new IllegalStateException("Unsupported argument [" + paramType.getName() + "] for @InitBinder method: " + initBinderMethod); } } } if (paramName != null) { initBinderArgs[i] = resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null); } else if (pathVarName != null) { initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null); } } return initBinderArgs; } @SuppressWarnings("unchecked") private Object resolveRequestParam(String paramName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (Map.class.isAssignableFrom(paramType) && paramName.length() == 0) { return resolveRequestParamMap((Class<? extends Map>) paramType, webRequest); } if (paramName.length() == 0) { paramName = getRequiredParameterName(methodParam); } Object paramValue = null; MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class); if (multipartRequest != null) { List<MultipartFile> files = multipartRequest.getFiles(paramName); if (!files.isEmpty()) { paramValue = (files.size() == 1 ? files.get(0) : files); } } if (paramValue == null) { String[] paramValues = webRequest.getParameterValues(paramName); if (paramValues != null) { paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues); } } if (paramValue == null) { if (defaultValue != null) { paramValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingParameterException(paramName, paramType); } paramValue = checkValue(paramName, paramValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, paramName); initBinder(handlerForInitBinderCall, paramName, binder, webRequest); return binder.convertIfNecessary(paramValue, paramType, methodParam); } private Map resolveRequestParamMap(Class<? extends Map> mapType, NativeWebRequest webRequest) { Map<String, String[]> parameterMap = webRequest.getParameterMap(); if (MultiValueMap.class.isAssignableFrom(mapType)) { MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(parameterMap.size()); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { for (String value : entry.getValue()) { result.add(entry.getKey(), value); } } return result; } else { Map<String, String> result = new LinkedHashMap<String, String>(parameterMap.size()); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { if (entry.getValue().length > 0) { result.put(entry.getKey(), entry.getValue()[0]); } } return result; } } @SuppressWarnings("unchecked") private Object resolveRequestHeader(String headerName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (Map.class.isAssignableFrom(paramType)) { return resolveRequestHeaderMap((Class<? extends Map>) paramType, webRequest); } if (headerName.length() == 0) { headerName = getRequiredParameterName(methodParam); } Object headerValue = null; String[] headerValues = webRequest.getHeaderValues(headerName); if (headerValues != null) { headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues); } if (headerValue == null) { if (defaultValue != null) { headerValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingHeaderException(headerName, paramType); } headerValue = checkValue(headerName, headerValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, headerName); initBinder(handlerForInitBinderCall, headerName, binder, webRequest); return binder.convertIfNecessary(headerValue, paramType, methodParam); } private Map resolveRequestHeaderMap(Class<? extends Map> mapType, NativeWebRequest webRequest) { if (MultiValueMap.class.isAssignableFrom(mapType)) { MultiValueMap<String, String> result; if (HttpHeaders.class.isAssignableFrom(mapType)) { result = new HttpHeaders(); } else { result = new LinkedMultiValueMap<String, String>(); } for (Iterator<String> iterator = webRequest.getHeaderNames(); iterator.hasNext();) { String headerName = iterator.next(); for (String headerValue : webRequest.getHeaderValues(headerName)) { result.add(headerName, headerValue); } } return result; } else { Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<String> iterator = webRequest.getHeaderNames(); iterator.hasNext();) { String headerName = iterator.next(); String headerValue = webRequest.getHeader(headerName); result.put(headerName, headerValue); } return result; } } /** * Resolves the given {@link RequestBody @RequestBody} annotation. */ protected Object resolveRequestBody(MethodParameter methodParam, NativeWebRequest webRequest, Object handler) throws Exception { return readWithMessageConverters(methodParam, createHttpInputMessage(webRequest), methodParam.getParameterType()); } private HttpEntity resolveHttpEntityRequest(MethodParameter methodParam, NativeWebRequest webRequest) throws Exception { HttpInputMessage inputMessage = createHttpInputMessage(webRequest); Class<?> paramType = getHttpEntityType(methodParam); Object body = readWithMessageConverters(methodParam, inputMessage, paramType); return new HttpEntity<Object>(body, inputMessage.getHeaders()); } private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType) throws Exception { MediaType contentType = inputMessage.getHeaders().getContentType(); if (contentType == null) { StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); String paramName = methodParam.getParameterName(); if (paramName != null) { builder.append(' '); builder.append(paramName); } throw new HttpMediaTypeNotSupportedException( "Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); } List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>(); if (this.messageConverters != null) { for (HttpMessageConverter<?> messageConverter : this.messageConverters) { allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); if (messageConverter.canRead(paramType, contentType)) { if (logger.isDebugEnabled()) { logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType +"\" using [" + messageConverter + "]"); } return messageConverter.read(paramType, inputMessage); } } } throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); } private Class<?> getHttpEntityType(MethodParameter methodParam) { Assert.isAssignable(HttpEntity.class, methodParam.getParameterType()); ParameterizedType type = (ParameterizedType) methodParam.getGenericParameterType(); if (type.getActualTypeArguments().length == 1) { Type typeArgument = type.getActualTypeArguments()[0]; if (typeArgument instanceof Class) { return (Class<?>) typeArgument; } else if (typeArgument instanceof GenericArrayType) { Type componentType = ((GenericArrayType) typeArgument).getGenericComponentType(); if (componentType instanceof Class) { // Surely, there should be a nicer way to do this Object array = Array.newInstance((Class<?>) componentType, 0); return array.getClass(); } } } throw new IllegalArgumentException( "HttpEntity parameter (" + methodParam.getParameterName() + ") is not parameterized"); } private Object resolveCookieValue(String cookieName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (cookieName.length() == 0) { cookieName = getRequiredParameterName(methodParam); } Object cookieValue = resolveCookieValue(cookieName, paramType, webRequest); if (cookieValue == null) { if (defaultValue != null) { cookieValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingCookieException(cookieName, paramType); } cookieValue = checkValue(cookieName, cookieValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, cookieName); initBinder(handlerForInitBinderCall, cookieName, binder, webRequest); return binder.convertIfNecessary(cookieValue, paramType, methodParam); } /** * Resolves the given {@link CookieValue @CookieValue} annotation. * <p>Throws an UnsupportedOperationException by default. */ protected Object resolveCookieValue(String cookieName, Class paramType, NativeWebRequest webRequest) throws Exception { throw new UnsupportedOperationException("@CookieValue not supported"); } private Object resolvePathVariable(String pathVarName, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (pathVarName.length() == 0) { pathVarName = getRequiredParameterName(methodParam); } String pathVarValue = resolvePathVariable(pathVarName, paramType, webRequest); WebDataBinder binder = createBinder(webRequest, null, pathVarName); initBinder(handlerForInitBinderCall, pathVarName, binder, webRequest); return binder.convertIfNecessary(pathVarValue, paramType, methodParam); } /** * Resolves the given {@link PathVariable @PathVariable} annotation. * <p>Throws an UnsupportedOperationException by default. */ protected String resolvePathVariable(String pathVarName, Class paramType, NativeWebRequest webRequest) throws Exception { throw new UnsupportedOperationException("@PathVariable not supported"); } private String getRequiredParameterName(MethodParameter methodParam) { String name = methodParam.getParameterName(); if (name == null) { throw new IllegalStateException( "No parameter name specified for argument of type [" + methodParam.getParameterType().getName() + "], and no parameter name information found in class file either."); } return name; } private Object checkValue(String name, Object value, Class paramType) { if (value == null) { if (boolean.class.equals(paramType)) { return Boolean.FALSE; } else if (paramType.isPrimitive()) { throw new IllegalStateException("Optional " + paramType + " parameter '" + name + "' is not present but cannot be translated into a null value due to being declared as a " + "primitive type. Consider declaring it as object wrapper for the corresponding primitive type."); } } return value; } private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { // Bind request parameter onto object... String name = attrName; if ("".equals(name)) { name = Conventions.getVariableNameForParameter(methodParam); } Class<?> paramType = methodParam.getParameterType(); Object bindObject; if (implicitModel.containsKey(name)) { bindObject = implicitModel.get(name); } else if (this.methodResolver.isSessionAttribute(name, paramType)) { bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); if (bindObject == null) { raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); } } else { bindObject = BeanUtils.instantiateClass(paramType); } WebDataBinder binder = createBinder(webRequest, bindObject, name); initBinder(handler, name, binder, webRequest); return binder; } /** * Determine whether the given value qualifies as a "binding candidate", i.e. might potentially be subject to * bean-style data binding later on. */ protected boolean isBindingCandidate(Object value) { return (value != null && !value.getClass().isArray() && !(value instanceof Collection) && !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass())); } protected void raiseMissingParameterException(String paramName, Class paramType) throws Exception { throw new IllegalStateException("Missing parameter '" + paramName + "' of type [" + paramType.getName() + "]"); } protected void raiseMissingHeaderException(String headerName, Class paramType) throws Exception { throw new IllegalStateException("Missing header '" + headerName + "' of type [" + paramType.getName() + "]"); } protected void raiseMissingCookieException(String cookieName, Class paramType) throws Exception { throw new IllegalStateException( "Missing cookie value '" + cookieName + "' of type [" + paramType.getName() + "]"); } protected void raiseSessionRequiredException(String message) throws Exception { throw new IllegalStateException(message); } protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { return new WebRequestDataBinder(target, objectName); } private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate, boolean failOnErrors) throws Exception { doBind(binder, webRequest); if (validate) { binder.validate(); } // zzy+ 把异常改为日志提示 if (failOnErrors && binder.getBindingResult().hasErrors()) { // throw new BindException(binder.getBindingResult()); logger.info("JSON转换时有异常:" + binder.getBindingResult().toString()); } } protected void doBind(WebDataBinder binder, NativeWebRequest webRequest) throws Exception { ((WebRequestDataBinder) binder).bind(webRequest); } /** * Return a {@link HttpInputMessage} for the given {@link NativeWebRequest}. * <p>Throws an UnsupportedOperation1Exception by default. */ protected HttpInputMessage createHttpInputMessage(NativeWebRequest webRequest) throws Exception { throw new UnsupportedOperationException("@RequestBody not supported"); } /** * Return a {@link HttpOutputMessage} for the given {@link NativeWebRequest}. * <p>Throws an UnsupportedOperationException by default. */ protected HttpOutputMessage createHttpOutputMessage(NativeWebRequest webRequest) throws Exception { throw new UnsupportedOperationException("@Body not supported"); } protected String parseDefaultValueAttribute(String value) { return (ValueConstants.DEFAULT_NONE.equals(value) ? null : value); } protected Object resolveDefaultValue(String value) { return value; } protected Object resolveCommonArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { // Invoke custom argument resolvers if present... if (this.customArgumentResolvers != null) { for (WebArgumentResolver argumentResolver : this.customArgumentResolvers) { Object value = argumentResolver.resolveArgument(methodParameter, webRequest); if (value != WebArgumentResolver.UNRESOLVED) { return value; } } } // Resolution of standard parameter types... Class paramType = methodParameter.getParameterType(); Object value = resolveStandardArgument(paramType, webRequest); if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) { throw new IllegalStateException("Standard argument type [" + paramType.getName() + "] resolved to incompatible value of type [" + (value != null ? value.getClass() : null) + "]. Consider declaring the argument type in a less specific fashion."); } return value; } protected Object resolveStandardArgument(Class<?> parameterType, NativeWebRequest webRequest) throws Exception { if (WebRequest.class.isAssignableFrom(parameterType)) { return webRequest; } return WebArgumentResolver.UNRESOLVED; } protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel) { ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class); String attrName = (attr != null ? attr.value() : ""); if ("".equals(attrName)) { Class resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType); attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue); } implicitModel.addAttribute(attrName, returnValue); } }
zzyapps
trunk/JqFw/core/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java
Java
asf20
36,261
package org.codehaus.jackson.map.deser; import java.io.IOException; import java.lang.reflect.*; import java.util.*; import org.codehaus.jackson.*; import org.codehaus.jackson.annotate.JsonTypeInfo; import org.codehaus.jackson.map.*; import org.codehaus.jackson.map.annotate.JsonCachable; import org.codehaus.jackson.map.deser.impl.*; import org.codehaus.jackson.map.deser.std.ContainerDeserializerBase; import org.codehaus.jackson.map.deser.std.StdDeserializer; import org.codehaus.jackson.map.introspect.AnnotatedClass; import org.codehaus.jackson.map.introspect.AnnotatedMember; import org.codehaus.jackson.map.introspect.AnnotatedWithParams; import org.codehaus.jackson.map.type.ClassKey; import org.codehaus.jackson.map.util.ClassUtil; import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.util.TokenBuffer; /** * Deserializer class that can deserialize instances of * arbitrary bean objects, usually from JSON Object structs, * but possibly also from simple types like String values. */ @JsonCachable /* Because of costs associated with constructing bean deserializers, * they usually should be cached unlike other deserializer types. * But more importantly, it is important to be able to cache * bean serializers to handle cyclic references. */ public class BeanDeserializer extends StdDeserializer<Object> implements ResolvableDeserializer { /* /********************************************************** /* Information regarding type being deserialized /********************************************************** */ /** * Class for which deserializer is built; used for accessing * annotations during resolution phase (see {@link #resolve}). */ final protected AnnotatedClass _forClass; /** * Declared type of the bean this deserializer handles. */ final protected JavaType _beanType; /** * Property that contains value to be deserialized using * deserializer; mostly needed to find contextual annotations * for subtypes. * * @since 1.7 */ final protected BeanProperty _property; /* /********************************************************** /* Construction configuration /********************************************************** */ /** * Object that handles details of constructing initial * bean value (to which bind data to), unless instance * is passed (via updateValue()) */ protected final ValueInstantiator _valueInstantiator; /** * Deserializer that is used iff delegate-based creator is * to be used for deserializing from JSON Object. */ protected JsonDeserializer<Object> _delegateDeserializer; /** * If the bean needs to be instantiated using constructor * or factory method * that takes one or more named properties as argument(s), * this creator is used for instantiation. */ protected final PropertyBasedCreator _propertyBasedCreator; /** * Flag that is set to mark "non-standard" cases; where either * we use one of non-default creators, or there are unwrapped * values to consider. */ protected boolean _nonStandardCreation; /* /********************************************************** /* Property information, setters /********************************************************** */ /** * Mapping of property names to properties, built when all properties * to use have been successfully resolved. * * @since 1.7 */ final protected BeanPropertyMap _beanProperties; /** * List of {@link ValueInjector}s, if any injectable values are * expected by the bean; otherwise null. * This includes injectors used for injecting values via setters * and fields, but not ones passed through constructor parameters. * * @since 1.9 */ final protected ValueInjector[] _injectables; /** * Fallback setter used for handling any properties that are not * mapped to regular setters. If setter is not null, it will be * called once for each such property. */ protected SettableAnyProperty _anySetter; /** * In addition to properties that are set, we will also keep * track of recognized but ignorable properties: these will * be skipped without errors or warnings. */ final protected HashSet<String> _ignorableProps; /** * Flag that can be set to ignore and skip unknown properties. * If set, will not throw an exception for unknown properties. */ final protected boolean _ignoreAllUnknown; /** * We may also have one or more back reference fields (usually * zero or one). */ final protected Map<String, SettableBeanProperty> _backRefs; /* /********************************************************** /* Related handlers /********************************************************** */ /** * Lazily constructed map used to contain deserializers needed * for polymorphic subtypes. */ protected HashMap<ClassKey, JsonDeserializer<Object>> _subDeserializers; /** * If one of properties has "unwrapped" value, we need separate * helper object * * @since 1.9 */ protected UnwrappedPropertyHandler _unwrappedPropertyHandler; /** * Handler that we need iff any of properties uses external * type id. */ protected ExternalTypeHandler _externalTypeIdHandler; /* /********************************************************** /* Life-cycle, construction, initialization /********************************************************** */ /** * @deprecated (since 1.9) Use the constructor that takes {@link ValueInstantiator} instead */ @Deprecated public BeanDeserializer(AnnotatedClass forClass, JavaType type, BeanProperty property, CreatorCollector creators, BeanPropertyMap properties, Map<String, SettableBeanProperty> backRefs, HashSet<String> ignorableProps, boolean ignoreAllUnknown, SettableAnyProperty anySetter) { this(forClass, type, property, creators.constructValueInstantiator(null), properties, backRefs, ignorableProps, ignoreAllUnknown, anySetter, null); } /** * @since 1.9 */ public BeanDeserializer(BeanDescription beanDesc, BeanProperty property, ValueInstantiator valueInstantiator, BeanPropertyMap properties, Map<String, SettableBeanProperty> backRefs, HashSet<String> ignorableProps, boolean ignoreAllUnknown, SettableAnyProperty anySetter, List<ValueInjector> injectables) { this(beanDesc.getClassInfo(), beanDesc.getType(), property, valueInstantiator, properties, backRefs, ignorableProps, ignoreAllUnknown, anySetter, injectables); } /** * @since 1.9 */ protected BeanDeserializer(AnnotatedClass forClass, JavaType type, BeanProperty property, ValueInstantiator valueInstantiator, BeanPropertyMap properties, Map<String, SettableBeanProperty> backRefs, HashSet<String> ignorableProps, boolean ignoreAllUnknown, SettableAnyProperty anySetter, List<ValueInjector> injectables) { super(type); _forClass = forClass; _beanType = type; _property = property; _valueInstantiator = valueInstantiator; if (valueInstantiator.canCreateFromObjectWith()) { _propertyBasedCreator = new PropertyBasedCreator(valueInstantiator); } else { _propertyBasedCreator = null; } _beanProperties = properties; _backRefs = backRefs; _ignorableProps = ignorableProps; _ignoreAllUnknown = true;//zzy+ ignoreAllUnknown; _anySetter = anySetter; _injectables = (injectables == null || injectables.isEmpty()) ? null : injectables.toArray(new ValueInjector[injectables.size()]); _nonStandardCreation = valueInstantiator.canCreateUsingDelegate() || (_propertyBasedCreator != null) || !valueInstantiator.canCreateUsingDefault() || (_unwrappedPropertyHandler != null); } /** * Copy-constructor that can be used by sub-classes to allow * copy-on-write styling copying of settings of an existing instance. * * @since 1.7 */ protected BeanDeserializer(BeanDeserializer src) { this(src, true/*src._ignoreAllUnknown*/); } /** * @since 1.9 */ protected BeanDeserializer(BeanDeserializer src, boolean ignoreAllUnknown) { super(src._beanType); _forClass = src._forClass; _beanType = src._beanType; _property = src._property; _valueInstantiator = src._valueInstantiator; _delegateDeserializer = src._delegateDeserializer; _propertyBasedCreator = src._propertyBasedCreator; _beanProperties = src._beanProperties; _backRefs = src._backRefs; _ignorableProps = src._ignorableProps; _ignoreAllUnknown = true;//zzy+ ignoreAllUnknown; _anySetter = src._anySetter; _injectables = src._injectables; _nonStandardCreation = src._nonStandardCreation; _unwrappedPropertyHandler = src._unwrappedPropertyHandler; } @Override public JsonDeserializer<Object> unwrappingDeserializer() { /* bit kludgy but we don't want to accidentally change type; * sub-classes MUST override this method to support unwrapped * properties... */ if (getClass() != BeanDeserializer.class) { return this; } /* main thing really is to just enforce ignoring of unknown * properties; since there may be multiple unwrapped values * and properties for all may be interleaved... */ return new BeanDeserializer(this, true); } /* /********************************************************** /* Public accessors /********************************************************** */ public boolean hasProperty(String propertyName) { return _beanProperties.find(propertyName) != null; } /** * Accessor for checking number of deserialized properties. * * @since 1.7 */ public int getPropertyCount() { return _beanProperties.size(); } public final Class<?> getBeanClass() { return _beanType.getRawClass(); } @Override public JavaType getValueType() { return _beanType; } /** * * @since 1.6 */ public Iterator<SettableBeanProperty> properties() { if (_beanProperties == null) { // since 1.7 throw new IllegalStateException("Can only call before BeanDeserializer has been resolved"); } return _beanProperties.allProperties(); } /** * Method needed by {@link BeanDeserializerFactory} to properly link * managed- and back-reference pairs. */ public SettableBeanProperty findBackReference(String logicalName) { if (_backRefs == null) { return null; } return _backRefs.get(logicalName); } /** * @since 1.9 */ public ValueInstantiator getValueInstantiator() { return _valueInstantiator; } /* /********************************************************** /* Validation, post-processing /********************************************************** */ /** * Method called to finalize setup of this deserializer, * after deserializer itself has been registered. * This is needed to handle recursive and transitive dependencies. */ @Override public void resolve(DeserializationConfig config, DeserializerProvider provider) throws JsonMappingException { Iterator<SettableBeanProperty> it = _beanProperties.allProperties(); UnwrappedPropertyHandler unwrapped = null; ExternalTypeHandler.Builder extTypes = null; while (it.hasNext()) { SettableBeanProperty origProp = it.next(); SettableBeanProperty prop = origProp; // May already have deserializer from annotations, if so, skip: if (!prop.hasValueDeserializer()) { prop = prop.withValueDeserializer(findDeserializer(config, provider, prop.getType(), prop)); } // [JACKSON-235]: need to link managed references with matching back references prop = _resolveManagedReferenceProperty(config, prop); // [JACKSON-132]: support unwrapped values (via @JsonUnwrapped) SettableBeanProperty u = _resolveUnwrappedProperty(config, prop); if (u != null) { prop = u; if (unwrapped == null) { unwrapped = new UnwrappedPropertyHandler(); } unwrapped.addProperty(prop); } // [JACKSON-594]: non-static inner classes too: prop = _resolveInnerClassValuedProperty(config, prop); if (prop != origProp) { _beanProperties.replace(prop); } /* one more thing: if this property uses "external property" type inclusion * (see [JACKSON-453]), it needs different handling altogether */ if (prop.hasValueTypeDeserializer()) { TypeDeserializer typeDeser = prop.getValueTypeDeserializer(); if (typeDeser.getTypeInclusion() == JsonTypeInfo.As.EXTERNAL_PROPERTY) { if (extTypes == null) { extTypes = new ExternalTypeHandler.Builder(); } extTypes.addExternal(prop, typeDeser.getPropertyName()); // In fact, remove from list of known properties to simplify later handling _beanProperties.remove(prop); } } } // Finally, "any setter" may also need to be resolved now if (_anySetter != null && !_anySetter.hasValueDeserializer()) { _anySetter = _anySetter.withValueDeserializer(findDeserializer(config, provider, _anySetter.getType(), _anySetter.getProperty())); } // as well as delegate-based constructor: if (_valueInstantiator.canCreateUsingDelegate()) { JavaType delegateType = _valueInstantiator.getDelegateType(); if (delegateType == null) { throw new IllegalArgumentException("Invalid delegate-creator definition for "+_beanType +": value instantiator ("+_valueInstantiator.getClass().getName() +") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'"); } AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator(); // Need to create a temporary property to allow contextual deserializers: BeanProperty.Std property = new BeanProperty.Std(null, delegateType, _forClass.getAnnotations(), delegateCreator); _delegateDeserializer = findDeserializer(config, provider, delegateType, property); } // or property-based one // IMPORTANT: must access properties that _propertyBasedCreator has if (_propertyBasedCreator != null) { for (SettableBeanProperty prop : _propertyBasedCreator.getCreatorProperties()) { if (!prop.hasValueDeserializer()) { _propertyBasedCreator.assignDeserializer(prop, findDeserializer(config, provider, prop.getType(), prop)); } } } if (extTypes != null) { _externalTypeIdHandler = extTypes.build(); // we consider this non-standard, to offline handling _nonStandardCreation = true; } _unwrappedPropertyHandler = unwrapped; if (unwrapped != null) { // we consider this non-standard, to offline handling _nonStandardCreation = true; } } /** * Helper method called to see if given property is part of 'managed' property * pair (managed + back reference), and if so, handle resolution details. * * @since 1.9 */ protected SettableBeanProperty _resolveManagedReferenceProperty(DeserializationConfig config, SettableBeanProperty prop) { String refName = prop.getManagedReferenceName(); if (refName == null) { return prop; } JsonDeserializer<?> valueDeser = prop.getValueDeserializer(); SettableBeanProperty backProp = null; boolean isContainer = false; if (valueDeser instanceof BeanDeserializer) { backProp = ((BeanDeserializer) valueDeser).findBackReference(refName); } else if (valueDeser instanceof ContainerDeserializerBase<?>) { JsonDeserializer<?> contentDeser = ((ContainerDeserializerBase<?>) valueDeser).getContentDeserializer(); if (!(contentDeser instanceof BeanDeserializer)) { throw new IllegalArgumentException("Can not handle managed/back reference '"+refName +"': value deserializer is of type ContainerDeserializerBase, but content type is not handled by a BeanDeserializer " +" (instead it's of type "+contentDeser.getClass().getName()+")"); } backProp = ((BeanDeserializer) contentDeser).findBackReference(refName); isContainer = true; } else if (valueDeser instanceof AbstractDeserializer) { // [JACKSON-368]: not easy to fix, alas throw new IllegalArgumentException("Can not handle managed/back reference for abstract types (property "+_beanType.getRawClass().getName()+"."+prop.getName()+")"); } else { throw new IllegalArgumentException("Can not handle managed/back reference '"+refName +"': type for value deserializer is not BeanDeserializer or ContainerDeserializerBase, but " +valueDeser.getClass().getName()); } if (backProp == null) { throw new IllegalArgumentException("Can not handle managed/back reference '"+refName+"': no back reference property found from type " +prop.getType()); } // also: verify that type is compatible JavaType referredType = _beanType; JavaType backRefType = backProp.getType(); if (!backRefType.getRawClass().isAssignableFrom(referredType.getRawClass())) { throw new IllegalArgumentException("Can not handle managed/back reference '"+refName+"': back reference type (" +backRefType.getRawClass().getName()+") not compatible with managed type (" +referredType.getRawClass().getName()+")"); } return new SettableBeanProperty.ManagedReferenceProperty(refName, prop, backProp, _forClass.getAnnotations(), isContainer); } /** * Helper method called to see if given property might be so-called unwrapped * property: these require special handling. * * @since 1.9 */ protected SettableBeanProperty _resolveUnwrappedProperty(DeserializationConfig config, SettableBeanProperty prop) { AnnotatedMember am = prop.getMember(); if (am != null && config.getAnnotationIntrospector().shouldUnwrapProperty(am) == Boolean.TRUE) { JsonDeserializer<Object> orig = prop.getValueDeserializer(); JsonDeserializer<Object> unwrapping = orig.unwrappingDeserializer(); if (unwrapping != orig && unwrapping != null) { // might be cleaner to create new instance; but difficult to do reliably, so: return prop.withValueDeserializer(unwrapping); } } return null; } /** * Helper method that will handle gruesome details of dealing with properties * that have non-static inner class as value... * * @since 1.9 */ protected SettableBeanProperty _resolveInnerClassValuedProperty(DeserializationConfig config, SettableBeanProperty prop) { /* Should we encounter a property that has non-static inner-class * as value, we need to add some more magic to find the "hidden" constructor... */ JsonDeserializer<Object> deser = prop.getValueDeserializer(); // ideally wouldn't rely on it being BeanDeserializer; but for now it'll have to do if (deser instanceof BeanDeserializer) { BeanDeserializer bd = (BeanDeserializer) deser; ValueInstantiator vi = bd.getValueInstantiator(); if (!vi.canCreateUsingDefault()) { // no default constructor Class<?> valueClass = prop.getType().getRawClass(); Class<?> enclosing = ClassUtil.getOuterClass(valueClass); // and is inner class of the bean class... if (enclosing != null && enclosing == _beanType.getRawClass()) { for (Constructor<?> ctor : valueClass.getConstructors()) { Class<?>[] paramTypes = ctor.getParameterTypes(); if (paramTypes.length == 1 && paramTypes[0] == enclosing) { if (config.isEnabled(DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS)) { ClassUtil.checkAndFixAccess(ctor); } return new SettableBeanProperty.InnerClassProperty(prop, ctor); } } } } } return prop; } /* /********************************************************** /* JsonDeserializer implementation /********************************************************** */ /** * Main deserialization method for bean-based objects (POJOs). */ @Override public final Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); // common case first: if (t == JsonToken.START_OBJECT) { jp.nextToken(); return deserializeFromObject(jp, ctxt); } // and then others, generally requiring use of @JsonCreator switch (t) { case VALUE_STRING: return deserializeFromString(jp, ctxt); case VALUE_NUMBER_INT: return deserializeFromNumber(jp, ctxt); case VALUE_NUMBER_FLOAT: return deserializeFromDouble(jp, ctxt); case VALUE_EMBEDDED_OBJECT: return jp.getEmbeddedObject(); case VALUE_TRUE: case VALUE_FALSE: return deserializeFromBoolean(jp, ctxt); case START_ARRAY: // these only work if there's a (delegating) creator... return deserializeFromArray(jp, ctxt); case FIELD_NAME: case END_OBJECT: // added to resolve [JACKSON-319], possible related issues return deserializeFromObject(jp, ctxt); } throw ctxt.mappingException(getBeanClass()); } /** * Secondary deserialization method, called in cases where POJO * instance is created as part of deserialization, potentially * after collecting some or all of the properties to set. */ @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException, JsonProcessingException { if (_injectables != null) { injectValues(ctxt, bean); } if (_unwrappedPropertyHandler != null) { return deserializeWithUnwrapped(jp, ctxt, bean); } if (_externalTypeIdHandler != null) { return deserializeWithExternalTypeId(jp, ctxt, bean); } JsonToken t = jp.getCurrentToken(); // 23-Mar-2010, tatu: In some cases, we start with full JSON object too... if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); SettableBeanProperty prop = _beanProperties.find(propName); jp.nextToken(); // skip field, returns value token if (prop != null) { // normal case try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } if (_anySetter != null) { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); continue; } // Unknown: let's call handler method handleUnknownProperty(jp, ctxt, bean, propName); } return bean; } @Override public Object deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { // In future could check current token... for now this should be enough: return typeDeserializer.deserializeTypedFromObject(jp, ctxt); } /* /********************************************************** /* Concrete deserialization methods /********************************************************** */ public Object deserializeFromObject(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_nonStandardCreation) { if (_unwrappedPropertyHandler != null) { return deserializeWithUnwrapped(jp, ctxt); } if (_externalTypeIdHandler != null) { return deserializeWithExternalTypeId(jp, ctxt); } return deserializeFromObjectUsingNonDefault(jp, ctxt); } final Object bean = _valueInstantiator.createUsingDefault(); if (_injectables != null) { injectValues(ctxt, bean); } for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); // Skip field name: jp.nextToken(); SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); } else if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } else { // Unknown: let's call handler method handleUnknownProperty(jp, ctxt, bean, propName); } } return bean; } /** * @since 1.9 */ protected Object deserializeFromObjectUsingNonDefault(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); } if (_propertyBasedCreator != null) { return _deserializeUsingPropertyBased(jp, ctxt); } // should only occur for abstract types... if (_beanType.isAbstract()) { throw JsonMappingException.from(jp, "Can not instantiate abstract type "+_beanType +" (need to add/enable type information?)"); } throw JsonMappingException.from(jp, "No suitable constructor found for type " +_beanType+": can not instantiate from JSON object (need to add/enable type information?)"); } public Object deserializeFromString(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { /* Bit complicated if we have delegating creator; may need to use it, * or might not... */ if (_delegateDeserializer != null) { if (!_valueInstantiator.canCreateFromString()) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } } return _valueInstantiator.createFromString(jp.getText()); } public Object deserializeFromNumber(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { switch (jp.getNumberType()) { case INT: if (_delegateDeserializer != null) { if (!_valueInstantiator.canCreateFromInt()) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } } return _valueInstantiator.createFromInt(jp.getIntValue()); case LONG: if (_delegateDeserializer != null) { if (!_valueInstantiator.canCreateFromInt()) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } } return _valueInstantiator.createFromLong(jp.getLongValue()); } // actually, could also be BigInteger, so: if (_delegateDeserializer != null) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } throw ctxt.instantiationException(getBeanClass(), "no suitable creator method found to deserialize from JSON integer number"); } /** * Method called to deserialize POJO value from a JSON floating-point * number. * * @since 1.9 */ public Object deserializeFromDouble(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { switch (jp.getNumberType()) { case FLOAT: // no separate methods for taking float... case DOUBLE: if (_delegateDeserializer != null) { if (!_valueInstantiator.canCreateFromDouble()) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } } return _valueInstantiator.createFromDouble(jp.getDoubleValue()); } // actually, could also be BigDecimal, so: if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); } throw ctxt.instantiationException(getBeanClass(), "no suitable creator method found to deserialize from JSON floating-point number"); } /** * Method called to deserialize POJO value from a JSON boolean * value (true, false) * * @since 1.9 */ public Object deserializeFromBoolean(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_delegateDeserializer != null) { if (!_valueInstantiator.canCreateFromBoolean()) { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } } boolean value = (jp.getCurrentToken() == JsonToken.VALUE_TRUE); return _valueInstantiator.createFromBoolean(value); } /** * @since 1.9 */ public Object deserializeFromArray(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_delegateDeserializer != null) { try { Object bean = _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); if (_injectables != null) { injectValues(ctxt, bean); } return bean; } catch (Exception e) { wrapInstantiationProblem(e, ctxt); } } throw ctxt.mappingException(getBeanClass()); } /** * Method called to deserialize bean using "property-based creator": * this means that a non-default constructor or factory method is * called, and then possibly other setters. The trick is that * values for creator method need to be buffered, first; and * due to non-guaranteed ordering possibly some other properties * as well. * * @since 1.2 */ protected final Object _deserializeUsingPropertyBased(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt); // 04-Jan-2010, tatu: May need to collect unknown properties for polymorphic cases TokenBuffer unknown = null; JsonToken t = jp.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); // to point to value // creator property? SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { // Last creator property to set? Object value = creatorProp.deserialize(jp, ctxt); if (buffer.assignParameter(creatorProp.getPropertyIndex(), value)) { jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; // never gets here } // polymorphic? if (bean.getClass() != _beanType.getRawClass()) { return handlePolymorphic(jp, ctxt, bean, unknown); } if (unknown != null) { // nope, just extra unknown stuff... bean = handleUnknownProperties(ctxt, bean, unknown); } // or just clean? return deserialize(jp, ctxt, bean); } continue; } // regular property? needs buffering SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(jp, ctxt)); continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } // "any property"? if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt)); continue; } // Ok then, let's collect the whole field; name and value if (unknown == null) { unknown = new TokenBuffer(jp.getCodec()); } unknown.writeFieldName(propName); unknown.copyCurrentStructure(jp); } // We hit END_OBJECT, so: Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; // never gets here } if (unknown != null) { // polymorphic? if (bean.getClass() != _beanType.getRawClass()) { return handlePolymorphic(null, ctxt, bean, unknown); } // no, just some extra unknown properties return handleUnknownProperties(ctxt, bean, unknown); } return bean; } /** * Method called in cases where we may have polymorphic deserialization * case: that is, type of Creator-constructed bean is not the type * of deserializer itself. It should be a sub-class or implementation * class; either way, we may have more specific deserializer to use * for handling it. * * @param jp (optional) If not null, parser that has more properties to handle * (in addition to buffered properties); if null, all properties are passed * in buffer */ protected Object handlePolymorphic(JsonParser jp, DeserializationContext ctxt, Object bean, TokenBuffer unknownTokens) throws IOException, JsonProcessingException { // First things first: maybe there is a more specific deserializer available? JsonDeserializer<Object> subDeser = _findSubclassDeserializer(ctxt, bean, unknownTokens); if (subDeser != null) { if (unknownTokens != null) { // need to add END_OBJECT marker first unknownTokens.writeEndObject(); JsonParser p2 = unknownTokens.asParser(); p2.nextToken(); // to get to first data field bean = subDeser.deserialize(p2, ctxt, bean); } // Original parser may also have some leftovers if (jp != null) { bean = subDeser.deserialize(jp, ctxt, bean); } return bean; } // nope; need to use this deserializer. Unknowns we've seen so far? if (unknownTokens != null) { bean = handleUnknownProperties(ctxt, bean, unknownTokens); } // and/or things left to process via main parser? if (jp != null) { bean = deserialize(jp, ctxt, bean); } return bean; } /* /********************************************************** /* Handling for cases where we have "unwrapped" values /********************************************************** */ /** * Method called when there are declared "unwrapped" properties * which need special handling */ protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_delegateDeserializer != null) { return _valueInstantiator.createUsingDelegate(_delegateDeserializer.deserialize(jp, ctxt)); } if (_propertyBasedCreator != null) { return deserializeUsingPropertyBasedWithUnwrapped(jp, ctxt); } TokenBuffer tokens = new TokenBuffer(jp.getCodec()); tokens.writeStartObject(); final Object bean = _valueInstantiator.createUsingDefault(); if (_injectables != null) { injectValues(ctxt, bean); } for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // ignorable things should be ignored if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } // but... others should be passed to unwrapped property deserializers tokens.writeFieldName(propName); tokens.copyCurrentStructure(jp); // how about any setter? We'll get copies but... if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } } tokens.writeEndObject(); _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); return bean; } protected Object deserializeWithUnwrapped(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); if (t == JsonToken.START_OBJECT) { t = jp.nextToken(); } TokenBuffer tokens = new TokenBuffer(jp.getCodec()); tokens.writeStartObject(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); SettableBeanProperty prop = _beanProperties.find(propName); jp.nextToken(); if (prop != null) { // normal case try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } // but... others should be passed to unwrapped property deserializers tokens.writeFieldName(propName); tokens.copyCurrentStructure(jp); // how about any setter? We'll get copies but... if (_anySetter != null) { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } } tokens.writeEndObject(); _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); return bean; } protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt); TokenBuffer tokens = new TokenBuffer(jp.getCodec()); tokens.writeStartObject(); JsonToken t = jp.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); // to point to value // creator property? SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { // Last creator property to set? Object value = creatorProp.deserialize(jp, ctxt); if (buffer.assignParameter(creatorProp.getPropertyIndex(), value)) { t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; // never gets here } // if so, need to copy all remaining tokens into buffer while (t == JsonToken.FIELD_NAME) { jp.nextToken(); // to skip name tokens.copyCurrentStructure(jp); t = jp.nextToken(); } tokens.writeEndObject(); if (bean.getClass() != _beanType.getRawClass()) { // !!! 08-Jul-2011, tatu: Could probably support; but for now // it's too complicated, so bail out throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values"); } return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); } continue; } // regular property? needs buffering SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(jp, ctxt)); continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } tokens.writeFieldName(propName); tokens.copyCurrentStructure(jp); // "any property"? if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt)); } } // We hit END_OBJECT, so: Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; // never gets here } return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens); } /* /********************************************************** /* Handling for cases where we have property/-ies wth /* external type id /********************************************************** */ protected Object deserializeWithExternalTypeId(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (_propertyBasedCreator != null) { return deserializeUsingPropertyBasedWithExternalTypeId(jp, ctxt); } return deserializeWithExternalTypeId(jp, ctxt, _valueInstantiator.createUsingDefault()); } protected Object deserializeWithExternalTypeId(JsonParser jp, DeserializationContext ctxt, Object bean) throws IOException, JsonProcessingException { final ExternalTypeHandler ext = _externalTypeIdHandler.start(); for (; jp.getCurrentToken() != JsonToken.END_OBJECT; jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { // normal case try { prop.deserializeAndSet(jp, ctxt, bean); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } // ignorable things should be ignored if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } // but others are likely to be part of external type id thingy... if (ext.handleToken(jp, ctxt, propName, bean)) { continue; } // if not, the usual fallback handling: if (_anySetter != null) { try { _anySetter.deserializeAndSet(jp, ctxt, bean, propName); } catch (Exception e) { wrapAndThrow(e, bean, propName, ctxt); } continue; } else { // Unknown: let's call handler method handleUnknownProperty(jp, ctxt, bean, propName); } } // and when we get this far, let's try finalizing the deal: return ext.complete(jp, ctxt, bean); } protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { final ExternalTypeHandler ext = _externalTypeIdHandler.start(); final PropertyBasedCreator creator = _propertyBasedCreator; PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt); TokenBuffer tokens = new TokenBuffer(jp.getCodec()); tokens.writeStartObject(); JsonToken t = jp.getCurrentToken(); for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) { String propName = jp.getCurrentName(); jp.nextToken(); // to point to value // creator property? SettableBeanProperty creatorProp = creator.findCreatorProperty(propName); if (creatorProp != null) { // Last creator property to set? Object value = creatorProp.deserialize(jp, ctxt); if (buffer.assignParameter(creatorProp.getPropertyIndex(), value)) { t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt); continue; // never gets here } // if so, need to copy all remaining tokens into buffer while (t == JsonToken.FIELD_NAME) { jp.nextToken(); // to skip name tokens.copyCurrentStructure(jp); t = jp.nextToken(); } if (bean.getClass() != _beanType.getRawClass()) { // !!! 08-Jul-2011, tatu: Could probably support; but for now // it's too complicated, so bail out throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values"); } return ext.complete(jp, ctxt, bean); } continue; } // regular property? needs buffering SettableBeanProperty prop = _beanProperties.find(propName); if (prop != null) { buffer.bufferProperty(prop, prop.deserialize(jp, ctxt)); continue; } // external type id (or property that depends on it)? if (ext.handleToken(jp, ctxt, propName, null)) { continue; } /* As per [JACKSON-313], things marked as ignorable should not be * passed to any setter */ if (_ignorableProps != null && _ignorableProps.contains(propName)) { jp.skipChildren(); continue; } // "any property"? if (_anySetter != null) { buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt)); } } // We hit END_OBJECT, so: Object bean; try { bean = creator.build(buffer); } catch (Exception e) { wrapInstantiationProblem(e, ctxt); return null; // never gets here } return ext.complete(jp, ctxt, bean); } /* /********************************************************** /* Overridable helper methods /********************************************************** */ protected void injectValues(DeserializationContext ctxt, Object bean) throws IOException, JsonProcessingException { for (ValueInjector injector : _injectables) { injector.inject(ctxt, bean); } } /** * Method called when a JSON property is encountered that has not matching * setter, any-setter or field, and thus can not be assigned. */ @Override protected void handleUnknownProperty(JsonParser jp, DeserializationContext ctxt, Object beanOrClass, String propName) throws IOException, JsonProcessingException { /* 22-Aug-2010, tatu: Caller now mostly checks for ignorable properties, so * following should not be necessary. However, "handleUnknownProperties()" seems * to still possibly need it so it is left for now. */ // If registered as ignorable, skip if (_ignoreAllUnknown || (_ignorableProps != null && _ignorableProps.contains(propName))) { jp.skipChildren(); return; } /* Otherwise use default handling (call handler(s); if not * handled, throw exception or skip depending on settings) */ super.handleUnknownProperty(jp, ctxt, beanOrClass, propName); } /** * Method called to handle set of one or more unknown properties, * stored in their entirety in given {@link TokenBuffer} * (as field entries, name and value). */ protected Object handleUnknownProperties(DeserializationContext ctxt, Object bean, TokenBuffer unknownTokens) throws IOException, JsonProcessingException { // First: add closing END_OBJECT as marker unknownTokens.writeEndObject(); // note: buffer does NOT have starting START_OBJECT JsonParser bufferParser = unknownTokens.asParser(); while (bufferParser.nextToken() != JsonToken.END_OBJECT) { String propName = bufferParser.getCurrentName(); // Unknown: let's call handler method bufferParser.nextToken(); handleUnknownProperty(bufferParser, ctxt, bean, propName); } return bean; } /** * Helper method called to (try to) locate deserializer for given sub-type of * type that this deserializer handles. */ protected JsonDeserializer<Object> _findSubclassDeserializer(DeserializationContext ctxt, Object bean, TokenBuffer unknownTokens) throws IOException, JsonProcessingException { JsonDeserializer<Object> subDeser; // First: maybe we have already created sub-type deserializer? synchronized (this) { subDeser = (_subDeserializers == null) ? null : _subDeserializers.get(new ClassKey(bean.getClass())); } if (subDeser != null) { return subDeser; } // If not, maybe we can locate one. First, need provider DeserializerProvider deserProv = ctxt.getDeserializerProvider(); if (deserProv != null) { JavaType type = ctxt.constructType(bean.getClass()); /* 09-Dec-2010, tatu: Would be nice to know which property pointed to this * bean... but, alas, no such information is retained, so: */ subDeser = deserProv.findValueDeserializer(ctxt.getConfig(), type, _property); // Also, need to cache it if (subDeser != null) { synchronized (this) { if (_subDeserializers == null) { _subDeserializers = new HashMap<ClassKey,JsonDeserializer<Object>>();; } _subDeserializers.put(new ClassKey(bean.getClass()), subDeser); } } } return subDeser; } /* /********************************************************** /* Helper methods for error reporting /********************************************************** */ /** * Method that will modify caught exception (passed in as argument) * as necessary to include reference information, and to ensure it * is a subtype of {@link IOException}, or an unchecked exception. *<p> * Rules for wrapping and unwrapping are bit complicated; essentially: *<ul> * <li>Errors are to be passed as is (if uncovered via unwrapping) * <li>"Plain" IOExceptions (ones that are not of type * {@link JsonMappingException} are to be passed as is *</ul> */ public void wrapAndThrow(Throwable t, Object bean, String fieldName, DeserializationContext ctxt) throws IOException { /* 05-Mar-2009, tatu: But one nasty edge is when we get * StackOverflow: usually due to infinite loop. But that * usually gets hidden within an InvocationTargetException... */ while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors and "plain" IOExceptions to be passed as is if (t instanceof Error) { throw (Error) t; } boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationConfig.Feature.WRAP_EXCEPTIONS); // Ditto for IOExceptions; except we may want to wrap mapping exceptions if (t instanceof IOException) { if (!wrap || !(t instanceof JsonMappingException)) { throw (IOException) t; } } else if (!wrap) { // [JACKSON-407] -- allow disabling wrapping for unchecked exceptions if (t instanceof RuntimeException) { throw (RuntimeException) t; } } // [JACKSON-55] Need to add reference information throw JsonMappingException.wrapWithPath(t, bean, fieldName); } public void wrapAndThrow(Throwable t, Object bean, int index, DeserializationContext ctxt) throws IOException { while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors and "plain" IOExceptions to be passed as is if (t instanceof Error) { throw (Error) t; } boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationConfig.Feature.WRAP_EXCEPTIONS); // Ditto for IOExceptions; except we may want to wrap mapping exceptions if (t instanceof IOException) { if (!wrap || !(t instanceof JsonMappingException)) { throw (IOException) t; } } else if (!wrap) { // [JACKSON-407] -- allow disabling wrapping for unchecked exceptions if (t instanceof RuntimeException) { throw (RuntimeException) t; } } // [JACKSON-55] Need to add reference information throw JsonMappingException.wrapWithPath(t, bean, index); } protected void wrapInstantiationProblem(Throwable t, DeserializationContext ctxt) throws IOException { while (t instanceof InvocationTargetException && t.getCause() != null) { t = t.getCause(); } // Errors and "plain" IOExceptions to be passed as is if (t instanceof Error) { throw (Error) t; } boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationConfig.Feature.WRAP_EXCEPTIONS); if (t instanceof IOException) { // Since we have no more information to add, let's not actually wrap.. throw (IOException) t; } else if (!wrap) { // [JACKSON-407] -- allow disabling wrapping for unchecked exceptions if (t instanceof RuntimeException) { throw (RuntimeException) t; } } throw ctxt.instantiationException(_beanType.getRawClass(), t); } /** * @deprecated Since 1.7 use variant that takes {@link DeserializationContext} */ @Deprecated public void wrapAndThrow(Throwable t, Object bean, String fieldName) throws IOException { wrapAndThrow(t, bean, fieldName, null); } /** * @deprecated Since 1.7 use variant that takes {@link DeserializationContext} */ @Deprecated public void wrapAndThrow(Throwable t, Object bean, int index) throws IOException { wrapAndThrow(t, bean, index, null); } }
zzyapps
trunk/JqFw/core/org/codehaus/jackson/map/deser/BeanDeserializer.java
Java
asf20
63,373
package cn.com.widemex.core.data; import java.util.Map; /** * 自定义Map,添加值转换 * @author 张中原 * */ public interface MyMap extends IDataTransform, Map<String, Object> { }
zzyapps
trunk/JqFw/core/cn/com/widemex/core/data/MyMap.java
Java
asf20
208
package cn.com.widemex.core.data; import java.math.BigDecimal; import java.util.Date; import java.sql.Time; import java.sql.Timestamp; /** * 数值转换接口 * @author 张中原 * */ public interface IDataTransform { /** * 获取字符串类型的数据 * @param propName bean的属性名 */ public String getString(String propName); /** * 获取int数据 * @param propName bean的属性名 * @return */ @Deprecated public Integer getInt(String propName); /** * 获取int数据 * @param propName bean的属性名 * @return */ public Integer getInteger(String propName); /** * 获取float数据 * @param propName bean的属性名 * @return */ public float getFloat(String propName); /** * 获取double数据 * @param propName bean的属性名 * @return */ public double getDouble(String propName); /** * 获取long数据 * @param propName bean的属性名 * @return */ public long getLong(String propName); /** * 获取boolean 数据 * @param propName bean的属性名 * @return */ public boolean getBoolean(String propName); /** * 获取BigDecimal数据 * @param propName bean的属性名 * @return */ public BigDecimal getBigDecimal(String propName); /** * 获取SQL DATE 数据 * @param propName bean的属性名 * @return */ public java.sql.Date getSqlDate(String propName); /** * 获取util Date 数据 * @param propName bean的属性名 * @return */ public Date getDate(String propName); /** * 获取Time数据 * @param propName bean的属性名 * @return */ public Time getTime(String propName); /** * 获取Timestamp 数据 * @param propName bean的属性名 * @return */ public Timestamp getTimestamp(String propName); /** * 获取字符串类型的数据 * @param propName bean的属性名 * @param defaultValue 默认值 */ public String getString(String propName, String defaultValue); /** * 获取int数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public int getInt(String propName, int defaultValue); /** * 获取float数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public float getFloat(String propName, float defaultValue); /** * 获取double数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public double getDouble(String propName, double defaultValue); /** * 获取long数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public long getLong(String propName, long defaultValue); /** * 获取boolean 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public boolean getBoolean(String propName, boolean defaultValue); /** * 获取BigDecimal数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public BigDecimal getBigDecimal(String propName, BigDecimal defaultValue); /** * 获取SQL DATE 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public java.sql.Date getSqlDate(String propName, java.sql.Date defaultValue); /** * 获取util Date 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Date getDate(String propName, Date defaultValue); /** * 获取Time数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Time getTime(String propName, Time defaultValue); /** * 获取Timestamp 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Timestamp getTimestamp(String propName, Timestamp defaultValue); }
zzyapps
trunk/JqFw/core/cn/com/widemex/core/data/IDataTransform.java
Java
asf20
3,993
package cn.com.widemex.core.data; import java.math.BigDecimal; import java.sql.Time; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import cn.com.widemex.core.utils.data.ConverHelper; public class MyHashMap extends HashMap<String, Object> implements MyMap { /** * 获取字符串类型的数据 * @param propName bean的属性名 */ public String getString(String propName ){ return ConverHelper.object2String(this.get(propName)); } /** * 获取int数据 * @param propName bean的属性名 * @return */ @Deprecated public Integer getInt(String propName){ return this.getInteger(propName); } /** * 获取Integer数据(修正null问题) * @param propName bean的属性名 * @return */ public Integer getInteger(String propName){ Object o = this.get(propName); if(o==null){ return null; } if(o instanceof Integer) return (Integer)o; return Integer.parseInt(o.toString()); } /** * 获取float数据 * @param propName bean的属性名 * @return */ public float getFloat(String propName){ return Float.parseFloat(this.get(propName).toString()); } /** * 获取double数据 * @param propName bean的属性名 * @return */ public double getDouble(String propName){ return Double.parseDouble(this.get(propName).toString()); } /** * 获取long数据 * @param propName bean的属性名 * @return */ public long getLong(String propName){ return Long.parseLong(this.get(propName).toString()); } /** * 获取boolean 数据 * @param propName * @return */ public boolean getBoolean(String propName){ return Boolean.parseBoolean(this.get(propName).toString()); } /** * 获取BigDecimal数据 * @param propName * @return */ public BigDecimal getBigDecimal(String propName){ return (BigDecimal)(this.get(propName)); } /** * 获取SQL DATE 数据 * @param propName * @return */ public java.sql.Date getSqlDate(String propName){ return ConverHelper.dateTimeObject2SqlDate(this.get(propName)); } /** * 获取util Date 数据 * @param propName * @return */ public Date getDate(String propName){ return ConverHelper.dateTimeObject2UtilDate(this.get(propName)); } /** * 获取Time数据 * @param propName * @return */ public Time getTime(String propName){ return ConverHelper.dateTimeObject2Time(this.get(propName)); } /** * 获取Timestamp 数据 * @param propName * @return */ public Timestamp getTimestamp(String propName){ return ConverHelper.dateTimeObject2Timestamp(this.get(propName)); } /** * 获取字符串类型的数据 * @param propName bean的属性名 * @param defaultValue 默认值 */ public String getString(String propName, String defaultValue){ try{ String str = this.getString(propName); return str==null ? defaultValue : str; }catch(Exception e){ return defaultValue; } } /** * 获取int数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public int getInt(String propName, int defaultValue){ try{ return this.getInt(propName); }catch(Exception e){ return defaultValue; } } /** * 获取float数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public float getFloat(String propName, float defaultValue){ try{ return this.getFloat(propName); }catch(Exception e){ return defaultValue; } } /** * 获取double数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public double getDouble(String propName, double defaultValue){ try{ return this.getDouble(propName); }catch(Exception e){ return defaultValue; } } /** * 获取long数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public long getLong(String propName, long defaultValue){ try{ return this.getLong(propName); }catch(Exception e){ return defaultValue; } } /** * 获取boolean 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public boolean getBoolean(String propName, boolean defaultValue){ try{ return this.getBoolean(propName); }catch(Exception e){ return defaultValue; } } /** * 获取BigDecimal数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public BigDecimal getBigDecimal(String propName, BigDecimal defaultValue){ try{ return this.getBigDecimal(propName); }catch(Exception e){ return defaultValue; } } /** * 获取SQL DATE 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public java.sql.Date getSqlDate(String propName, java.sql.Date defaultValue){ try{ return this.getSqlDate(propName); }catch(Exception e){ return defaultValue; } } /** * 获取util Date 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Date getDate(String propName, Date defaultValue){ try{ return this.getDate(propName); }catch(Exception e){ return defaultValue; } } /** * 获取Time数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Time getTime(String propName, Time defaultValue){ try{ return this.getTime(propName); }catch(Exception e){ return defaultValue; } } /** * 获取Timestamp 数据 * @param propName bean的属性名 * @param defaultValue 默认值 * @return */ public Timestamp getTimestamp(String propName, Timestamp defaultValue){ try{ return this.getTimestamp(propName); }catch(Exception e){ return defaultValue; } } }
zzyapps
trunk/JqFw/core/cn/com/widemex/core/data/MyHashMap.java
Java
asf20
6,048
package cn.com.widemex.core.db; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collection; import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.com.widemex.core.utils.data.StrHelper; import cn.com.widemex.core.utils.data.Type; import cn.com.widemex.core.utils.reflection.GenericsUtils; import cn.com.widemex.core.vo.PageVO; import cn.com.widemex.core.vo.SortVO; /** * DAO基本实现类 * @author 张中元 * * @param <T> pojo名称 * @param <ID> 主键类型 */ public class HibernateDao<T> extends HibernateDaoSupport{ /**实体类型*/ protected Class<T> entityClass; /**基本hql语句*/ public String entityHql; /** * 实例化dao */ public HibernateDao() { //获得范型参数的类型 this.entityClass = GenericsUtils.getSuperClassGenricType(this.getClass()); //根据范型参数初始化HQL this.entityHql = "from " + this.entityClass.getName() + " "; } ///////////////////////////////查询---start///////////////////////////////////////////////////// /** * 根据ID得到po * @param id * @return */ public T get(Serializable id) { if (id == null) { return null; } else { return this.getHibernateTemplate().get(this.entityClass, id); } } /** * 根据ID得到po(from 缓存) * @param id * @return */ public T load(Serializable id) { return this.getHibernateTemplate().load(this.entityClass, id); } /** * 根据hql查询 * @param hql * @param params * @return */ public List<T> find(String hql, Object... params) { return createQuery(hql, params).list(); } // public List<T> find(String hql, boolean isHql, Object... params) { // return createQuery(hql, isHql, params).list(); // } /** * 根据hql语句获取第一条记录 */ public T findUnique(String hql, Object... params) { return (T) createQuery(hql, params).uniqueResult(); } /** * 是否唯一 * @param COL=? ... * @param 查询参数 * @return */ public boolean isUnique(String hql, Object... params){ return this.getCount(hql, params) == 0; } /** * 分页查询 * @param page 分页对象 * @return */ public PageVO findPage(PageVO page) { Object[] params = page.getWhereParams(); int count = 0; String hql = page.getWhere(); if(hql.toUpperCase().indexOf("SELECT") != 0){ if(this.entityHql.indexOf("where") > 0){ hql = hql.replace("where", "and"); } hql = this.entityHql + hql; } // 处理排序 if(page.getSortList()!=null && page.getSortList().size()>0){ hql += " ORDER BY "; List<SortVO> sortList = page.getSortList(); for (int i = 0; i < sortList.size(); i++) { SortVO sortVO = sortList.get(i); hql += sortVO.getProperty() + " " + sortVO.getDirection() + ((i+1) == sortList.size() ? " " : ", "); } } Query query = createQuery(hql, params); if(page.getLimit() != 0){ count = this.getCount(page.getWhere(), params); query = query.setFirstResult(page.getStart()); query = query.setMaxResults(page.getLimit()); } List<T> results = query.list(); page.setTotal(count); page.setRows(results); return page; } /** * 分页查询 * @param start 开始记录 * @param limit 最大行数 * @param where where条件 * @param params where条件参数 * @return */ public PageVO findPage(int start, int limit, String where, Object... params) { return findPage(new PageVO(start, limit, where, params)); } /** * 分页查询 * @param start 开始记录 * @param limit 最大行数 * @param where 查询条件 * @return */ public PageVO findPage(int start, int limit, String where) { return findPage(new PageVO(start, limit, where)); } /** * 分页查询 * @param where 查询条件 * @param params 动态参数 * @return */ public PageVO findPage(String where, Object... params) { return findPage(new PageVO(0, 0, where, params)); } /** * 分页查询 * @param where 查询条件 * @return */ public PageVO findPage(String where) { return findPage(new PageVO(0, 0, where)); } /** * 返回记录条数 * @param where 查询条件 * @param params 查询参数 * @return */ public int getCount(String where, Object... params) { return this.getCount(where, true, params); } /** * 返回记录条数 * @param where 查询条件 * @param isHql 是否是HQL * @param params 查询参数 * @return */ public int getCount(String where, boolean isHql, Object... params) { int i = (where.toUpperCase()).indexOf("ORDER BY"); if(i >= 0) where = where.substring(0, i); if(where.toUpperCase().indexOf("WHERE") < 0 && params.length > 0) where = " where " + where; String hql = ""; if(where.toUpperCase().indexOf("SELECT COUNT(1)") != 0){ if(where.toUpperCase().trim().indexOf("SELECT") != 0 && where.toUpperCase().trim().indexOf("FROM") != 0){ if(this.entityHql.toUpperCase().indexOf("WHERE") > 0){ where = where.replace("where", "and"); } hql = "select count(*) " + this.entityHql + where; } else{ hql = "select count(*) " + where.substring(where.toUpperCase().indexOf("FROM")); } } else{ hql = where; } hql = hql.replaceAll("fetch", ""); hql = hql.replaceAll("FETCH", ""); return Type.toInt(createQuery(hql, isHql, params).uniqueResult()); } ///////////////////////////////查询---end///////////////////////////////////////////////////// ///////////////////////////////保存、更新---start//////////////////////////////////////////////// /** * 保存或者更新pojo * @param entity pojo对象 */ public boolean saveOrUpdate(T entity) { return this.saveOrUpdate(entity, 0); } /** * 保存或更新pojo集合 * @param entities 集合 */ public boolean saveOrUpdateAll(Collection<T> entities){ return this.saveOrUpdate(entities, 3); } /** * 保存pojo * @param entity pojo对象 */ public boolean save(T entity){ return this.saveOrUpdate(entity, 1); } /** * 更新pojo * @param entity pojo对象 */ public boolean update(T entity) { return this.saveOrUpdate(entity, 2); } /** * 根据标识来判断是保存、更新、集合保存更新 * @param entity pojo对象 * @param flag 标识 0:保存或更新 ; 1:保存; 2:更新; 3:保存或者更新集合 * @return */ private boolean saveOrUpdate(Object entity, int flag){ switch (flag) { case 0: this.getHibernateTemplate().saveOrUpdate((T) entity); break; case 1: this.getHibernateTemplate().save((T)entity); break; case 2: this.getHibernateTemplate().update((T)entity); break; case 3: this.getHibernateTemplate().saveOrUpdateAll((Collection<T>)entity); break; } return true; } ///////////////////////////////保存、更新---end//////////////////////////////////////////////////////////////// ///////////////////////////////删除---start//////////////////////////////////////////////////////////////// /** * 删除pojo * @param entity pojo对象 */ public boolean remove(T entity) { return this.remove(null, entity); } /** * 根据主键删除 * @param id 主键 */ public boolean remove(Serializable id) { return this.remove(id, null); } /** * 删除全部 * @return */ public boolean removeAll() { return this.removeAll(this.getAll()); } /** * 删除集合里的所有信息 */ public boolean removeAll(Collection<T> list) { boolean success = false; for (T obj : list) { success = this.remove(null, obj); if(!success) return false; } return success; } /** * 删除记录:优先根据id删除,如果id在数据库中不存在,则根据pojo对象删除 * @param id 主键 * @param entity pojo对象 * @return */ private boolean remove(Serializable id, T entity) { Object obj = id == null ? entity : this.get(id); this.getHibernateTemplate().delete(obj); return true; } /** * 删除记录:根据hql语句及其参数 */ public boolean remove(String hql, Object... params) { return this.executeUpdate(hql, params) > 0; } ///////////////////////////////删除---end//////////////////////////////////////////////////////////////// /** * 根据QBC条件创建Criteria * @param criterions * @return */ private Criteria createCriteria(Criterion... criterions) { Criteria criteria = this.getSession().createCriteria(this.entityClass); for (Criterion c : criterions) { criteria.add(c); } return criteria; } private Criteria createCriteria(String sort, boolean isAsc, Criterion... criterions) { Criteria criteria = this.createCriteria(criterions); if(sort != null){ if (isAsc) { criteria.addOrder(Order.asc(sort)); } else { criteria.addOrder(Order.desc(sort)); } } return criteria; } /** * 单条件QBC查询 * @param name * @param value * @return */ public List<T> findBy(String name, Object value) { return createCriteria(Restrictions.eq(name, value)).list(); } public List<T> findBy(String name, Object value, String sort, boolean isAsc) { return createCriteria(sort, isAsc, Restrictions.eq(name, value)).list(); } public List<T> findByLike(String name, Object value) { return createCriteria(Restrictions.like(name, value)).list(); } public List<T> findByLike(String name, Object value, String sort, boolean isAsc) { return createCriteria(sort, isAsc, Restrictions.like(name, value)).list(); } public T findUniqueBy(String name, Object value) { return (T) createCriteria(Restrictions.eq(name, value)) .setMaxResults(1).uniqueResult(); } /** * QBC排序、返回所有记录 * @param sort * @param isAsc * @return */ public List<T> getAll(String sort, boolean isAsc) { Criteria criteria = createCriteria(); if ((sort == null) || sort.trim().equals("")) { /// } else { if (isAsc) { criteria.addOrder(Order.asc(sort)); } else { criteria.addOrder(Order.desc(sort)); } } return criteria.list(); } public List<T> getAll(){ return this.getAll(null, false); } /** * executeUpdate * @param hql * @param isHql * @param params */ public int executeUpdate(String hql, boolean isHql, Object... params){ Query query = this.createQuery(hql, isHql, params); return query.executeUpdate(); } public int executeUpdate(String hql, Object... params){ return this.executeUpdate(hql, true, params); } /** * 根据hql、params返回query * @param hql * @param params * @return */ public Query createQuery(String hql, boolean isHql, Object... params) { Query query = null; Session session = this.getSession(); if(isHql){ if(hql.indexOf("from") < 0 && hql.indexOf("where") < 0) hql = this.entityHql + " where " + hql; query = session.createQuery(hql); } else{ query = session.createSQLQuery(hql); } if(params != null){ int pLen = 0; for (int i = 0; i < params.length; i++) { Object v = params[i]; if(StrHelper.isEmpty(v + "") && hql.toUpperCase().indexOf("WHERE") > 0 && hql.toUpperCase().indexOf("UPDATE") < 0){ continue; } if(v != null && v.getClass().isArray()){ query.setParameterList("value" + i, (Object[]) params[i]); } else{ query.setParameter(pLen++, params[i]); } } } return query; } public Query createQuery(String hql, Object... params) { return this.createQuery(hql, true, params); } }
zzyapps
trunk/JqFw/core/cn/com/widemex/core/db/HibernateDao.java
Java
asf20
13,799
package cn.com.widemex.core.db; import java.io.Serializable; import java.util.Collection; import java.util.List; import cn.com.widemex.core.vo.PageVO; /** * 通用DAO接口 * @author 张中元 * * @param <T> pojo类 * @param <ID> 主键类型 */ public interface ExtDao<T>/*<T, ID extends Serializable> extends GenericDAO<T, ID> */ { /** * 根据ID得到po * @param id * @return */ public T get(Serializable id); /** * 查询 * 默认为HQL查询 * @param hql * @param params * @return */ public List<T> find(String hql, Object... params); /** * 查询 * 允许设置是否是HQL查询 * @param hql * @param isHql * @param params * @return */ public List<T> find(String hql, boolean isHql, Object... params); /** * 查询 * 根据字段、值返回符合条件的记录集 * @param name * @param value * @return */ public List<T> findBy(String name, Object value); /** * 查询 * 根据字段、值返回符合条件的记录集 * 允许设置排序 * @param name * @param value * @param sort * @param isAsc * @return */ public List<T> findBy(String name, Object value, String sort, boolean isAsc); /** * 查询 * 返回符合条件的第一条记录 * @param name * @param value * @return */ public T findUniqueBy(String name, Object value); /** * 分页查询 * @param start * @param limit * @param where * @param params * @return */ public PageVO findPage(int start, int limit, String where, Object... params); /** * 分页 * @param page 分页对象 * @return */ public PageVO findPage(PageVO page); /** * 保存 * 新增或更新 * @param entity * @return */ public boolean saveOrUpdate(T entity); /** * 批量保存 * 新增或更新 * @param entities * @return */ public boolean saveOrUpdateAll(Collection<T> entities); /** * 新增 * @param entity * @return */ public boolean save(T entity); /** * 更新 * @param entity * @return */ public boolean update(T entity); /** * 删除 * @param id * @return */ public boolean remove(T id); /** * 删除 * @param id * @return */ public boolean remove(Serializable id); /** * 批量删除 * @param list * @return */ public boolean removeAll(Collection<T> list); /** * 删除 * @param hql * @param params * @return */ public boolean remove(String hql, Object... params); /** * 删除 * @param hql * @param params * @param types * @return */ public boolean remove(String hql, Object[] params, int[] types); /** * 是否唯一 * @param COL=? ... * @param 查询参数 * @return */ public boolean isUnique(String hql, Object... params); }
zzyapps
trunk/JqFw/core/cn/com/widemex/core/db/ExtDao.java
Java
asf20
2,969