how to connect MS Access (x86) DB using Microsoft Jscript running in x64 bit Environment - ms-access-2013

I am trying to connect an MS Access (x86) database (*.mdb) from a third party application which is x64 bit and supports Microsoft JScript ...
My Code Looks like below:
function testaccess(sender : System.Object, cmdArgs : Ico.Gwx.CommandExecutionEventArgs)
{
try
{
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\EC_SCADA\\Configurations\\ModbusEthernetConfig\\EC_ModbusOPC_Config.mdb;Persist Security Info=False";
var cnn = System.Data.OleDb.OleDbConnection;
var cmd = System.Data.OleDb.OleDbCommand;
var qr1 : String = "Select IPAddress from Devices where Name = 'Machine1'";
var da : System.Data.OleDb.OleDbDataAdapter;
var dt : System.Data.DataTable;
//MessageBox.Show("Variables defined");
cnn = new System.Data.OleDb.OleDbConnection(strConnectionString);
//MessageBox.Show("cnn defined");
cmd = new System.Data.OleDb.OleDbCommand(qr1, cnn);
//MessageBox.Show("cmd defined");
da = new System.Data.OleDb.OleDbDataAdapter(cmd);
cnn.Open();
MessageBox.Show("Connection Opened");
da.Fill(dt);
MessageBox.Show("Code End");
}
catch (e)
{ MessageBox.Show("OOPS!!! something went wrong, Kindly try again!!!!");
}
}
First of all the Code editor itself throws error at line "da = new..." as "More than one constructor matches this argument list"
Can anyone help on this??

I found couple of issues here.
[1] missed to define dataTable like
"dt = new System.Data.DataTable"
[2] I downloaded and installed "Microsoft Access Database Engine 2010 Redistributable - 64 bit" from Below link, installed on my computer and the code just works fine.
[https://www.microsoft.com/en-gb/download/details.aspx?id=13255]

Related

The provider is not compatible with the version of oracle (ASP.NET Core MVC)

I'm really frustrated and i do not know what to do.
I'm trying to connect to an Oracle 11g database but every time I try to connect Visual Studio 2019 throws an error message. I already tried a lot of different things but nothing really helped me.
I have already made sure the app set to run in 32 bit mode in the IIS console. I still can't figure out why is not working.
By the way, here is my code:
readonly string connectionString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROD)));User Id=xxx;Password=xxxx;"
public IEnumerable<Person>GetPersonList
{
var listPerson = new List<Person>();
using (OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select * from myview", con);
cmd.Connection = con;
cmd.InitialLOBFetchSize = 1000;
cmd.CommandType = CommandType.Text;
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var list = new Person();
list.CODE = Convert.ToInt32(dr["CODE"].ToString());
list.NAME = dr["NAME"].ToString();
list.LASTNAME = dr["LASTNAME"].ToString();
listPerson.Add(list);
}
con.Close();
}
return listPerson;
}
What should I do?
My problem was solved: needed to install instant client for Oracle 11g and everything worked just fine

How To Use ODAC With Visual Studio 2015 Call Oracle DB (Stored-Function)

