DataTable already belongs to this DataSet Error working with dataset - asp.net-3.5

i have dataset that fills data from three tables. here i just want to populate data of menu bar from database.
private DataSet GetData()
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = from m in db.Menus
where (m.IsActive == true)
select new
{
MenuID = m.MenuID,
MenuName = m.MenuName,
MenuLocation = m.MenuLocation
};
DataSet myDataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("MenuID", typeof(int)));
dt.Columns.Add(new DataColumn("MenuName", typeof(string)));
dt.Columns.Add(new DataColumn("MenuLocation", typeof(string)));
foreach (var item in query)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["MenuID"] = item.MenuID.ToString();
dr["MenuName"] = item.MenuName.ToString();
if (item.MenuLocation != null)
{
dr["MenuLocation"] = item.MenuLocation.ToString();
}
dt.Rows.Add(dr);
}
}
myDataSet.Tables.Add(dt);
var query1 = from c in db.CategoryMenus
where (c.IsActive == true)
select new
{
CategoryID = c.CategoryMenuID,
CategoryMenuName = c.CategoryMenuName,
CategoryMenuLocation = c.CategoryMenuLocation
};
dt.Columns.Add(new DataColumn("CategoryID", typeof(int)));
dt.Columns.Add(new DataColumn("CategoryMenuName", typeof(string)));
dt.Columns.Add(new DataColumn("CategoryMenuLocation", typeof(string)));
foreach (var item in query1)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["CategoryID"] = item.CategoryID.ToString();
dr["CategoryMenuName"] = item.CategoryMenuName.ToString();
if (item.CategoryMenuLocation != null)
{
dr["CategoryMenuLocation"] = item.CategoryMenuLocation.ToString();
}
dt.Rows.Add(dr);
}
}
//Line 80
myDataSet.Tables.Add(dt);
var query2 = from s in db.SubCategoryMenus
where (s.IsActive == true)
select new
{
SubCategoryID = s.SubCategoryMenuId,
SubCategoryMenuName = s.SubCategoryMenuName,
SubCategoryMenuLocation = s.SubCategoryMenuLocation
};
dt.Columns.Add(new DataColumn("SubCategoryID", typeof(int)));
dt.Columns.Add(new DataColumn("SubCategoryMenuName", typeof(string)));
dt.Columns.Add(new DataColumn("SubCategoryMenuLocation", typeof(string)));
foreach (var item in query2)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["SubCategoryID"] = item.SubCategoryID.ToString();
dr["SubCategoryMenuName"] = item.SubCategoryMenuName.ToString();
if (item.SubCategoryMenuLocation != null)
{
dr["SubCategoryMenuLocation"] = item.SubCategoryMenuLocation.ToString();
}
dt.Rows.Add(dr);
}
}
myDataSet.Tables.Add(dt);
return myDataSet;
}
}
from the second query while it iterates and add row to this tables then erro occured like:
Server Error in '/EasyWeb' Application.
DataTable already belongs to this DataSet.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: DataTable already belongs to this DataSet.
Source Error:
Line 78: }
Line 79: }
Line 80: myDataSet.Tables.Add(dt);
Line 81: var query2 = from s in db.SubCategoryMenus
Line 82: where (s.IsActive == true)
Source File: f:\EasyWeb\MenuControl.ascx.cs Line: 80
Stack Trace:
[ArgumentException: DataTable already belongs to this DataSet.]
System.Data.DataTableCollection.BaseAdd(DataTable table) +4825888
System.Data.DataTableCollection.Add(DataTable table) +112
MenuControl.GetData() in f:\EasyWeb\MenuControl.ascx.cs:80
MenuControl.Page_Load(Object sender, EventArgs e) in f:\EasyWeb\MenuControl.ascx.cs:20
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Control.LoadRecursive() +141
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

You need to name the tables after getting the copy from your method and before adding it to the DataSet.
Like this
dt.TableName = "A";
myDataSet.Tables.Add(dt);

ok i found just need different tables for that.
like
Datatable dt=new Datatable("Menu");
DataTable dt1 = new DataTable("Category");
DataTable dt2 = new DataTable("SubCategory");

Related

How to Repeat Previous Actions in Exception in EF 6

I am having a problem with repeating previous operations when there is an error in the SaveChanges method of Entity Framework.
Below is the code block
public static int SaveChangesTask(this DbContext db)
{
int result = -1;int countLoop = 0;
bool continueLoop = true;
var modifiedOrAddedEntities = db.ChangeTracker.Entries().Where(a => a.State != EntityState.Detached
&& a.State != EntityState.Unchanged).ToList();
while (continueLoop && countLoop<3)
{
try
{
result= db.SaveChanges();
continueLoop = false;
}
catch(Exception ex)
{
string error = ex.ToSystemException();
if(error.ToLowerInvariant().Contains("ORA-00060".ToLowerInvariant()) || error.ToLowerInvariant().Contains("deadlock"))
{
foreach (var item in modifiedOrAddedEntities)
{
db.Entry(item).State = item.State;
}
countLoop++;
Random rnd = new Random();
System.Threading.Thread.Sleep(rnd.Next(1, 5)* 1000);
}
else
{
throw ex;
}
}
}
return result;
}
But when I want to add old tracking objects to context, Entity Framework Throws Exception like that
"The entity type DbEntityEntry is not part of the model for the current context"

