Sharing the code below please any one tell what is the error
try
{
OrganoCollection = new ObservableCollection<HRM_Organogram>();
foreach (var jobTypeDef in LobjWsHrmOeLinking.GetUnOccupiedRecordSearch())
{
OrganoCollection.Add(jobTypeDef);
}
}
catch (Exception ex)
{
ApplicationClass.Message(ex.Message, "Error", MessageType.Error);
}
And the Definition of function is giving below this function is used throug a wcf service
public List<HRM_Organogram> GetUnOccupiedRecordSearch()
{
List<HRM_Organogram> p_objMaster = new List<HRM_Organogram>();
try
{
using (var context = new CMS_ERPEntities())
{
context.ContextOptions.LazyLoadingEnabled = false;
var l_objMaster = (from OG in context.HRM_Organogram
join OE in context.HRM_OELinking
on OG.OrganoID equals OE.OrganoID
where OE.FinalizeStatus == true
select OG.OrganoID).ToList();
p_objMaster = (from OG in context.HRM_Organogram
where !l_objMaster.Contains(OG.OrganoID)
&& OG.Isactive==true
select OG).ToList();
}
}
catch (Exception ex)
{
throw ex;
}
return p_objMaster;
}
And The Error is:
Argument Type CMS_ERPClient.Service.HRM_OeLinking.HRM_Organogram is
Not Assianable to CMS_ERPClient.Service.HRM_OrganGram.HRM_OrganGram
There is more than one type called HRM_Organogram, one in the namespace CMSERPClient_Service.HRM_OElinking and one in the namespace CMS_ERPClientService.HRMORganogram. You are trying to add the latter to a collection of the former. Check your using statements.
And if I may say, your namespace and type names are awful! Refactor them to have more descriptive and distinctive names and you'll have a much more enjoyable coding experience!
My guess is one is a DTO type and one is a Model type, and you'll have a mapper somewhere to do a conversion. I also guess this sentence won't mean a whole lot to you - try to see how these types are used elsewhere and look for code that has using statements for both and converts one to the other.
Related
I'm trying to create a Class with a method where I can load a file (In this case CSV) and convert it to any predefined datastructure within my program.
With a lot of help from other articles I've written the following code, But I got stuck. (so the placed code has errors).
The idea is that I use the method CsvSerialise, the input is a byteArray and transform it to an object list where the input is what kind of output type I want.
If anyone has some Ideas, please give them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Text.RegularExpressions;
namespace DocumentArchiveV2.Util
{
public class CsvSerialiser
{
public List<Output> CsvSerialise<Output, DestinationFormat>(byte[] csvData, Type destinationType)
{
try
{
List<List<string>> lislistCsvData = BinaryDataToList(csvData);
List<string> columnNames = lislistCsvData[0];
List< destinationType > = new List<DestinationFormat>();
// loop over de regels / records
for (int i = 1; i < lislistCsvData.Count - 1; i++)
{
var Instance = Activator.CreateInstance(destinationType);
var properties = Instance.GetType().GetProperties();
foreach (var property in properties)
{
int index = columnNames.FindIndex(x => x == property.Name);
if (index >= 0)
{
PropertyInfo propertyInfo = destinationType.GetProperty(lislistCsvData[i][index]);
Type propertyType = propertyInfo.GetType();
var geconverteerdeWaarde = VindPropertyNaam(propertyType, lislistCsvData[i][index]);
propertyInfo.SetValue(propertyInfo, geconverteerdeWaarde);
}
}
}
}
catch (Exception)
{
throw;
}
}
public object VindPropertyNaam(Type type, string popertyName)
{
try
{
var parse = type.GetMethod("Parse", new[] { typeof(string) });
if (parse == null) throw new NotSupportedException();
return parse.Invoke(null, new object[] { popertyName });
}
//or don't catch
catch (Exception)
{
return null;
}
}
private object LoadRecord(Type propertyType)
{
throw new NotImplementedException();
}
private List<List<string>> BinaryDataToList(byte[] csvData)
{
try
{
List<List<string>> serialised = new List<List<string>>();
foreach (var line in Regex.Split(Encoding.ASCII.GetString(csvData), "\r\n"))
{
string[] splittedLine = line.Split(';');
serialised.Add(line.Split(';').ToList());
}
return serialised;
}
catch (Exception ex)
{
DiagnoseLib.Logging.Logger.Error(ex.Message);
return null;
}
}
}
}
I pretty much dislike your code due to numereous violations of OOP practicies known to be the best. However, since it is not the question you're asking, I'd like to ignore those and focus on what you'd like to get right now.
So basically what you're doing is called "parsing". It's all about taking a somehow formatted (CSV in your case) text and converting to internal data structures. Since yoy eager to come up with generic solution (which by itself is perfect thing to do, though as well much harder), you objectively don't know what kind of data structure it gonna be. Hence, you need be able to configure this process. How? Typically, with help of higer order functions. Something like new DataStructureBuilder<TDataStructure>((environment, result) => result.Text = environemt["Text"]). It is far from being a real code, however gives you an idea: there is a generic datastructure of (assuming) TDataStructure type and you specify the way it should be filled with data explicitly. environment stands for parsed text (that very moment, when you read the values you'd like you data strutctures to ship further, however yet those are stored into raw form of dictionaries, lists, hashsets, etc.).
I found where I went wrong.
I was trying to return a generic type while it should have been an objecttype
Thanks all who have given insight.
public List<object> CsvSerialise(byte[] csvData, object destinationType)
{
// The rest of the code with some small adjustments
}
I am trying use LINQ in a C# program to get information from a database. I have found a lot of examples showing basic to advanced queries, but i get a error when i try to build. See basic LINQ example below:
The class with the LINQ
public class StdFy
{
public object GetStdFy(DrillholeEntities ddb)
{
try
{
var myList = ((from t1 in ddb.DTM_QAQC_BLK_STD from t2 in ddb.DTM_STANDARDSASSAY.Where(x=> t1.STANDARDID==x.STANDARDID && t1.ASSAYVALUE==x.STANDARDVALUE)
select new
{
CHECKID = t1.CHECKID,
STANDARDID = t1.STANDARDID,
PRIORITY = t1.ASSAY_PRIORITY,
NAME = t1.ASSAYNAME,
ASSAYVALUE = t1.ASSAYVALUE,
STANDARDVALUE = t2.STANDARDVALUE,
STANDARDDEVIATION = t2.STANDARDDEVIATION,
NORMALIZACION = (t2.STANDARDVALUE- t1.ASSAYVALUE)/ t2.STANDARDDEVIATION,
LABJOBNO = t1.LABJOBNO,
LOADDATE = t1.RETURNDATE
})).OrderBy(x => x.LOADDATE).ToList();
return myList;
}
catch (Exception)
{
throw new NotImplementedException();
}
}
}
and then
DrillholeEntities ddb;
StdFy stdFy = new StdFy();
using (ddb = new DrillholeEntities())
{
IOrderedEnumerable<DTM_QAQC_BLK_STD> datosTodos;
datosTodos = stdFy.GetStdFy(ddb);
}
and when i buuild the project i get the error
Severity Code Description Project File Line Suppression State
Error CS0266 Cannot implicitly convert type 'object' to
'System.Linq.IOrderedEnumerable'.
An explicit conversion exists (are you missing a
cast?) Inspinia_MVC5 C:\Users\chachl9\Documents\Visual Studio
2015\Projects\MVC5_Full_Version\Inspinia_MVC5\Controllers\GraphsController.cs 55 Active
You are returning a list of objects of an anonymous type by
select new { ... }
thats may the reason why you use object as return type of your method.
Than you assign the return value to a specific type. Thats the reason why the exception ist thrown.
To get this work I would implement a new class which contains all your needed properties. Use it in
select new MyNewClass { Property1 = ...}
change the return type of your method from object to IEnumerable<MyNewClass>. Aswell the variable you assign the return value to.
You should also use PascalCase properties as mentioned by Gert Arnold in the comments.
Also mixing the select from in where LINQ syntax with the Lambda methods .Where(x => ...) make it hard to read.
I'm facing a very strange problem on two easy webapi methods:
I have lot of methods that are used to retrive masterdata from db.
They are all similars and they all read tables with same structures.
I really don't know why for example this method works:
this works
[HttpGet]
//[Authorize]
[Route("offertsource/get")]
public IHttpActionResult api_MasterData_OffertSource_GET()
{
var res = new List<mdOffertSource>();
try
{
res = (from c in db.mdOffertSources.OrderBy(x => x.OffertSource)
select new mdOffertSource() { idOffertSource = c.idOffertSource, Code = c.Code, OffertSource = c.OffertSource }).ToList();
return Ok(res);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
and this doesn't work:
NOT working code
[HttpGet]
//[Authorize]
[Route("offertstatus/get")]
public IHttpActionResult api_MasterData_OffertStatus_GET()
{
var res = new List<mdOffertStatus>();
try
{
res = (from c in db.mdOffertStatus.OrderBy(x => x.intOrder).ThenBy(x => x.OffertStatus)
select new mdOffertStatus() { idOffertStatus = c.idOffertStatus, Code = c.Code, OffertStatus = c.OffertStatus }).ToList();
return Ok(res);
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
I have lot of methods similar to the first one working and only the second one below is not working.
If I test it, i get this error:
Explicit construction of entity type 'XionDB.mdOffertStatus' in query is not allowed.
I have already tried to remove the table mdOffertStatus from the dbml file and to add again it but I face the same problem...
This is very strange.
Thanks to support
Your OfferSources table isn't empty, is it? That would cause the Select not to be called and avoid the error thrown in the second method.
(Would leave this as a comment but don't have enough points.)
I solved my problem by deleting the dbml file and adding it again...
Before I tryied to remove and add again the table mdOffertStatus but nothing changed, dropping the dbml and adding it again fixed the problem.
May be there was some mess in the solution...
Thanks to support
What is the proper way to create a variable that will house a list of anonymous objects that are generated through a LINQ query while keeping the variable declaration outside of a try/catch and the assignment being handled inside of a try/catch?
At the moment I'm declaring the variable as IEnumberable<object>, but this causes some issues down the road when I'm trying to use it later...
i.e.
var variableDeclaration;
try{
...
assignment
...
}catch...
EDIT:
If it's relevant (don't think it is) the list of objects is being returned as a Json result from an MVC3 action. I'm trying to reduce the time that some using statements are open with the DB as I'm having some performance issues that I'm trying to clear up a bit. In doing some of my testing I came across this issue and can't seem to find info on it.
EDIT 2:
If I could request the avoidance of focusing on LINQ. While LINQ is used the question is more specific to the scoping issues associated with Anonymous objects. Not the fact that LINQ is used (in this case) to generate them.
Also, a couple of answers have mentioned the use of dynamic while this will compile it doesn't allow for the usages that I'm needing later on the method. If what I'm wanting to do isn't possible then at the moment the answer appears to be to create a new class with the definition that I'm needing and to use that.
It's possible to get around this by creating a generic Cast method as outlined by Jon Skeet here. It will work and give you the intellisense you want. But, at this point, what's wrong with creating a custom type for your linq method?
public class MyClass
{
public int MyInt { get; set; }
}
IEnumerable<MyClass> myClass =
//Some Linq query that returns a collection of MyClass
Well, if you're using LINQ, the query is not evaluated unless materialized...
So, you might be able to:
var myQuery = //blah
try
{
myQuery = myQuery.ToList(); //or other materializing call
}
catch
{
}
Could you perhaps get away with using dynamic ??
dynamic variableDeclaration;
try
{
variableDeclaration = SomeList.Where(This => This == That);
}
catch { }
Not sure what this will affect further in your code block, but just a thought :)
If you are declaring the variable ahead of using it like a try/catch you can't use [var] as it is intendend. Instead you have to type the the variable.
var x = 0;
try{
x = SomethingReturningAnInt();
}
or
int x;
try{
x = SomethingReturningAnInt();
}
However in your case you don't really "know" what the method returns
var x = ...;
try{
x = Something();
}
catch{}
won't work
Option you have when you don't know the type in advance is use of dynamic:
dynamic x;
try{
x = Something();
}
catch{}
(But that feels like going back to VB4)
Another cheat: you can define variable locally (similarly to Jon's hack in Dave Zych answer) and than use it inside try/catch. As long as you can create the same anonymous item type before try-catch you are OK (as anonymous types wit the same field names and types are considered the same):
var myAnonymouslyType = Enumerable.Repeat(
new {Field1 = (int)1, Field2 = (string)"fake"}, 0);
try
{
myAnonymouslyType = ...(item =>
new {Field1 = item.Id, Field2=item.Text})...
}
...
This is safer option than covered in Jon's casting of anonymous types between functions because compiler will immediately find errors if types don't match.
Note: I'd vote for non-anonymous type if you have to go this way...
Note 2: depending on your actual need consider simply returning data from inside try/catch and having second return of default information outside.
This has vexed me for a while. In the end I've build some Generic helper methods where I can pass in the code that generates the anonymous objects, and the catch code as lamdas as follows
public static class TryCatch
{
public static T Expression<T>(Func<T> lamda, Action<Exception> onException)
{
try
{
return lamda();
}
catch(Exception e)
{
onException(e);
return default(T);
}
}
}
//and example
Exception throwexception = null;
var results = TryCatch.Expression(
//TRY
() =>
{
//simulate exception happening sometimes.
if (new Random().Next(3) == 2)
{
throw new Exception("test this");
}
//return an anonymous object
return new { a = 1, b = 2 };
} ,
//CATCH
(e) => { throwexception = e;
//retrow if you wish
//throw e;
}
);
https://gist.github.com/klumsy/6287279
I have a database with many single isolated tables, and I need to fill their contents to their Entities.
Currently I have for each and every table something like this:
try
{
using(DBContext context = new DBContext())
{
var vehicleTypes = context.VehicleTypes;
return vehicleTypes;
}
}
catch(Exception ex)
{
//handle error
}
What I'm seeking for is best described as something like this:
var vehicleTypes = context.GetEntitySet(VehicleEntity);
var buildingTypes = context.GetEntitySet(BuildingEntity);
where VehicleEntity, BuildingEntity (...) are entities from entity model.
I know I don't have this option explicitly, but something in that similar way would be nice. Extension method is also an option...
I'm working with EntityFramework 4.0, POCO Self Tracking Entities (without proxy).
Thanks
edit: My latest try was this:
public static IEnumerable<TEntity> GetTableContent<TEntity>() where TEntity:class
{
try
{
using (var context = new DBEntities())
{
var result = context.ExecuteStoreQuery<TEntity>("SELECT * FROM " + typeof(TEntity).Name); //the table names correspond to Entity type class names
return result;
}
}
catch (Exception ex)
{
//handle error...
}
}
but I get the error:
The data reader is incompatible with the specified 'DBEntities.MyEntity'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.
and that's true - the names don't match - but I figured it would've mapped the table from query based on edmx definition? How can I get this right?
Start with code which actually works before trying to make it "generic"
result = context.ExecuteStoreQuery<Something>("SELECT SOMETHING_ID AS ID, ..., FROM SOMETHING...");