There is a strange problem that has been found in Oracle DB with Visual Studio by my project. First I open my Toad to check Oracle function like as below picture:
When I have put 3 parameter's value into SF_GET_COMP_SVAL, it is working ,and then when I have tried it in my project as following, it also works very well.
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleDbContext"].ToString()))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = "select PG_AIS.SF_GET_COMP_SVAL('3','2','1') from dual";
try
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
However it can't be working when I use Paramters mode like as following code
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual"; cmd.Parameters.Add("a2", "1");
cmd.Parameters.Add("a3", "2");
cmd.Parameters.Add("a1", "3");
why????
I wasted half day and have found the ODAC problem in my case, why can't insert into data with paramters in Visual Studio platform , because of parameters name , if fact in my MySql and MSSql there don't need to follow the sequence with parameter , but unfortunately in the Oracle it can't change ordering ,the parameter's depends on index sequence so that you can change any parameter's name
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("a1", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
or
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("xx", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
parameter a1 or xx is the same (depends on index sequence not parameter name)
both codes can get the same result.
PS: Hopefully it will be modify soon by Oracle Provider.
I have found another method to deal with this problem , please try it
OracleCommand command = new OracleCommand(query, connection)
{ CommandType = CommandType.Text, BindByName = true };
PS:http://www.codeproject.com/Articles/208176/Gotcha-sharp-Using-Named-Parameters-with-Oracl <-- it could be a great way to deal with

MSMQQueueManagement error when creating a class instance

I have a routine to get the counts on a MSMQ queue. I have been using this code for years on 2003 and 2008 server with no trouble. I am now updating the code to run on 2012R2 server and to test this I am compiling with VS2013 premium on Windows 8.1 using the following code:
String sPath;
Int32 nCount = 0;
Object oPath, oNull, oServer;
String [] sParts;
Char [] sSeps = { ':', '\\' };
MSMQ.MSMQQueueManagementClass mgmt;
//
// The configuration path is a standard .net path. For DCOM we need the
// DIRECT= prefixed
//
sPath = "DIRECT=OS:" + m_QueueConfig.QueuePath;
//
// Split the string looking for the sever name
//
sParts = sPath.Split( sSeps, StringSplitOptions.RemoveEmptyEntries );
//
// Get the count from the server
//
mgmt = new MSMQ.MSMQQueueManagementClass();
try
{
oPath = sPath;
oNull = Type.Missing;
if( sParts.Length < 2 || sParts[1] == "." )
oServer = Environment.MachineName;
else
oServer = sParts[1];
mgmt.Init( ref oServer, ref oNull, ref oPath );
nCount = mgmt.MessageCount;
}
catch( Exception )
{
nCount = 0;
}
finally
{
Marshal.ReleaseComObject( mgmt );
}
return nCount;
This will error on the "mgmt. = new MSMQ.MSMQQueueManagementClass()" statement with the following error:
Retrieving the COM class factory for component with CLSID {33B6D07E-F27D-42FA-B2D7-BF82E11E9374} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
Looking in the HKEY_CLASSES_ROOT hive I can find 39CE96FE-F4C5-4484-A143-4C2D5D324229 which pointed to the MQOA.DLL in system32, but not the CLSID from the error, which is what a 80040154 is.
I have tried creating a new typelib using the system32/mqoa.dll but I still get the same error. So what I am doing wrong?
According to the registry I have MSMQ version 6.2.9200 installed and it works with my application I just can't get the management interface to load.
mgmt.Init( ref oServer, ref oNull, ref oPath );
The MSMQQueueManagement interface does not have an Init() method. Looks to me like you are mixing up different coclasses. The 39CE96FE guid is for MSMQManagement, the 33B6D07E guid is for MSMQQueueManagment. The latter one is not supposed to appear in the registry so the runtime error is entirely expected. Fix:
mgmt = new MSMQ.MSMQManagement();
// etc..

How to automate Package Manager Console in Visual Studio 2013

My specific problem is how can I automate "add-migration" in a build process for the Entity Framework. In researching this, it seems the mostly likely approach is something along the lines of automating these steps
Open a solution in Visual Studio 2013
Execute "Add-Migration blahblah" in the Package Manager Console (most likely via an add-in vsextention)
Close the solution
This initial approach is based on my own research and this question, the powershell script ultimately behind Add-Migration requires quite a bit of set-up to run. Visual Studio performs that setup automatically when creating the Package Manager Console and making the DTE object available. I would prefer not to attempt to duplicate that setup outside of Visual Studio.
One possible path to a solution is this unanswered stack overflow question
In researching the NuGet API, it does not appear to have a "send this text and it will be run like it was typed in the console". I am not clear on the lines between Visual Studio vs NuGet so I am not sure this is something that would be there.
I am able to find the "Pacakage Manager Console" ironically enough via "$dte.Windows" command in the Package Manager Console but in a VS 2013 window, that collection gives me objects which are "Microsoft.VisualStudio.Platform.WindowManagement.DTE.WindowBase". If there is a way stuff text into it, I think I need to get it to be a NuGetConsole.Implementation.PowerConsoleToolWindow" through reviewing the source code I am not clear how the text would stuffed but I am not at all familiar with what I am seeing.
Worst case, I will fall back to trying to stuff keys to it along the lines of this question but would prefer not to since that will substantially complicate the automation surrounding the build process.
All of that being said,
Is it possible to stream commands via code to the Package Manager Console in Visual Studio which is fully initialized and able to support an Entity Framework "add-migration" command?
Thanks for any suggestions, advice, help, non-abuse in advance,
John
The approach that worked for me was to trace into the entity framework code starting in with the AddMigrationCommand.cs in the EntityFramework.Powershell project and find the hooks into the EntityFramework project and then make those hooks work so there is no Powershell dependency.
You can get something like...
public static void RunIt(EnvDTE.Project project, Type dbContext, Assembly migrationAssembly, string migrationDirectory,
string migrationsNamespace, string contextKey, string migrationName)
{
DbMigrationsConfiguration migrationsConfiguration = new DbMigrationsConfiguration();
migrationsConfiguration.AutomaticMigrationDataLossAllowed = false;
migrationsConfiguration.AutomaticMigrationsEnabled = false;
migrationsConfiguration.CodeGenerator = new CSharpMigrationCodeGenerator(); //same as default
migrationsConfiguration.ContextType = dbContext; //data
migrationsConfiguration.ContextKey = contextKey;
migrationsConfiguration.MigrationsAssembly = migrationAssembly;
migrationsConfiguration.MigrationsDirectory = migrationDirectory;
migrationsConfiguration.MigrationsNamespace = migrationsNamespace;
System.Data.Entity.Infrastructure.DbConnectionInfo dbi = new System.Data.Entity.Infrastructure.DbConnectionInfo("DataContext");
migrationsConfiguration.TargetDatabase = dbi;
MigrationScaffolder ms = new MigrationScaffolder(migrationsConfiguration);
ScaffoldedMigration sf = ms.Scaffold(migrationName, false);
}
You can use this question to get to the dte object and from there to find the project object to pass into the call.
This is an update to John's answer whom I have to thank for the "hard part", but here is a complete example which creates a migration and adds that migration to the supplied project (project must be built before) the same way as Add-Migration InitialBase -IgnoreChanges would:
public void ScaffoldedMigration(EnvDTE.Project project)
{
var migrationsNamespace = project.Properties.Cast<Property>()
.First(p => p.Name == "RootNamespace").Value.ToString() + ".Migrations";
var assemblyName = project.Properties.Cast<Property>()
.First(p => p.Name == "AssemblyName").Value.ToString();
var rootPath = Path.GetDirectoryName(project.FullName);
var assemblyPath = Path.Combine(rootPath, "bin", assemblyName + ".dll");
var migrationAssembly = Assembly.Load(File.ReadAllBytes(assemblyPath));
Type dbContext = null;
foreach(var type in migrationAssembly.GetTypes())
{
if(type.IsSubclassOf(typeof(DbContext)))
{
dbContext = type;
break;
}
}
var migrationsConfiguration = new DbMigrationsConfiguration()
{
AutomaticMigrationDataLossAllowed = false,
AutomaticMigrationsEnabled = false,
CodeGenerator = new CSharpMigrationCodeGenerator(),
ContextType = dbContext,
ContextKey = migrationsNamespace + ".Configuration",
MigrationsAssembly = migrationAssembly,
MigrationsDirectory = "Migrations",
MigrationsNamespace = migrationsNamespace
};
var dbi = new System.Data.Entity.Infrastructure
.DbConnectionInfo("ConnectionString", "System.Data.SqlClient");
migrationsConfiguration.TargetDatabase = dbi;
var scaffolder = new MigrationScaffolder(migrationsConfiguration);
ScaffoldedMigration migration = scaffolder.Scaffold("InitialBase", true);
var migrationFile = Path.Combine(rootPath, migration.Directory,
migration.MigrationId + ".cs");
File.WriteAllText(migrationFile, migration.UserCode);
var migrationItem = project.ProjectItems.AddFromFile(migrationFile);
var designerFile = Path.Combine(rootPath, migration.Directory,
migration.MigrationId + ".Designer.cs");
File.WriteAllText(designerFile, migration.DesignerCode);
var designerItem = project.ProjectItems.AddFromFile(migrationFile);
foreach(Property prop in designerItem.Properties)
{
if (prop.Name == "DependentUpon")
prop.Value = Path.GetFileName(migrationFile);
}
var resxFile = Path.Combine(rootPath, migration.Directory,
migration.MigrationId + ".resx");
using (ResXResourceWriter resx = new ResXResourceWriter(resxFile))
{
foreach (var kvp in migration.Resources)
resx.AddResource(kvp.Key, kvp.Value);
}
var resxItem = project.ProjectItems.AddFromFile(resxFile);
foreach (Property prop in resxItem.Properties)
{
if (prop.Name == "DependentUpon")
prop.Value = Path.GetFileName(migrationFile);
}
}
I execute this in my project template's IWizard implementation where I run a migration with IgnoreChanges, because of shared entites with the base project. Change scaffolder.Scaffold("InitialBase", true) to scaffolder.Scaffold("InitialBase", false) if you want to include the changes.

RFC on HttpWebRequest vs RESTSharp from Windows CE / Compact Framework 3.5

I created a simple WebAPI service in .NET4 and Visual Studio 2010.
I need to consume that service in a Windows CE / CF 3.5 app
I do have HttpWebRequest available to me, but am not sure if this is the way to go, or I should use RestSharp. Does anybody have insight/experience that would help me decide? I prefer not using 3rd party code when possible to avoid it, but am willing to do so if there is a clear advantage over the "raw" offerings.
Does anyone have, or know of, examples for accessing WebApi services using HttpWebRequest OR RestSharp from CF 3.5?
I have this code (adapted from from http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api) for sample WebAPI methods:
public class VendorItemsController : ApiController
{
VendorItem[] vendorItems = new VendorItem[]
{
new VendorItem { VendorId = "1", VendorItemId = "Tomato Soup", ItemId = "Groceries", PackSize = 1 },
new VendorItem { VendorId = "2", VendorItemId = "V8", ItemId = "Groceries", PackSize = 6 },
new VendorItem { VendorId = "3", VendorItemId = "Garlic", ItemId = "Groceries", PackSize = 1 },
};
public IEnumerable<VendorItem> GetAllProducts()
{
return vendorItems;
}
public VendorItem GetProductById(string id)
{
var vendorItem = vendorItems.FirstOrDefault((p) => p.VendorId == id);
if (vendorItem == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return vendorItem;
}
}
...but don't know how to consume this using, if possible, HttpWebRequest.
Note: HttpClient is not available to me (HttpWebRequest is, though).
UPDATE
I start the VS2010 app that has the WebAPI method; but when I run the VS2008 Windows CE / Compact Framekwork 3.5 app with this code:
Uri _baseAddress = new Uri("http://localhost:48614/");
string localFile = "fetchedVendorItems.txt";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_baseAddress + "api/vendoritems/");
req.Method = "GET";
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
// Retrieve response stream and wrap in StreamReader
Stream respStream = resp.GetResponseStream();
StreamReader rdr = new StreamReader(respStream);
// Create the local file
StreamWriter wrtr = new StreamWriter(localFile);
// loop through response stream reading each line and writing to the local file
string inLine = rdr.ReadLine();
while (inLine != null)
{
wrtr.WriteLine(inLine);
inLine = rdr.ReadLine();
}
rdr.Close();
wrtr.Close();
(which I adapted from here: http://msdn.microsoft.com/en-us/library/aa446517.aspx)
...I get, "Unable to connect to the remote server"
UPDATE 2
This does work directly in the browser on the dev machine:
http://localhost:48614/api/redemptions/
It returns these values from a Controller:
readonly Redemption[] redemptions =
{
new Redemption { RedemptionId = "1", RedemptionName = "Old", RedemptionItemId = "ABC", RedemptionAmount = 0.25M, RedemptionDept = "2.0", RedemptionSubDept = "42" },
new Redemption { RedemptionId = "2", RedemptionName = "Damaged", RedemptionItemId = "BCD", RedemptionAmount = 5.00M, RedemptionDept = "42.0", RedemptionSubDept = "76" },
new Redemption { RedemptionId = "3", RedemptionName = "Rebate", RedemptionItemId = "DEF", RedemptionAmount = 42.75M, RedemptionDept = "76.0", RedemptionSubDept = "112" }
};
...like so:
<ArrayOfRedemption xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/HHSServerWebAPI.Models">
<Redemption>
<RedemptionAmount>0.25</RedemptionAmount>
<RedemptionDept>2.0</RedemptionDept>
<RedemptionId>1</RedemptionId>
<RedemptionItemId>ABC</RedemptionItemId>
<RedemptionName>Old</RedemptionName>
<RedemptionSubDept>42</RedemptionSubDept>
</Redemption>
<Redemption>
<RedemptionAmount>5.00</RedemptionAmount>
<RedemptionDept>42.0</RedemptionDept>
<RedemptionId>2</RedemptionId>
<RedemptionItemId>BCD</RedemptionItemId>
<RedemptionName>Damaged</RedemptionName>
<RedemptionSubDept>76</RedemptionSubDept>
</Redemption>
<Redemption>
<RedemptionAmount>42.75</RedemptionAmount>
<RedemptionDept>76.0</RedemptionDept>
<RedemptionId>3</RedemptionId>
<RedemptionItemId>DEF</RedemptionItemId>
<RedemptionName>Rebate</RedemptionName>
<RedemptionSubDept>112</RedemptionSubDept>
</Redemption>
</ArrayOfRedemption>
...even when the VS2008 project is not running - is that because this data was cached (the first time I entered:
http://localhost:48614/api/redemptions/
...in the browser, the Web API app was running)?
I get that the emulator won't recognize "localhost" as the desktop instance, considering itself someone/somewhere else. So how can I test this on an emulator? What IP address can I use?
Avoiding 3rd party code out of hand is just plain silly. Why reinvent the wheel? If you are a company who's IP is making REST calls, then sure, roll it, but I suspect your core business offering is in solving some other problem. I mean why use the CF itself, and not C? Why use C and not assembly? Why use a third-party processor and not design your own?
All that aside, RestSharp comes with source and it's free, so there's little risk in using it. There are some things I like about it - primarily that most of the grunt work for REST calls done. I'm a big fan of not reinventing things. It has some quirks that I've "fixed" locally (I'm meaning to do a pull request, just haven't found the time yet) but they were minor and not what I'd consider to be "typical" cases.
As for calling Web APIs with RestSharp, there's a pretty thorough coverage over in this article.

Resources