Crm plugin update fails

I have created two new fields named "Price" for quote and quote product and I want to update the second every time I update the first.
Here is my code:
protected void ExecutePostAccountUpdateContacts(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
string oldPrice = "";
string newPrice = "";
IPluginExecutionContext context = localContext.PluginExecutionContext;
IOrganizationService service = localContext.OrganizationService;
var ServiceContext = new OrganizationServiceContext(service);
ITracingService tracingService = localContext.TracingService;
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
Entity entity = (Entity)context.InputParameters["Target"];
Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains(this.preImageAlias)) ? context.PreEntityImages[this.preImageAlias] : null;
// get the post entity image
Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains(this.postImageAlias)) ? context.PostEntityImages[this.postImageAlias] : null;
if (preImageEntity.Attributes.Contains("Price"))
{
oldPrice = (string)preImageEntity.Attributes["Price"];
}
if (postImageEntity.Attributes.Contains("Price"))
{
newPrice = (string)postImageEntity.Attributes["Price"];
}
if (newPrice != oldPrice)
{
try
{
//Create query to get the related contacts
var res = from c in ServiceContext.CreateQuery("Products")
where c["parentQuoteid"].Equals(entity.Id)
select c;
foreach (var c in res)
{
Entity e = (Entity)c;
e["Price"] = newPrice;
ServiceContext.UpdateObject(e);
}
ServiceContext.SaveChanges();
}
catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}
}
}
}
Although you haven't asked a question, your query isn't quite right. So I am assuming your plugin fails when querying for product with a parentquoteid.
Not all linq operators are implemented, also , pass the entity logical name to the create query as a parameter, so instead of Products, just product. There is no out of the box field called parentquoteid, are you missing your custom attribute prefix?
var res = from c in ServiceContext.CreateQuery("product")
where c.GetAttributeValue<Guid>("new_parentquoteid") == entity.Id
select c;

How to implement boolean retrieval using hitcollector in below scenario

I am running my code on TREC documents and right now implementing scoring scheme to get number of relevant documents. However now i want to implement boolean retrieval, I am trying to use HitCollector.
below is my code..
public class BatchSearch {
private BatchSearch() {}
/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
String usage =
"Usage:\tjava BatchSearch [-index dir] [-simfn similarity] [-field f] [-queries file]";
if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)\n");
System.exit(0);
}
String index = "index";
String field = "contents";
String queries = null;
String simstring = "default";
for(int i = 0;i < args.length;i++) {
if ("-index".equals(args[i])) {
index = args[i+1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i+1];
i++;
} else if ("-queries".equals(args[i])) {
queries = args[i+1];
i++;
} else if ("-simfn".equals(args[i])) {
simstring = args[i+1];
i++;
}
}
Similarity simfn = null;
if ("default".equals(simstring)) {
simfn = new DefaultSimilarity();
} else if ("bm25".equals(simstring)) {
simfn = new BM25Similarity();
} else if ("dfr".equals(simstring)) {
simfn = new DFRSimilarity(new BasicModelP(), new AfterEffectL(), new NormalizationH2());
} else if ("lm".equals(simstring)) {
simfn = new LMDirichletSimilarity();
}
if (simfn == null) {
System.out.println(usage);
System.out.println("Supported similarity functions:\ndefault: DefaultSimilary (tfidf)");
System.out.println("bm25: BM25Similarity (standard parameters)");
System.out.println("dfr: Divergence from Randomness model (PL2 variant)");
System.out.println("lm: Language model, Dirichlet smoothing");
System.exit(0);
}
IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(simfn);
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41);
BufferedReader in = null;
if (queries != null) {
in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
} else {
in = new BufferedReader(new InputStreamReader(new FileInputStream("queries"), "UTF-8"));
}
QueryParser parser = new QueryParser(Version.LUCENE_41, field, analyzer);
while (true) {
String line = in.readLine();
if (line == null || line.length() == -1) {
break;
}
line = line.trim();
if (line.length() == 0) {
break;
}
String[] pair = line.split(" ", 2);
Query query = parser.parse(pair[1]);
doBatchSearch(in, searcher, pair[0], query, simstring);
}
reader.close();
}
/**
* This function performs a top-1000 search for the query as a basic TREC run.
*/
public static void doBatchSearch(BufferedReader in, IndexSearcher searcher, String qid, Query query, String runtag)
throws IOException {
// Collect enough docs to show 5 pages
TopDocs results = searcher.search(query, 1000);
ScoreDoc[] hits = results.scoreDocs;
HashMap<String, String> seen = new HashMap<String, String>(1000);
int numTotalHits = results.totalHits;
int start = 0;
int end = Math.min(numTotalHits, 1000);
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String docno = doc.get("docno");
// There are duplicate document numbers in the FR collection, so only output a given
// docno once.
if (seen.containsKey(docno)) {
continue;
}
seen.put(docno, docno);
System.out.println(qid+" Q0 "+docno+" "+i+" "+hits[i].score+" "+runtag);
}
}
}
The scoring is done in doBatchSearch and now i want to implement HitCollector here.

