system missing method exception. why this happening - c#

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.

The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

Related

SaveChanges() doesn't insert any records to database

I'm using Entity Framework to add new records to the database, everything goes ok without any errors, but I don't see the new record in the database.
Update code works, but insert code doesn't work. No errors appear, but no records are inserted into the database.
My code :
var DBs2 = ConnectionTools.OpenConn();
DBs2.Configuration.AutoDetectChangesEnabled = false;
DBs2.Configuration.ValidateOnSaveEnabled = false;
var resList = CreatedSerials.Where(u => u.Item4 == VID).ToList();
foreach (var r in resList)
{
// if serial id ==0 => new then add it as new
if ( r.Item7 == 0)
{
try
{
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
ss.Add(purchasesItemSerials);
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
}
else
{
var DBs350 = ConnectionTools.OpenConn();
var UpdateSerial = DBs350.purchases_item_seriels.Find(r.Item7);
UpdateSerial.pitem_ID = pitem_ID;
UpdateSerial.stitems_ID = r.Item1;
UpdateSerial. pmain_ID = PurchasesID;
UpdateSerial.pitem_virtualID = r.Item4;
UpdateSerial.pis_CustomSerial = r.Item2;
UpdateSerial.pis_ExpireDate = r.Item3;
UpdateSerial.pis_Statues = r.Item6;
UpdateSerial.ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID"));
UpdateSerial.Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice"));
DBs350.SaveChanges();
}
}
try
{
DBs2.purchases_item_seriels.AddRange(ss);
DBs2.SaveChanges();
}
catch (Exception eeeeee)
{
Msg.Show("", eeeeee.ToString(), 0);return;
}
I also tried :
DBs2.Configuration.AutoDetectChangesEnabled = true;
DBs2.Configuration.ValidateOnSaveEnabled = true;
but again: no data is inserted, no errors appear
I also tried :
int returnCode = DBs2.SaveChanges();
and returnCode = 0
**I also tried : inserting just a single item then SaveChanges **
// if this serial is new
var NewSerialresList = CreatedSerials.Where(u => u.Item4 == VID && u.Item7 == 0).ToList();
if (NewSerialresList.Count() > 0)
{
var ss = new List<purchases_item_seriels>();
foreach (var r in NewSerialresList)
{
try
{
mrsalesdbEntities DBs002 = new mrsalesdbEntities();
var purchasesItemSerials = new purchases_item_seriels()
{
pitem_ID = pitem_ID,
stitems_ID = r.Item1,
pmain_ID = PurchasesID,
pitem_virtualID = r.Item4,
pis_CustomSerial = r.Item2,
pis_ExpireDate = r.Item3,
pis_Statues = 0,
ss_StoreID = Convert.ToInt32(gridView1.GetRowCellValue(ItemImdex, "storeID")),
Purchases_Price = Convert.ToDecimal(gridView1.GetRowCellValue(ItemImdex, "item_NetSmallestUnitPrice")),
};
//ss.Add(purchasesItemSerials);
DBs002.purchases_item_seriels.Add(purchasesItemSerials);
DBs002.SaveChanges();
}
catch (Exception ex)
{
Msg.Show("", ex.ToString(), 0);
}
}
int CC = ss.Count();
}
i use this function to change the connection variables at run-time :
public static mrsalesdbEntities OpenConn()
{
mrsalesdbEntities MrSalesContext = new mrsalesdbEntities();
MrSalesContext.ChangeDatabase
(
initialCatalog: myconn.database,
port: Convert.ToUInt32( myconn.port),
userId: myconn.uid,
password: myconn.password,
dataSource: myconn.server
);
return MrSalesContext;
}
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
uint port = 3307,
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "mrsalesdbEntities")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new MySqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.Database = initialCatalog;
if ((port) != 0)
sqlCnxStringBuilder.Port = port;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.Server = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
//sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
}

System.OutOfMemoryExeption C#

