I'm new to C#, creating excel plugins and also new to ExcelDNA. I got the examples working on http://exceldna.codeplex.com/wikipage?title=Getting%20Started. The UDF "MultiplyThem" works as expected.
When I modify example #3 on that site to grab data from a mysql database. I reference not only ExcelDna.Integration.dll but also MySql.Data.dll in my project. I then compile it with this statement:
c:\windows\microsoft.net\framework\v2.0.50727\csc.exe /target:library /reference:ExcelDna.Integration.dll /reference:MySql.Data.dll TestLib.cs
When I open up the excel-add in and start typing in my UDF(in this case, "=MultiplyThem()") there is no UDF called "MultiplyThem". Why did it suddenly stop working? Here's my C# code:
using ExcelDna.Integration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
public class MyFunctions
{
[ExcelFunction(Description = "Grabs data from database", Category = "Useful functions")]
public static string MultiplyThem(string[] args)
{
string connString = "Server=localhost;Port=3306;Database=test;Uid=root;password=pword";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT field_value FROM customers";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
string myvariable = "bad";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
myvariable = reader["field_value"].ToString();
}
return myvariable;
}
}
And my Test1.dna file (I am targeting .NET Framework 4 in my project):
<DnaLibrary RuntimeVersion="v4.0">
<ExternalLibrary Path="TestLib.dll"/>
</DnaLibrary>
Excel-DNA does not currently support string arrays as parameters. If you change the string[] args to object[] args it should be fine.
Related
I have a procedure named as Get_Added_Request_ID and using this procedure I need to get returned the Request_ID value (VARCHAR2). I have referrd plenty of docs released by Oracle and Microsoft but still I could not find a good solution may be because I am a new learner for Oracle and ASp.NET. Please someone help me in this issue. Thanks in advance
-- Parameter Type Mode Default?
-- ATTR_ VARCHAR2 IN
-- REQUEST_ID VARCHAR2 OUT
Please view this link for the documentation on how to connect to oracle by using oracle data provider
You should use oracle data provider from this link for connecting oracle.
the example code for your scenario will be
Using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;
namespace CallingOracleStoredProc
{
class Program
{
static void Main(string[] args)
{
using (OracleConnection objConn = new OracleConnection("Data Source=*your datasource*; User ID=*Your UserID*; Password=*Your Password*"))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "Get_Added_Request_ID";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("ATTR_", OracleType.NVarChar).Value = "test";
objCmd.Parameters.Add("REQUEST_ID", OracleType.NVarChar).Direction = ParameterDirection.Output;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
System.Console.WriteLine("The Request ID is {0}", objCmd.Parameters["REQUEST_ID"].Value);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: {0}",ex.ToString());
}
objConn.Close();
}
}
}
}
use execute scalar which return 1 row - 1 column value & store it in appropriate variable
For e.g :- SqlHelper.ExecuteScalar(_connectionString, CommandType.StoredProcedure, "Get_Added_Request_ID", null);
note :- ExecuteScalar is came from nuget Microsoft.Application Block
I'm working on a C# project in Visual Studio 2012 on Windows 10 and Oracle 11g.
In order to connect my c# project I had to install Oracle Data Access Components_ODTwithODAC121024 and everything worked fine.
I updated the target .NET framework of my project to 3.5, and now I get this error:
Could not load file or assembly 'Oracle.DataAccess, Version=2.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
After really long search and test I think that caused by incompatibility issue.
I tried to enable .NET Framework 3.5 through Programs and Features -> Turn Windows features on or off.
I tried to read reference and importing the Oracle.DataAccess.dll from
C:\app\Samer\product\11.2.0\dbhome_1\ODP.NET\bin\2.x
and I also used the Oracle.DataAccess.dll that comes with Oracle Data Access Components
My project works fine when I disable the method that deals with oracle commands.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace backup_Check_v01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Read_const_File();
}
//Method for Reading Constants File
public void Read_const_File()
{
string File_Path;
File_Path = #"s:\test\result";
Get_File_info(File_Path);
}
//Method for reading file information ex(File Name,Size,and creation date..etc)
public void Get_File_info(string para1)
{
FileInfo info = new FileInfo(para1);
richTextBox1.AppendText(Environment.NewLine + "File Name: " + Path.GetFileNameWithoutExtension(info.Name));
richTextBox1.AppendText(Environment.NewLine + "File Size (Bytes): " + info.Length.ToString());
richTextBox1.AppendText(Environment.NewLine + "Creation Time: " + info.CreationTime.ToString());
richTextBox1.AppendText(Environment.NewLine + "Last Access: " + info.LastAccessTime.ToString());
richTextBox1.AppendText(Environment.NewLine + " **************************** ");
search_for_string(para1);
}
public void search_for_string(string para2)
{
string keywords = "sb_0501_Thu.dmp";
string oradb = "Data Source=sb_1901;User Id=sb_1901;Password=sb00;";
StreamReader sr = new StreamReader(para2);
richTextBox1.AppendText(Environment.NewLine + sr.ReadToEnd());
if (!richTextBox1.Text.Contains(keywords))
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',0,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
else
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',1,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
}
}
}
You refer to ODP.NET version 2.121.2.0. but it seems you have installed Oracle Client 11.2. The versions have to match with each other (at least the major version number)
Open your *.csproj file and set reference of Oracle.DataAccess like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
</Reference>
Attributes like Version=... or processorArchitecture=... are not required. Your application will load the correct Oracle.DataAccess.dll depending on selected architecture and target .NET framework
I am still new to ASP.net and I'm learning how to call classes. I've looked around for tutorials, but not all are specific to ASP.net 4.0 so I'm not sure if I should apply them.
Right now, I am trying to connect to my SQL database. My webconfig file has been set up with the connectionstring "dbConnectionString" and is working properly when I've tested it with GridViews. What I'd like to do now is access the database from code behind.
I've seen some ways to accomplish this, but I'd like the most efficient, resuable way. I've tried to adopt the answer listed here: How to create sql connection with c# code behind, access the sql server then conditionally redirect? however, I'm getting an error.
I am doing this with C# as a website, not a web application. Here is my code behind for Login.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlComm; // Is this how I connect to my class from this page????
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//no code written yet
}
}
}
My class in the App_Code folder, file name SQLComm.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
/// <summary>
/// SQL Query class
/// </summary>
public class SqlComm
{
// Connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
// Execute sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// Execute SQL query and return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(PjSql.dbcs()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// Retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// Execute a stored procedure with 1 parameter
// Returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
As you can see, I haven't written any code to actually use the class yet, but the "using SQLComm;" line itself is giving me this error:
Compiler Error Message: CS0246: The type or namespace name 'SqlComm' could not be found (are you missing a using directive or an assembly reference?)
As I'm still new, I'm unsure where to go from here. I seem to have included everything contained in the answer on the page I linked above. What else and I missing?
Edit: I read this post regarding a similar issue: asp.NET 2.0 Web Site Can't Access Classes in App_Code
Could this be because I am doing a website and not a web application, so the App_Code folder is being handled differently when I FTP the files over?
using SQLComm means you want to use the namespace SqlComm, which doesn't exist. I think what you want is (somewhere in your codebehind):
DataTable dt = SqlComm.SqlDataTable(...) // call one of the static methods.
You can call it directly.
Given your class has static methods only you'll call it like this:
SqlComm.SqlReturn("select * from table");
So I believe I figured it out. I had my App_Code folder within the subdirectory of my Aspx website, instead of in the root of the server. I moved the folder to the root and now it's working.
I'd be interested in hearing any answers to my edit to my original post though. Since I'm doing this as a website instead of a web application, are there any other issues I will need to keep in mind regarding using classes like this or other issues? I've looked around but haven't seen many differences.
Thanks to everyone for you help!
I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement