I have an Oracle package that gives a list of facilities based on user ID. It is used to determine access. We have several projects that use this package already but they are all VB and WebForms - we are moving over to C# and MVC and this is the first project like that utilizing this package.
When attempting to run a query in the package, I get a System.InvalidOperationException: The number of parameters does not match number of values for stored procedure.
Procedure spec (I do not have access to the body and this part cannot be edited as it is used extensively in other applications):
Procedure GetFacilitiesByUser
(
p_EmpNo IN int,
cur_OUT out sys_refcursor
);
And my C#:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
namespace MvcApplication1.DataAccess
{
public class InpatientSecurity
{
public List<string> GetHospitals(int EmployeeNumber)
{
var response = new List<string>() { };
object[] _params = { EmployeeNumber };
IDataReader dr = ExecuteQuery(
"connection string",
"datawarehouse.Access.GetFacilitiesByUser",
_params
);
while (dr.Read())
{
response.Add("test");
}
return response;
}
private IDataReader ExecuteQuery(string provider, string procedure, params object[] args)
{
var _db = new OracleDatabase(provider);
object[] objArr = new object[args.Length];
args.CopyTo(objArr, 0);
if (args.Length > 1)
{
objArr[objArr.Length - 1] = System.DBNull.Value;
}
IDataReader reader = _db.ExecuteReader(procedure, objArr); /* Exception thrown here */
_db = null;
return reader;
}
}
}
I did not write the original VB code used to access this procedure, this is just a
As usual, I figured it out shortly after posting. The objArr array needs to be of length 2, I guess to take into account the ref cursor? Changing the following line in ExecuteQuery() fixed the issue.
Change this:
object[] objArr = new object[args.Length];
To this:
object[] objArr = new object[args.Length + 1];
Related
Following this link How to obtain a list of workspaces using Rally REST .NET
I tried the example however when I try to query against sub["Workspaces"] I get the error
RuntimeBinderException was unhandled;
The best overloaded method match for 'Rally.RestApi.RallyRestApi.Query(Rally.RestApi.Request)' has some invalid arguments
I cannot find any other ways to gather a list of workspaces from the subscription using the RallyApi dll for .Net which I obtained from the link provided.
Any help will be much appreciated.
Try to modify that code as follows:
Request wRequest = new Request(sub["Workspaces"]);
QueryResult queryResult = restApi.Query(wRequest);
Here is an entire app:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace Rest_v2._0_test
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//get the current subscription
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
//query the Workspaces collection
QueryResult queryResult = restApi.Query(wRequest);
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine( workspaceName + " " + workspaceReference);
}
}
}
}
I am using C# and the Entity Framework to access a MySQL database.
I am grabbing the results of a stored procedure, and trying to turn them into a list of objects, However whenever it comes to the part what references a table through a one to many relationship, it fails with the error
There is already an open DataReader associated with this Connection which must be closed first.
The code I am using is here:
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarHireCommon.DataObjects;
namespace CarHireServer
{
public class DatabaseHandler
{
protected static DatabaseHandler instance;
protected carhireEntities1 Entities;
public static DatabaseHandler GetInstance()
{
if (instance == null)
instance = new DatabaseHandler();
return instance;
}
public DatabaseHandler()
{
Entities = new carhireEntities1();
}
public List<AvailableAssets> GetAvailableAssets(DateTime startDate, DateTime endDate)
{
ObjectResult<asset> res = Entities.GetAvailableAssets(startDate, endDate);
List<AvailableAssets> list = new List<AvailableAssets>();
foreach(var assetRes in res)
{
AvailableAssets asset=new AvailableAssets();
asset.id = assetRes.id;
asset.Comment = assetRes.comments;
asset.Make = assetRes.make;
asset.Model = assetRes.model;
asset.Fuel = assetRes.fuel;
asset.LongTerm = assetRes.longterm;
// This is the line that errors:
asset.Category = assetRes.category.categoryname;
list.Add(asset);
}
return list;
}
}
}
I have allready told it which table the Stored Procedure returns, and the other variables access correctly.
I have also tried doing it the long way with:
var cat = from b in Entities.categories where b.id == assetRes.category_id select b;
asset.Category = cat.FirstOrDefault<category>().categoryname;
However the thing still exceptions with the exact same error.
I found C# Entity Framework: There is already an open DataReader associated with this Connection which must be closed first which will probably help you exactly with this question.
GL!
Below is what I use to log into the database using linq and then I use C# expressions to gather the data I want. The next thing I want to do is convert this data into an XML any Ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
namespace VcacManagementTools.BuildProfiles
{
public static class BuildProfileTools
{
public static ICollection<string> GetExistingBuildProfileNames(string repositoryHostname,
string repositoryUsername,
string repositoryPassword)
{
var url = string.Format("https://{0}/repository/data/ManagementModelEntiti.svc", repositoryHostname);
var managementModelClient = new DynamicOps.ManagementModel.ManagementModelEntities(new Uri(url))
{
Credentials = new NetworkCredential(repositoryUsername, repositoryPassword)
};
return managementModelClient
.GlobalProfiles
.Select(gp => gp.ProfileName)
.ToList();
The Output I recieve is a list of values
If I understood you well, you want to take the data (the list contains the data from the database) and put it in XML file. I used variables to show where to put each data.
In case you have an XML:
try
{
doc = XDocument.Load(spath, LoadOptions.SetBaseUri);
foreach(String propertyData in dataList)
{
XElement root = new XElement(ElementName);
root.Add(new XElement("property1", propertyData));
doc.Element(MainElement).Add(root);
}
doc.Save(spath);
}
catch (Exception)
{
}
I am trying to develop a simple application with a simple SQLite database. I am new to C# so I may have missed something obvious. When I run the following code, it returns the error:
SQL logic error or missing database.No such table: Customer
(edit: Yes I have created that table within the database, I performed/confirmed this using the sqlite command prompt
Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace TestPersonDatabase
{
public partial class DBconnection : Form
{
SQLiteDatabase sqliteDb = new SQLiteDatabase();
public DBconnection()
{
InitializeComponent();
}
// Using SQLite
private void btnInsert_Click(object sender, EventArgs e)
{
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("CustomerId", this.fieldInsertId.Text);
data.Add("FirstName", this.fieldInsertFName.Text);
data.Add("LastName", this.fieldInsertLName.Text);
data.Add("MobileNumber", this.fieldInsertDob.Text);
try
{
sqliteDb.Insert("Customer", data);
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
}
class SQLiteDatabase
{ String dbConnection;
public SQLiteDatabase()
{
dbConnection = "Data Source=" + (global::TestPersonDatabase.Properties.Resources.database);
}
public bool Insert(String tableName, Dictionary<String, String> data)
{
String columns = "";
String values = "";
Boolean returnCode = true;
foreach (KeyValuePair<String, String> val in data)
{
columns += String.Format(" {0},", val.Key.ToString());
values += String.Format(" '{0}',", val.Value);
}
columns = columns.Substring(0, columns.Length - 1);
values = values.Substring(0, values.Length - 1);
try
{
this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
}
catch (Exception fail)
{
MessageBox.Show(fail.Message);
returnCode = false;
}
return returnCode;
}
Obviously the code above is two different classes put together. Just made it easier for you to read.
It seems like it cannot find the database file. But I appear to have linked it up correctly (its in the solution resources). Any help would be very much appreciated as I am a bit stumped! Thanks :)
You never opened your sql connection try:
dbConnection.Open(); //Initiate connection to the db
It doesn't look like you've created the table.
Before you input any data you'll need to create the table using something like:
this.ExecuteNonQuerySQL("CREATE TABLE Customers(CustomerID INTEGER PRIMARY KEY, sPassword TEXT, CustomerName TEXT);");
Once you've created the table the insert code you have should work fine.
I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project