When I'm running my application and load a file(25MB) through it, everything runs just fine.
But when I try loading a file(160MB) I get a System.OutOfMemoryExeption.
Although I have been able to load the larger file at some point in time.
Is there anyway to fix this? If so, any help would be much appreciated!
My Code that loads the files:
private void openFile (string fileName)
{
List<Structs.strValidData> _header1 = new List<Structs.strValidData>();
List<Structs.strValidData> _header2 = new List<Structs.strValidData>();
List<Structs.strValidData> _header3 = new List<Structs.strValidData>();
List<Structs.strValidData> _header4 = new List<Structs.strValidData>();
var textBoxArray = new[]
{
textBoxResStart_Status1,
textBoxResStart_Status2,
textBoxResStart_Status3,
textBoxResStart_Status4,
textBoxResStart_Status5,
textBoxResStart_Status6,
textBoxResStart_Status7,
textBoxResStart_Status8,
};
var radioButtonArray = new[]
{
radioButtonResStart_SelectStr1,
radioButtonResStart_SelectStr2,
radioButtonResStart_SelectStr3,
radioButtonResStart_SelectStr4,
radioButtonResStart_SelectStr5,
radioButtonResStart_SelectStr6,
radioButtonResStart_SelectStr7,
radioButtonResStart_SelectStr8,
};
readCSV read;
read = new readCSV();
strInfo = default(Structs.strInfo);
strData = default(Structs.strData);
strSetup = default(Structs.strSetup);
strValidData = new List<Structs.strValidData>();
readID = default(Structs.ReadID);
try
{
strInfo = read.loadInfo(fileName);
strData = read.loadData(fileName);
strSetup = read.loadSetup(fileName);
readID = read.loadID(fileName);
strValidData = read.loadValidData(fileName);
var Str1 = read.loadStr1(fileName);
var Str235678 = read.loadStr235678(fileName);
var Str4 = read.loadStr4(fileName);
foreach (Structs.strValidData items in strValidData)
{
if (items.Str1_ValidData == true)
{
Str1_headers.Add(items);
}
if (items.Str2_ValidData == true ||
items.Str3_ValidData == true ||
items.Str5_ValidData == true ||
items.Str6_ValidData == true ||
items.Str7_ValidData == true ||
items.Str8_ValidData == true)
{
Str235678_headers.Add(items);
}
if (items.Str4_ValidData == true)
{
Str4_headers.Add(items);
}
}
Str1_data = combineData(Str1, Str1_headers);
Str4_data = combineData(Str4, Str4_headers);
var Str235678_CombinedData = combineData(Str235678, Str235678_headers);
foreach (Structs.strValidData items in Str235678_CombinedData)
{
if (items.Str2_ValidData == true)
{
Str2_data.Add(items);
}
if (items.Str3_ValidData == true)
{
Str3_data.Add(items);
}
if (items.Str5_ValidData == true)
{
Str5_data.Add(items);
}
if (items.Str6_ValidData == true)
{
Str6_data.Add(items);
}
if (items.Str7_ValidData == true)
{
Str7_data.Add(items);
}
if (items.Str8_ValidData == true)
{
Str8_data.Add(items);
}
}
strInfo = read.loadInfo(openDialog.FileName);
strData = read.loadData(openDialog.FileName);
strSetup = read.loadSetup(openDialog.FileName);
readID = read.loadID(openDialog.FileName);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
error.logSystemError(err);
}
}
Here are the ReadCSV() code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FileHelpers;
using FileHelpers.Events;
namespace Reading_Files
{
public class readCSV
{
public int strCnt = 0;
private readCSVprogressForm _waitForm;
public List<Structs.strDataImport> copyList(List<strData> copyFrom)
{
List<Structs.strDataImport> list = new List<Structs.strDataImport>();
list.AddRange(copyFrom.Select(s => copyListContents(s)));
return list;
}
public Structs.strDataImport copyListContents(strData copyFrom)
{
Structs.strDataImport data = new Structs.strDataImport();
data.sCD_TimeCP2711 = copyFrom.sCD_TimeCP2711;
data.sCD_TimeCX9020_1 = copyFrom.sCD_TimeCX9020_1;
data.sCD_TimeCX9020_2 = copyFrom.sCD_TimeCX9020_2;
data.rCD_CX9020_1_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_1_TimeDiff_DataLow);
data.rCD_CX9020_2_TimeDiff_DataLow = (Int32)(copyFrom.rCD_CX9020_2_TimeDiff_DataLow);
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumUpper = copyFrom.iCD_NumUpper;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.iCD_NumLower = copyFrom.iCD_NumLower;
data.bCD_1_Status = copyFrom.bCD_1_Status;
data.bCD_1_Overrange = copyFrom.bCD_1_Overrange;
data.iCD_1_Str_ID = copyFrom.iCD_1_Str_ID;
data.rCD_1_Value = copyFrom.rCD_1_Value;
data.bCD_2_Status = copyFrom.bCD_2_Status;
data.bCD_2_Overrange = copyFrom.bCD_2_Overrange;
data.iCD_2_Str_ID = copyFrom.iCD_2_Str_ID;
data.rCD_2_Value = copyFrom.rCD_2_Value;
data.bCD_3_Status = copyFrom.bCD_3_Status;
data.bCD_3_Overrange = copyFrom.bCD_3_Overrange;
data.iCD_3_Str_ID = copyFrom.iCD_3_Str_ID;
data.iCD_3_RawData = copyFrom.iCD_3_RawData;
data.rCD_3_Value = copyFrom.rCD_3_Value;
data.bCD_4_Status = copyFrom.bCD_4_Status;
data.bCD_4_Overrange = copyFrom.bCD_4_Overrange;
data.iCD_4_Str_ID = copyFrom.iCD_4_Str_ID;
data.iCD_4_RawData = copyFrom.iCD_4_RawData;
data.rCD_4_Value = copyFrom.rCD_4_Value;
data.bCD_5_Status = copyFrom.bCD_5_Status;
data.bCD_5_Overrange = copyFrom.bCD_5_Overrange;
data.iCD_5_Str_ID = copyFrom.iCD_5_Str_ID;
data.iCD_5_RawData = copyFrom.iCD_5_RawData;
data.rCD_5_Value = copyFrom.rCD_5_Value;
data.bCD_6_Status = copyFrom.bCD_6_Status;
data.bCD_6_Overrange = copyFrom.bCD_6_Overrange;
data.iCD_6_Str_ID = copyFrom.iCD_6_Str_ID;
data.iCD_6_RawData = copyFrom.iCD_6_RawData;
data.rCD_6_Value = copyFrom.rCD_6_Value;
data.bCD_7_Status = copyFrom.bCD_7_Status;
data.bCD_7_Overrange = copyFrom.bCD_7_Overrange;
data.iCD_7_Str_ID = copyFrom.iCD_7_Str_ID;
data.iCD_7_RawData = copyFrom.iCD_7_RawData;
data.rCD_7_Value = copyFrom.rCD_7_Value;
data.bCD_8_Status = copyFrom.bCD_8_Status;
data.bCD_8_Overrange = copyFrom.bCD_8_Overrange;
data.iCD_8_Str_ID = copyFrom.iCD_8_Str_ID;
data.iCD_8_RawData = copyFrom.iCD_8_RawData;
data.rCD_8_Value = copyFrom.rCD_8_Value;
data.bCD_9_Status = copyFrom.bCD_9_Status;
data.bCD_9_Overrange = copyFrom.bCD_9_Overrange;
data.iCD_9_Str_ID = copyFrom.iCD_9_Str_ID;
data.iCD_9_RawData = copyFrom.iCD_9_RawData;
data.rCD_9_Value = copyFrom.rCD_9_Value;
data.bCD_10_Status = copyFrom.bCD_10_Status;
data.bCD_10_Overrange = copyFrom.bCD_10_Overrange;
data.iCD_10_Str_ID = copyFrom.iCD_10_Str_ID;
data.iCD_10_RawData = copyFrom.iCD_10_RawData;
data.rCD_10_Value = copyFrom.rCD_10_Value;
data.bCD_11_Status = copyFrom.bCD_11_Status;
data.bCD_11_Overrange = copyFrom.bCD_11_Overrange;
data.iCD_11_Str_ID = copyFrom.iCD_11_Str_ID;
data.iCD_11_RawData = copyFrom.iCD_11_RawData;
data.rCD_11_Value = copyFrom.rCD_11_Value;
data.bCD_12_Status = copyFrom.bCD_12_Status;
data.bCD_12_Overrange = copyFrom.bCD_12_Overrange;
data.iCD_12_Str_ID = copyFrom.iCD_12_Str_ID;
data.iCD_12_RawData = copyFrom.iCD_12_RawData;
data.rCD_12_Value = copyFrom.rCD_12_Value;
data.bCD_13_Status = copyFrom.bCD_13_Status;
data.bCD_13_Overrange = copyFrom.bCD_13_Overrange;
data.iCD_13_Str_ID = copyFrom.iCD_13_Str_ID;
data.iCD_13_RawData = copyFrom.iCD_13_RawData;
data.rCD_13_Value = copyFrom.rCD_13_Value;
data.bCD_14_Status = copyFrom.bCD_14_Status;
data.bCD_14_Overrange = copyFrom.bCD_14_Overrange;
data.iCD_14_Str_ID = copyFrom.iCD_14_Str_ID;
data.iCD_14_RawData = copyFrom.iCD_14_RawData;
data.rCD_14_Value = copyFrom.rCD_14_Value;
data.bCD_15_Status = copyFrom.bCD_15_Status;
data.bCD_15_Overrange = copyFrom.bCD_15_Overrange;
data.iCD_15_Str_ID = copyFrom.iCD_15_Str_ID;
data.iCD_15_RawData = copyFrom.iCD_15_RawData;
data.rCD_15_Value = copyFrom.rCD_15_Value;
data.bCD_16_Status = copyFrom.bCD_16_Status;
data.bCD_16_Overrange = copyFrom.bCD_16_Overrange;
data.iCD_16_Str_ID = copyFrom.iCD_16_Str_ID;
data.iCD_16_RawData = copyFrom.iCD_16_RawData;
data.rCD_16_Value = copyFrom.rCD_16_Value;
data.bCD_17_Status = copyFrom.bCD_17_Status;
data.bCD_17_Overrange = copyFrom.bCD_17_Overrange;
data.iCD_17_Str_ID = copyFrom.iCD_17_Str_ID;
data.iCD_17_RawData = copyFrom.iCD_17_RawData;
data.rCD_17_Value = copyFrom.rCD_17_Value;
data.bCD_18_Status = copyFrom.bCD_18_Status;
data.bCD_18_Overrange = copyFrom.bCD_18_Overrange;
data.iCD_18_Str_ID = copyFrom.iCD_18_Str_ID;
data.iCD_18_RawData = copyFrom.iCD_18_RawData;
data.rCD_18_Value = copyFrom.rCD_18_Value;
data.bCD_19_Status = copyFrom.bCD_19_Status;
data.bCD_19_Overrange = copyFrom.bCD_19_Overrange;
data.iCD_19_Str_ID = copyFrom.iCD_19_Str_ID;
data.rCD_19_Value = copyFrom.rCD_19_Value;
data.bCD_20_Status = copyFrom.bCD_20_Status;
data.bCD_20_Overrange = copyFrom.bCD_20_Overrange;
data.iCD_20_Str_ID = copyFrom.iCD_20_Str_ID;
data.rCD_20_Value = copyFrom.rCD_20_Value;
return data;
}
public Structs.ReaStrID load_ID(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strIDSelector);
var data = engine.ReadFile(FileName);
Structs.ReaStrID structure = new Structs.ReaStrID();
foreach (strID filteredData in data)
{
structure.steID[0] = filteredData._1_Ste_ID;
structure.Status[0] = filteredData._1_Status;
structure.steID[1] = filteredData._2_Ste_ID;
structure.Status[1] = filteredData._2_Status;
structure.steID[2] = filteredData._3_Ste_ID;
structure.Status[2] = filteredData._3_Status;
structure.steID[3] = filteredData._4_Ste_ID;
structure.Status[3] = filteredData._4_Status;
structure.steID[4] = filteredData._5_Ste_ID;
structure.Status[4] = filteredData._5_Status;
}
return structure;
}
public Structs.strInfo loadInfo(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strInfoSelector);
var data = engine.ReadFile(FileName);
Structs.strInfo structure = new Structs.strInfo();
foreach (strInfo filteredData in data)
{
structure.Date = filteredData.Date;
structure.Description1 = filteredData.Description1;
structure.Description2 = filteredData.Description2;
structure.Description3 = filteredData.Description3;
}
return structure;
}
public Structs.strData loadData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strDataSelector);
var data = engine.ReadFile(FileName);
Structs.strData structure = new Structs.strData();
foreach (strData filteredData in data)
{
structure.iMDstr_var1_TypeID = filteredData.iMDstr_var1_TypeID;
structure.rMDstr_var1_Lenght = filteredData.rMDstr_var1_Lenght;
structure.iMDstr_var2_TypeID = filteredData.iMDstr_var2_TypeID;
structure.rMDstr_var2_Lenght = filteredData.rMDstr_var2_Lenght;
structure.iMDstr_var3_TypeID = filteredData.iMDstr_var3_TypeID;
structure.rMDstr_var3_Lenght = filteredData.rMDstr_var3_Lenght;
structure.iMDstr_var4_TypeID = filteredData.iMDstr_var4_TypeID;
structure.rMDstr_var4_Lenght = filteredData.rMDstr_var4_Lenght;
}
return structure;
}
public Structs.strSetup loadSetup(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strID),
typeof(strData),
typeof(strSetup),
typeof(strData));
engine.RecordSelector = new RecordTypeSelector(strSetupSelector);
var data = engine.ReadFile(FileName);
Structs.strSetup structure = new Structs.strSetup();
foreach (strSetup filteredData in data)
{
structure.sSSstr_Sens = filteredData.sSSstr_Sens;
structure.bSSstr_S1_A = filteredData.bSSstr_S1_A;
structure.iSSstr_S1_B = filteredData.iSSstr_S1_B;
structure.sSSstr_S1_C = filteredData.sSSstr_S1_C;
structure.rSSstr_S1_D = filteredData.rSSstr_S1_D;
structure.bSSstr_S2_A = filteredData.bSSstr_S2_A;
structure.iSSstr_S2_B = filteredData.iSSstr_S2_B;
structure.sSSstr_S2_C = filteredData.sSSstr_S2_C;
structure.rSSstr_S2_D = filteredData.rSSstr_S2_D;
structure.bSSstr_S3_A = filteredData.bSSstr_S3_A;
structure.iSSstr_S3_B = filteredData.iSSstr_S3_B;
structure.sSSstr_S3_C = filteredData.sSSstr_S3_C;
structure.iSSstr_S3_D = filteredData.iSSstr_S3_D;
}
return structure;
}
public List<Structs.str1> load1(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strID),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str1Selector);
var data = engine.ReadFile(FileName);
List<Structs.str1> list = new List<Structs.str1>();
int i = 0;
foreach (str1 data1 in data)
{
Structs.str1 structure = new Structs.str1();
structure.rGL_1_L_Positive = data1.rGL_1_L_Positive;
structure.rGL_1_L_Negative = data1.rGL_1_L_Negative;
structure.rGL_1_R_Positive = data1.rGL_1_R_Positive;
structure.rGL_1_R_Negative = data1.rGL_1_R_Negative;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.str4> load4(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strData),
typeof(strValidData),
typeof(strStartNum),
typeof(str1),
typeof(str4));
engine.RecordSelector = new RecordTypeSelector(str4Selector);
var data = engine.ReadFile(FileName);
List<Structs.str4> list = new List<Structs.str4>();
int i = 0;
foreach (str4 data4 in data)
{
Structs.str4 structure = new Structs.str4();
structure.rGL_4_1 = data4.rGL_4_1;
structure.rGL_4_2 = data4.rGL_4_2;
structure.rGL_4_3 = data4.rGL_4_3;
structure.rGL_4_4 = data4.rGL_4_4;
structure.rGL_4_5 = data4.rGL_4_5;
structure.rGL_4_6 = data4.rGL_4_6;
structure.rGL_4_7 = data4.rGL_4_7;
structure.rGL_4_8 = data4.rGL_4_8;
list.Add(structure);
i++;
}
return list;
}
public List<Structs.strValidData> loadValidData(string FileName)
{
var engine = new MultiRecordEngine(typeof(strInfo),
typeof(strData),
typeof(strSetup),
typeof(strID),
typeof(strData),
typeof(strValidData));
engine.RecordSelector = new RecordTypeSelector(strValidDataSelector);
var data = engine.ReadFile(FileName);
List<Structs.strValidData> list = new List<Structs.strValidData>();
int i = 0;
foreach (strValidData strValidData in data)
{
Structs.strValidData structure = new Structs.strValidData();
structure._name = String.Format("strItem {0}", i + 1);
structure._index = i;
structure.str1_ValidData = strValidData.str1_ValidData;
structure.str2_ValidData = strValidData.str2_ValidData;
structure.str3_ValidData = strValidData.str3_ValidData;
structure.str4_ValidData = strValidData.str4_ValidData;
structure.str5_ValidData = strValidData.str5_ValidData;
structure.str6_ValidData = strValidData.str6_ValidData;
structure.str7_ValidData = strValidData.str7_ValidData;
structure.str8_ValidData = strValidData.str8_ValidData;
structure.str9_ValidData = strValidData.str9_ValidData;
list.Add(structure);
i++;
}
return list;
}
public List<List<Structs.strDataImport>> loadstrDataAsync(string FileName)
{
var engine_Data = new FileHelperAsyncEngine<strData>();
engine_Data.BeforeReadRecord += BeforeEventAsync;
engine_Data.AfterReadRecord += AfterEventAsync;
engine_Data.Progress += ReadProgress;
List<strData> list = new List<strData>();
List<List<Structs.strDataImport>> list2D = new List<List<Structs.strDataImport>>();
using (engine_Data.BeginReadFile(FileName))
{
var prevRowNo = 0;
var j = 0;
strCnt = 0;
foreach (strData filteredData in engine_Data)
{
if (prevRowNo > filteredData.RowNo)
{
list2D.Add(copyList(list));
list.Clear();
}
prevRowNo = filteredData.RowNo;
list.Add(filteredData);
}
list2D.Add(copyList(list));
}
return list2D;
}
private Type strIDSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA .STATUS .STRID **"))
return typeof(strID);
else
{
return null;
}
}
private Type InfoSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_FILE **"))
return typeof(strInfo);
else
{
return null;
}
}
private Type strDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_DATA **"))
return typeof(strData);
else
{
return null;
}
}
private Type strSetupSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_SETUP **"))
return typeof(strSetup);
else
{
return null;
}
}
private Type strValidDataSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_VALID_DATA **"))
return typeof(strValidData);
else
{
return null;
}
}
private Type StartNumSelector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_START_NUMBER **"))
return typeof(strStartNum);
else
{
return null;
}
}
private Type str1Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_1 **"))
return typeof(str1);
else
{
return null;
}
}
private Type str4Selector(MultiRecordEngine engine, string recordLine)
{
if (recordLine.Length == 0)
return null;
if (recordLine.Contains("** #_4 **"))
return typeof(str4);
else
{
return null;
}
}
private void BeforeEventAsync(EngineBase engine, BeforeReadEventArgs<strData> e)
{
if (e.RecordLine != "")
{
if (Char.IsDigit(e.RecordLine, 0))
{
}
else
{
e.SkipThisRecord = true;
}
}
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void AfterEventAsync(EngineBase engine, AfterReadEventArgs<strData> e)
{
if (e.RecordLine.Contains("** #_VALID_DATA **;"))
{
e.SkipThisRecord = true;
}
}
private void ReadProgress(object sender, ProgressEventArgs e)
{
ShowWaitForm("Opening file." + "\n" + "\n" + "Please wait...", "Open File");
_waitForm.progressBar1.Value = Convert.ToInt16(e.Percent);
}
public void ShowWaitForm(string message, string caption)
{
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new readCSVprogressForm();
_waitForm.ShowMessage(message);
_waitForm.Text = caption;
_waitForm.TopMost = true;
_waitForm.Show();
_waitForm.Refresh();
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
}
Given the comments, it sounds like the problem is really that you're using structs extensively. These should almost certainly be classes for idiomatic C#. See the design guidelines for more details of how to pick between these.
At the moment, you're loading all the values in a big List<T>. Internally, that has an array - so it's going to be an array of your struct type. That means all the values are required to be in a single contiguous chunk of memory - and it sounds like that chunk can't be allocated.
If you change your data types to classes, then a contiguous chunk of memory will still be required - but only enough to store references to the objects you create. You'll end up using slightly more data overall (due to per-object overhead and the references to those objects) but you won't have nearly as strict a requirement on allocating a single big chunk of memory.
That's only one reason to use classes here - the reason of "this just isn't a normal use of structs" is a far bigger one, IMO.
As an aside, I'd also very strongly recommend that you start following .NET naming conventions, particularly around the use of capitalization and avoiding underscores to separate words in names. (There are other suggestions for improving the code in the question too, and I'd advise reading them all carefully.)

