8. Csharp Snippets

21 марта 2023 г.

16:10

string csvFilePathTmp = _Connection.GetConfigParm("Custom\SED\CsvDirTemp") + "\" + _Connection.GetConfigParm("Custom\SED\CsvFileName");

using(var reader = new System.IO.StreamReader(csvFilePathTmp))

{

System.Collections.Generic.List\<string> ModuleSED = new System.Collections.Generic.List\<string>();

System.Collections.Generic.List\<string> ProductSED = new System.Collections.Generic.List\<string>();

System.Collections.Generic.List\<string> GroupAD = new System.Collections.Generic.List\<string>();

System.Collections.Generic.List\<string> dbKeySEDProduct = new System.Collections.Generic.List\<string>(); //Для хранения ключей продуктов из БД

System.Collections.Generic.List\<string> csvKeySEDProduct = new System.Collections.Generic.List\<string>(); // Для хранения ключей продуктов из загруженного CSV

System.Collections.Generic.List\<string> CsvDiffDb = new System.Collections.Generic.List\<string>();

System.Collections.Generic.List\<string> CsvErrors = new System.Collections.Generic.List\<string>();

// Для хранения значений колонок файла CSV

string strCsvKeySEDProduct;

string csvModuleSED;

string csvCategorySED;

string csvProductSED;

string csvRoleSED;

string csvAdditionalParam;

string csvGroupAD;

string csvApprovalPerson;

//Объявим DataTable для хранения данных из CSV

/*var dtCSV = new System.Data.DataTable();

dtCSV.Columns.Add("Key",typeof(string));

dtCSV.Columns.Add("ModuleSED",typeof(string));

dtCSV.Columns.Add("CategorySED",typeof(string));

dtCSV.Columns.Add("ProductSED",typeof(string));

dtCSV.Columns.Add("RoleSED",typeof(string));

dtCSV.Columns.Add("AdditionalParam",typeof(string));

dtCSV.Columns.Add("GroupAD",typeof(string));

dtCSV.Columns.Add("ApprovalPerson",typeof(string)); */

//Объявим HashTables для хранения данных из CSV

System.Collections.Hashtable htCSV_ModuleSED = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_CategorySED = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_ProductSED = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_RoleSED = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_AdditionalParam = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_GroupAD = new System.Collections.Hashtable();

System.Collections.Hashtable htCSV_ApprovalPerson = new System.Collections.Hashtable();

//Объявим HashTables для хранения данных из DB

System.Collections.Hashtable htDB_ModuleSED = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_CategorySED = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_ProductSED = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_RoleSED = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_AdditionalParam = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_GroupAD = new System.Collections.Hashtable();

System.Collections.Hashtable htDB_ApprovalPerson = new System.Collections.Hashtable();

//Получим лист из ключей продуктов записей в БД

var CCC_KeySED = this.DataContext.CCCSEDProducts.GetColumn("CCC_Key");

var CCC_ModuleSED = this.DataContext.CCCSEDProducts.GetColumn("CCC_ModuleSED");

var CCC_CategorySED = this.DataContext.CCCSEDProducts.GetColumn("CCC_CategorySED");

var CCC_ProductSED = this.DataContext.CCCSEDProducts.GetColumn("CCC_SEDProduct");

var CCC_RoleSED = this.DataContext.CCCSEDProducts.GetColumn("CCC_SEDRole");

var CCC_AdditionalParam = this.DataContext.CCCSEDProducts.GetColumn("CCC_AdditionalParam");

var CCC_GroupAD = this.DataContext.CCCSEDProducts.GetColumn("CCC_AdGroupName");

var CCC_ApprovalPerson = this.DataContext.CCCSEDProducts.GetColumn("CCC_ApprovalPerson");

foreach (var row1 in this.DataContext.CCCSEDProducts) {

dbKeySEDProduct.Add(CCC_KeySED.GetValue(row1).ToString());

htDB_ModuleSED.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_ModuleSED.GetValue(row1).ToString());

htDB_CategorySED.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_CategorySED.GetValue(row1).ToString());

htDB_ProductSED.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_ProductSED.GetValue(row1).ToString());

htDB_RoleSED.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_RoleSED.GetValue(row1).ToString());

htDB_AdditionalParam.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_AdditionalParam.GetValue(row1).ToString());

htDB_GroupAD.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_GroupAD.GetValue(row1).ToString());

htDB_ApprovalPerson.Add(CCC_KeySED.GetValue(row1).ToString(), CCC_ApprovalPerson.GetValue(row1).ToString());

}