ORA-06550 , wrong number or types of arguments in call to Oracle Stored Procedure

I have a stored procedure which has one in parameter and one out parameter as follows:
create or replace procedure worker_name (w_id in number, w_first out worker.first_name%type) is
Begin
select first_name into w_first
from worker
where worker_id = w_id;
end;
Code to call this stored procedure:
public DataTable <b>GetEmployeeName</b>(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter(":employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.<b>GetData</b>("macw_conv.worker_name", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}
public DataTable <b>GetData</b>(string query, ArrayList parameters,string queryType)
{
//DataTable dt = new DataTable();
try
{
_con =
new OracleConnection(Oradb);
_con.Open();
_cmd = new OracleCommand(query, _con);
if (_cmd.Connection.State == ConnectionState.Open)
{
if (queryType == "SP" && parameters != null)
{
_cmd.CommandType = CommandType.StoredProcedure;
if (parameters.Count > 0)
{
foreach (OracleParameter param in parameters)
{
_cmd.Parameters.Add(param);
}
}
}
}
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(_cmd);
da.Fill(ds);
if (ds.Tables.Count > 0)
{
return ds.Tables[0];
}
return null;
}
I guess I'm unable to see the obvious error. It's something about the data type mismatch between the out parameter in the stored procedure and output parameter in the code. Any kind of help is appreciated.
Thanks!
I figured out the issue: it was because the datatype of the variable that is saving the out parameter was not handled properly. I changed the code as follows:
try
{
_con = new OracleConnection(Oradb);
_cmd = _con.CreateCommand();
_cmd.CommandType = CommandType.StoredProcedure;
_cmd.CommandText = "macw_conv.worker_name";
OracleParameter inobj1 = _cmd.Parameters.Add("w_id", OracleDbType.Int32,50);
inobj1.Direction = ParameterDirection.Input;
inobj1.Value = _employeeID;
OracleParameter inobj2 = _cmd.Parameters.Add("w_last", OracleDbType.Int32, 50);
inobj2.Direction = ParameterDirection.Input;
inobj2.Value = String.IsNullOrEmpty(_lastName) ? null : _lastName;
OracleParameter outobj = _cmd.Parameters.Add("w_first", OracleDbType.Varchar2, 50);
outobj.Direction = ParameterDirection.Output;
_con.Open();
_cmd.ExecuteNonQuery();
_employeeName = ((OracleString) _cmd.Parameters[1].Value).ToString();
_cmd.Dispose();
_con.Close();
}
catch (OracleException ex)
{
Console.WriteLine(ex.Message);
}
return _employeeName;
Try
public DataTable GetEmployeeName(int _employeeID)
{
ArrayList arrEmployeeName = new ArrayList();
OracleParameter paramEmployeeId = new OracleParameter("employeeid", _employeeID);
arrEmployeeName.Add(paramEmployeeId);
OracleParameter paramEmployeeFirst = new OracleParameter("first", OracleDbType.Varchar2, ParameterDirection.Output);
arrEmployeeName.Add(paramEmployeeFirst);
DataLayer obj = new DataLayer();
DataTable tblEmployee = obj.GetData("macw_conv.worker_name(:1,:2)", arrEmployeeName, "SP");
if (tblEmployee.Rows.Count > 0)
{
return tblEmployee;
}
return null;
}

Execute stored procedure in Entity Framework, return List<DataTable> or DataSet

How do I modify the below method to return a List< DataTable> or a DataSet? I want to make it generic so it can return multiple resultsets from the database.
public static DataTable ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
var dt = new DataTable();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dt;
}
I ended up doing it like this -
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
var ds = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
reader.NextResult() should technically work. Here is the modified version:
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
DataSet dataSet = new DataSet();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
do
{
DataTable dt = new DataTable();
dt.Load(reader);
dataSet.Tables.Add(dt);
}
while (reader.NextResult());
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dataSet;
}