Validation error when attempting to SaveChanges to table

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.
This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}
You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik

Controller is returning blank View in my website

public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.

How to properly dispose objects created for Ldap search using ADODB ADsDSObject provider

I am looking for the best way how to lookup LDAP directory for users by given criteria. At the moment the best performance seems to offer usage of ADsDSObject provider. The code will run in ASP.NET web site.
I would like to confirm how to properly dispose the resources. Here is the code used at the moment. Is the code releasing resources correctly or need to be improved?
public static List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
ADODB.Command adoCommand = new ADODB.Command();
ADODB.Connection adoConnection = new ADODB.Connection();
ADODB.Recordset adoResultSet = new ADODB.Recordset();
adoConnection.ConnectionString = connectionString;
adoConnection.Open();
adoCommand.ActiveConnection = adoConnection;
adoCommand.CommandText = BuildSelectStatmentFrom(criteria);
object dummy = Type.Missing;
try
{
adoResultSet = adoCommand.Execute(out dummy, ref dummy, 0);
if (adoResultSet != null)
{
while (adoResultSet.EOF == false)
{
LookupValues value = new LookupValues();
for (int i = 0; i < adoResultSet.Fields.Count; i++)
{
switch (adoResultSet.Fields[i].Name)
{
case "a-foreignGivenName":
value.FirstName = (adoResultSet.Fields[i].Value).ToString();
break;
case "a-foreignSn":
value.LastName = (adoResultSet.Fields[i].Value).ToString();
break;
}
}
usersMatchingCriteria.Add(value);
adoResultSet.MoveNext();
}
}
}
finally
{
if (adoResultSet != null)
{
adoResultSet.Close();
adoResultSet = null;
}
if (adoConnection != null)
{
adoConnection.Close();
adoConnection = null;
}
}
return usersMatchingCriteria;
}
I found equivalent and even a bit faster to use classes from System.DirectoryServices.Protocols namespace. Equivalent code using .NET classes
public List<LookupValues> FindBy(LdapSearchCriteria criteria)
{
List<LookupValues> usersMatchingCriteria = new List<LookupValues>();
NetworkCredential credentials = new NetworkCredential(connectionDetails.UserName, connectionDetails.Password, connectionDetails.Domain);
LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier(connectionDetails.Server, connectionDetails.Port, false, false);
using (LdapConnection connection = CreateConnection(directoryIdentifier))
{
connection.Bind(credentials);
SearchRequest search = CreateSearchRequest(criteria);
SearchResponse response = connection.SendRequest(search) as SearchResponse;
foreach (SearchResultEntry entry in response.Entries)
{
LookupValues foundUser = GetUserDetailsFrom(entry);
usersMatchingCriteria.Add(foundUser);
}
}
return usersMatchingCriteria;
}

Categories

Resources