//Пройдемся по строкам файла CSV

while (!reader.EndOfStream)

{

var line = reader.ReadLine();

string sep = "\t";

var values = line.Split(sep.ToCharArray());

csvModuleSED = values[0];

csvCategorySED = values[1];

csvProductSED = values[2];

csvRoleSED = values[3];

csvAdditionalParam = values[4];

csvGroupAD = values[7];

csvApprovalPerson = values[9];

//Пропустим Header CSV

if (csvModuleSED == "ModuleSED" || csvModuleSED == "Модуль СЭД") {

continue;

}

//Сформируем ключ продукта

ModuleSED.Add(values[0]);

ProductSED.Add(values[2]);

if (csvAdditionalParam == "") {

csvKeySEDProduct.Add(csvModuleSED + " - " + csvProductSED);

strCsvKeySEDProduct = csvModuleSED + " - " + csvProductSED;

}

else {

csvKeySEDProduct.Add(csvModuleSED + " - " + csvProductSED + " - " + csvAdditionalParam);

strCsvKeySEDProduct = csvModuleSED + " - " + csvProductSED + " - " + csvAdditionalParam;

}

//Заполним DataTable CSV

//dtCSV.Rows.Add(strCsvKeySEDProduct,csvModuleSED,csvCategorySED,csvProductSED,csvRoleSED,csvAdditionalParam,csvGroupAD,csvApprovalPerson);

//Заполним HashTables CSV

htCSV_ModuleSED.Add(strCsvKeySEDProduct, csvModuleSED);

htCSV_CategorySED.Add(strCsvKeySEDProduct, csvCategorySED);

htCSV_ProductSED.Add(strCsvKeySEDProduct, csvProductSED);

htCSV_RoleSED.Add(strCsvKeySEDProduct, csvRoleSED);

htCSV_AdditionalParam.Add(strCsvKeySEDProduct, csvAdditionalParam);

htCSV_GroupAD.Add(strCsvKeySEDProduct, csvGroupAD);

htCSV_ApprovalPerson.Add(strCsvKeySEDProduct, csvApprovalPerson);

}

//Проверка на пустные обязательные поля

int i = 0;

foreach (string ModuleSED_ in ModuleSED) {

i += 1;

if (ModuleSED_ == "") {

string str_i;

str_i = i.ToString();

Call4.MessageType = "Error";

Call4.MessageText = "Колонка Модуль СЭД пустая в " + str_i + " строке";

Call4.TableStore = this.TableStore.GetChildTableStore(_Module, (this.TableStore.Name + "_Call4"));

Call4.GetAction(ct);

CsvErrors.Add("Error");

}

}

i = 0;

foreach (string ProductSED_ in ProductSED) {

i += 1;

if (ProductSED_ == "") {

string str_i;

str_i = i.ToString();

Call4.MessageType = "Error";

Call4.MessageText = "Колонка Продукт СЭД пустая в " + str_i + " строке";

Call4.TableStore = this.TableStore.GetChildTableStore(_Module, (this.TableStore.Name + "_Call4"));

Call4.GetAction(ct);

CsvErrors.Add("Error");

}

}

//Сформируем Lists отличающихся записей csv и DB

var CsvExceptDb = csvKeySEDProduct.Except(dbKeySEDProduct).ToList();

var DbExceptCsv = dbKeySEDProduct.Except(csvKeySEDProduct).ToList();

//Заполним Коллекцию продуктов, которые будут импортированы в БД

VI.WebRuntime.ColumnInsertValues _insertValues = new VI.WebRuntime.ColumnInsertValues();

VI.WebRuntime.IDataColumn _ModuleSED = this.DataContext.CCCSEDProductsDiff.GetColumn("ModuleSED");

VI.WebRuntime.IDataColumn _CategorySED = this.DataContext.CCCSEDProductsDiff.GetColumn("CategorySED");

VI.WebRuntime.IDataColumn _ProductSED = this.DataContext.CCCSEDProductsDiff.GetColumn("ProductSED");

VI.WebRuntime.IDataColumn _RoleSED = this.DataContext.CCCSEDProductsDiff.GetColumn("RoleSED");

VI.WebRuntime.IDataColumn _AdditionalParam = this.DataContext.CCCSEDProductsDiff.GetColumn("AdditionalParam");

VI.WebRuntime.IDataColumn _GroupAD = this.DataContext.CCCSEDProductsDiff.GetColumn("ADGroup");

VI.WebRuntime.IDataColumn _ApprovalPerson = this.DataContext.CCCSEDProductsDiff.GetColumn("ApprovalPerson");

foreach (string keySEDProduct in CsvExceptDb) {

_insertValues.DynamicInsertValues[_ModuleSED] = _row =>

{

return htCSV_ModuleSED[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_CategorySED] = _row =>

{

return htCSV_CategorySED[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_ProductSED] = _row =>

{

return htCSV_ProductSED[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_RoleSED] = _row =>

{

return htCSV_RoleSED[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_AdditionalParam] = _row =>

{

return htCSV_AdditionalParam[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_GroupAD] = _row =>

{

return htCSV_GroupAD[keySEDProduct].ToString();

};

_insertValues.DynamicInsertValues[_ApprovalPerson] = _row =>

{

return htCSV_ApprovalPerson[keySEDProduct].ToString();

};

this.DataContext.CCCSEDProductsDiff.Insert(VI.WebRuntime.ResultSet.FromList(false, ""), 2147483647, _insertValues);

}

//Заполним Коллекцию продуктов, которые будут удалены из БД

VI.WebRuntime.ColumnInsertValues _insertValues1 = new VI.WebRuntime.ColumnInsertValues();

VI.WebRuntime.IDataColumn _ModuleSED1 = this.DataContext.CSVProductsDiff.GetColumn("ModuleSED");

VI.WebRuntime.IDataColumn _CategorySED1 = this.DataContext.CSVProductsDiff.GetColumn("CategorySED");

VI.WebRuntime.IDataColumn _ProductSED1 = this.DataContext.CSVProductsDiff.GetColumn("ProductSED");

VI.WebRuntime.IDataColumn _RoleSED1 = this.DataContext.CSVProductsDiff.GetColumn("RoleSED");

VI.WebRuntime.IDataColumn _AdditionalParam1 = this.DataContext.CSVProductsDiff.GetColumn("AdditionalParam");

VI.WebRuntime.IDataColumn _GroupAD1 = this.DataContext.CSVProductsDiff.GetColumn("ADGroup");

VI.WebRuntime.IDataColumn _ApprovalPerson1 = this.DataContext.CSVProductsDiff.GetColumn("ApprovalPerson");

foreach (string keySEDProduct in DbExceptCsv) {

_insertValues1.DynamicInsertValues[_ModuleSED1] = _row =>

{

return htDB_ModuleSED[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_CategorySED1] = _row =>

{

return htDB_CategorySED[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_ProductSED1] = _row =>

{

return htDB_ProductSED[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_RoleSED1] = _row =>

{

return htDB_RoleSED[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_AdditionalParam1] = _row =>

{

return htDB_AdditionalParam[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_GroupAD1] = _row =>

{

return htDB_GroupAD[keySEDProduct].ToString();

};

_insertValues1.DynamicInsertValues[_ApprovalPerson1] = _row =>

{

return htDB_ApprovalPerson[keySEDProduct].ToString();

};

this.DataContext.CSVProductsDiff.Insert(VI.WebRuntime.ResultSet.FromList(false, ""), 2147483647, _insertValues1);

}

//Сравним две Data Tables: dtCSV и CCCSEDProducts

/*_Form.ShowMessage("Hello");

_Form.ShowMessage(dtCSV.Rows.Count.ToString());        

_Form.ShowMessage(dtCSV.Rows[5][7].ToString());        

_Form.ShowMessage(this.DataContext.CCCSEDProducts.Rows[5][7].ToString());        

*/

//Заполним Коллекцию отличающихся продуктов между csv и БД

VI.WebRuntime.ColumnInsertValues _insertValues3 = new VI.WebRuntime.ColumnInsertValues();

VI.WebRuntime.IDataColumn _ModuleSED2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("ModuleSED");

VI.WebRuntime.IDataColumn _CategorySED2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("CategorySED");

VI.WebRuntime.IDataColumn _ProductSED2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("ProductSED");

VI.WebRuntime.IDataColumn _RoleSED2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("RoleSED");

VI.WebRuntime.IDataColumn _AdditionalParam2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("AdditionalParam");

VI.WebRuntime.IDataColumn _GroupAD2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("ADGroup");

VI.WebRuntime.IDataColumn _ApprovalPerson2 = this.DataContext.CCCSEDProductsDiff1.GetColumn("ApprovalPerson");

foreach (string stri in dbKeySEDProduct) {

try {string.Compare(htCSV_GroupAD[stri].ToString(),htDB_GroupAD[stri].ToString());}

catch {continue;}

if (string.Compare(htCSV_GroupAD[stri].ToString(),htDB_GroupAD[stri].ToString()) != 0 || string.Compare(htCSV_ApprovalPerson[stri].ToString(),htDB_ApprovalPerson[stri].ToString()) != 0) {

//_Form.ShowMessage("Ключ: " + stri + " Значение группы в файле: " + htCSV_GroupAD[stri].ToString() + " Значение группы в БД: " + htDB_GroupAD[stri].ToString() + " Значение согласующего в файле:" + htCSV_ApprovalPerson[stri].ToString() + " Значение согласующего в БД: " + htDB_ApprovalPerson[stri].ToString());

_insertValues3.DynamicInsertValues[_ModuleSED2] = _row =>

{

return htDB_ModuleSED[stri].ToString();

};

_insertValues3.DynamicInsertValues[_CategorySED2] = _row =>

{

return htDB_CategorySED[stri].ToString();

};

_insertValues3.DynamicInsertValues[_ProductSED2] = _row =>

{

return htDB_ProductSED[stri].ToString();

};

_insertValues3.DynamicInsertValues[_RoleSED2] = _row =>

{

return htDB_RoleSED[stri].ToString();

};

_insertValues3.DynamicInsertValues[_AdditionalParam2] = _row =>

{

return htDB_AdditionalParam[stri].ToString();

};

_insertValues3.DynamicInsertValues[_GroupAD2] = _row =>

{

if (string.Compare(htCSV_GroupAD[stri].ToString(),htDB_GroupAD[stri].ToString()) != 0 ) {return htDB_GroupAD[stri].ToString() + " -> " + htCSV_GroupAD[stri].ToString();}

else {return htDB_GroupAD[stri].ToString();}

};

_insertValues3.DynamicInsertValues[_ApprovalPerson2] = _row =>

{

if ( string.Compare(htCSV_ApprovalPerson[stri].ToString(),htDB_ApprovalPerson[stri].ToString()) != 0) {return htDB_ApprovalPerson[stri].ToString() + " -> " + htCSV_ApprovalPerson[stri].ToString();}

else {return htDB_ApprovalPerson[stri].ToString();}

};

this.DataContext.CCCSEDProductsDiff1.Insert(VI.WebRuntime.ResultSet.FromList(false, ""), 2147483647, _insertValues3);

}

}        

//Заполним коллекцию CSVValidated для отображения формы с детальными данными, что валидация пройдена

if (CsvErrors.Count == 0) {

VI.WebRuntime.ColumnInsertValues _insertValues2 = new VI.WebRuntime.ColumnInsertValues();

VI.WebRuntime.IDataColumn _Valid = this.DataContext.CSVValidated.GetColumn("Valid");

_insertValues2.DynamicInsertValues[_Valid] = _row =>

{

return "hh";

};

this.DataContext.CSVValidated.Insert(VI.WebRuntime.ResultSet.FromList(false, ""), 2147483647, _insertValues2);

}

}

//-------------------------------------------------

//Удалим все файлы во временной директории СЭД

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(_Connection.GetConfigParm("Custom\SED\CsvDirTemp"));

foreach (System.IO.FileInfo file in di.GetFiles()) {

file.Delete();

}

//-------------

//Переместим файл csv из временной директрории в рабочую для синхронизации.

string CsvDirTemp = _Connection.GetConfigParm("Custom\SED\CsvDirTemp");

string CsvDir = _Connection.GetConfigParm("Custom\SED\CsvDir");

string CsvFileName = _Connection.GetConfigParm("Custom\SED\CsvFileName");

string CsvFilePath = CsvDir + "\" + CsvFileName;

string CsvFilePathTemp = CsvDirTemp + "\" + CsvFileName;

if (System.IO.File.Exists(CsvFilePath)) {

System.IO.File.Delete(CsvFilePath);

}

System.IO.File.Move(CsvFilePathTemp, CsvFilePath);

IVI_Common_UserMessageAdd SaveFileInform = _UserSession.ApplicationInfo.CreateComponent\<IVI_Common_UserMessageAdd>();

SaveFileInform.MessageType = "Success";

SaveFileInform.MessageText = "Файл сохранен в рабочей директории для синхронизации с АСУД";

SaveFileInform.TableStore = this.TableStore.GetChildTableStore(_Module, (this.TableStore.Name + "_SaveFileInform"));

SaveFileInform.GetAction(ct);

//------

//Удалим все файлы во временной директории СЭД

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(_Connection.GetConfigParm("Custom\SED\CsvDirTemp"));

foreach (System.IO.FileInfo file in di.GetFiles()) {

file.Delete();

}