Fill Dataset From sqlite - xamarin.android

How can this function be modified.
I want to use it to fill in the dataset from sqllite.
error
public void fillDATASET( DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLite.SQLiteConnection(dbPath);
using (Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SqliteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}

This is because you use two different libraries.
var conn = new SQLite.SQLiteConnection(dbPath);
here you used the method in sqlite-net-pcl nuget,
Mono.Data.Sqlite.SqliteCommand cmd = new SqliteCommand(query, conn)
here you want use the method in System.Data.SQLite.Core nuget.
So you need to use a unified.
For example(use System.Data.SQLite.Core nuget):
using System.Data;
using System.Data.SQLite;
public void fillDATASET(DataSet ds, string tablename, string query)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"Department.db3");
var conn = new SQLiteConnection(dbPath);
using (SQLiteCommand cmd = new SQLiteCommand(query, conn))// error conn
{
using (var DataAdapterd = new SQLiteDataAdapter(cmd))
{
ds.Clear();
DataAdapterd.Fill(ds, tablename);
}
}
}

Related

ASP.NET Stored Procedure Call insert VarBinary into sql

I have a string that is data bytes base64EncodedString from iOS which is an extremely long string
let imageStr = imageData.base64EncodedString()
I am calling a .NET Method from my ios that will call a stored procedure to insert these bytes into the database.
Here is my .NET Method, I have the data type set to VarBinary
public string PostLandGradingImages(List<Images> landingCells)
{
try
{
using (connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("PostLandGradingImages", connection))
{
command.CommandType = CommandType.StoredProcedure;
for (int i = 0; i < landingCells.Count; i++)
{
command.Parameters.Clear();
SqlParameter parameter1 = new SqlParameter("#Job_No", SqlDbType.VarChar);
parameter1.Value = landingCells[i].jobNo;
parameter1.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter1);
SqlParameter parameter2 = new SqlParameter("#Image", SqlDbType.VarBinary);
parameter2.Value = landingCells[i].imageBytes;
parameter2.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter2);
command.ExecuteNonQuery();
}
}
}
}
catch (Exception e)
{
return e.Message.ToString();
}
return "All Good";
}
Here is my Image Class, notice my imageBytes is defined as a byte[]:
public class Images
{
public string jobNo { get; set; }
public byte[] imageBytes { get; set; }
}
The column I am inserting into is defined as varbinary(MAX)
and here is my stored procedure:
ALTER PROCEDURE [dbo].[PostLandGradingImages]
-- Add the parameters for the stored procedure here
#Job_No varchar(MAX) = NULL,
#Image varbinary(MAX) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO LandGradingImages (Job_No, ImageBytes) VALUES (#Job_No, #Image)
END
My problem is nothing is getting inserted, I am getting this error in my catch:
Object reference not set to an instance of an object.
My question is, what am I doing wrong? Should I not be sending base64EncodedString or am I not setting my class right? or my db column?
I tried this:
byte[] bytes = System.Convert.FromBase64String(landingCells[i].imageBytes);
SqlParameter parameter2 = new SqlParameter("#Image", SqlDbType.VarBinary, 800000);
parameter2.Value = bytes;
parameter2.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter2);
Still does not work :( and I changed imageBytes to string.
I modified your code a little to the method below. It creates a new CommandType.StoredProcedure for every Image. Also the results are returned per image, so you can see which ones failed. In your method, if you have 10 images, and the 9th failed, you would not know that.
public List<Images> PostLandGradingImages(List<Images> landingCells)
{
//create a connection to the database
using (SqlConnection connection = new SqlConnection(Common.connectionString))
{
//loop all the images
for (int i = 0; i < landingCells.Count; i++)
{
//create a fresh sql command for every Image
using (SqlCommand command = new SqlCommand("PostLandGradingImages", connection))
{
command.CommandType = CommandType.StoredProcedure;
//add the parameters
command.Parameters.Add("#Job_No", SqlDbType.VarChar).Value = landingCells[i].jobNo;
command.Parameters.Add("#Image", SqlDbType.VarBinary).Value = landingCells[i].imageBytes;
try
{
//open the connection if closed
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
//execute the stored procedure
command.ExecuteNonQuery();
//set the save result to the image
landingCells[i].saveResult = true;
}
catch (Exception ex)
{
//handle error per Image
landingCells[i].errorMessage = ex.Message;
}
}
}
}
return landingCells;
}
In order to track the save result per image I've added two properties to the Image class, but this can be done in various other ways as well.
public class Images
{
public string jobNo { get; set; }
public byte[] imageBytes { get; set; }
public bool saveResult { get; set; }
public string errorMessage { get; set; }
}
A simple test was done with the following code. None of them gave a NullReference Error. Even with both properties being null, a database entry was still made.
//create a new list with Images
List<Images> landingCells = new List<Images>();
//add some dummy data
landingCells.Add(new Images() { jobNo = null, imageBytes = null });
landingCells.Add(new Images() { jobNo = "Job 1", imageBytes = null });
landingCells.Add(new Images() { jobNo = null, imageBytes = new byte[10000] });
landingCells.Add(new Images() { jobNo = "Job 2", imageBytes = new byte[10000] });
//send the images to be saved
landingCells = PostLandGradingImages(landingCells);
//loop all the images to check the result
for (int i = 0; i < landingCells.Count; i++)
{
if (landingCells[i].saveResult == false)
{
//display the result for each failed image
Label1.Text += landingCells[i].errorMessage + "<br>";
}
}
If there is still a NullReference error, that means that your List landingCells itself is null, or an Image object within that List is null (in which case it should never have been added to the List in the first place imho). You can change the snippet easily to check for that.
Consider batching the queries in a transaction. Also you should validate the values provided to the method to make sure that you can call the stored procedure correctly.
public int PostLandGradingImages(List<Images> landingCells) {
int count = 0;
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
//Transaction to batch the actions.
using (var transaction = connection.BeginTransaction()) {
foreach (var image in landingCells) {
if (valid(image)) {//validate input properties.
try {
using (SqlCommand command = connection.CreateCommand()) {
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "PostLandGradingImages";
command.Parameters
.Add("#Job_No", SqlDbType.VarChar, image.jobNo.Length)
.Value = image.jobNo;
command.Parameters
.Add("#Image", SqlDbType.VarBinary, image.imageBytes.Length)
.Value = image.imageBytes;
count += command.ExecuteNonQuery();
}
} catch {
//TODO: Log error
}
}
}
if (landingCells.Count == count) {
transaction.Commit();
}
}
}
return count;
}
private bool valid(Images image) {
return image != null && String.IsNullOrWhiteSpace(image.jobNo)
&& image.imageBytes != null && image.imageBytes.Length > 0;
}

Connecting to Open LDAP fails to bind with System.DirectoryServices.Protocols

I have been trying to connect to Open LDAP using sample code from MSDN (Alex Tcherniakhovski)
http://blogs.msdn.com/b/alextch/archive/2012/05/07/sample-code-to-query-openldap-directory-via-net-system-directoryservices-protocols.aspx
I have tried on PORT 636 : ssl as it is in the sample code
And on PORT 389 non ssl to see if i could succeed
When trying on PORT 389 (with the same credentials I could connect to the OPEN LDAP using Softerra LDAP Browser)
I get the following error : The distinguished name contains invalid syntax.
I ran Microsoft Network Monitor and found out that some unwanted characters ââ get added to my Bind request just before my name. These characters never appear in the dotnet solution yet they are part of the request and make it fail.
Do you have an idea of how to get rid of these ?
I would have shown an image but i am not allowed.
My monitor shows BindRequest: Version:3, Name:ââcn=Manager,dc=...
in the dotnet code name is "cn=Manager,dc=.."
Using the code as is with SSL on port 636 lead to the following error : The LDAP server is unavailable.
I get the same error trying to connect with sslbind from Solution DirectoryServices.Protocol downloaded from here.
http://www.microsoft.com/en-us/download/confirmation.aspx?id=18086
Thanks for your help
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Globalization;
using System.Net;
using System.Security;
namespace OpenLDAPNextUID
{
public class LDAPHelper
{
private readonly LdapConnection ldapConnection;
private readonly string searchBaseDN;
private readonly int pageSize;
public LDAPHelper(
string searchBaseDN,
string hostName,
int portNumber,
AuthType authType,
string connectionAccountName,
SecureString connectionAccountPassword,
int pageSize)
{
var ldapDirectoryIdentifier = new LdapDirectoryIdentifier(
hostName,
portNumber,
true,
false);
var networkCredential = new NetworkCredential(
connectionAccountName,
connectionAccountPassword);
ldapConnection = new LdapConnection(
ldapDirectoryIdentifier,
networkCredential)
{AuthType = authType};
ldapConnection.SessionOptions.ProtocolVersion = 3;
this.searchBaseDN = searchBaseDN;
this.pageSize = pageSize;
}
public IEnumerable<SearchResultEntryCollection> PagedSearch(
string searchFilter,
string[] attributesToLoad)
{
var pagedResults = new List<SearchResultEntryCollection>();
var searchRequest = new SearchRequest
(searchBaseDN,
searchFilter,
SearchScope.Subtree,
attributesToLoad);
var searchOptions = new SearchOptionsControl(SearchOption.DomainScope);
searchRequest.Controls.Add(searchOptions);
var pageResultRequestControl = new PageResultRequestControl(pageSize);
searchRequest.Controls.Add(pageResultRequestControl);
while (true)
{
var searchResponse = (SearchResponse)ldapConnection.SendRequest(searchRequest);
var pageResponse = (PageResultResponseControl)searchResponse.Controls[0];
yield return searchResponse.Entries;
if (pageResponse.Cookie.Length == 0)
break;
pageResultRequestControl.Cookie = pageResponse.Cookie;
}
}
}
}
namespace OpenLDAP
{
class Program
{
static void Main(string[] args)
{
var password = new[]{'P','a','s','s','w','#','r','d'};
var secureString = new SecureString();
foreach (var character in password)
secureString.AppendChar(character);
var baseOfSearch = "dc=fabrikam,dc=com";
var ldapHost = "ubuntu.fabrikam.com";
var ldapPort = 636; //SSL
var ldapPort = 389; //not SSL
var connectAsDN = "cn=admin,dc=fabrikam,dc=com";
var pageSize = 1000;
var openLDAPHelper = new LDAPHelper(
baseOfSearch,
ldapHost,
ldapPort,
AuthType.Basic,
connectAsDN,
secureString,
pageSize);
var searchFilter = "nextUID=*";
var attributesToLoad = new[] {"nextUID"};
var pagedSearchResults = openLDAPHelper.PagedSearch(
searchFilter,
attributesToLoad);
foreach (var searchResultEntryCollection in pagedSearchResults)
foreach (SearchResultEntry searchResultEntry in searchResultEntryCollection)
Console.WriteLine(searchResultEntry.Attributes["nextUID"][0]);
Console.Read();
}
}
}

How do i use LinqToExcel to get cell values contained in the excel file

I am using this code to retrieve the receipient name and receipient number but the recpt.receipient_name and recpt.receipient_number are null.
The excel table is of this format
Name Number
andrew 1223
james 12223
dave 454545
//select names from the excel file with specified sheet name
var receipients = from n in messages.Worksheet<BulkSmsModel>(sheetName)
select n;
foreach (var recpt in receipients)
{
BulkSms newRecpt = new BulkSms();
if (recpt.receipient_number.Equals("") == true || recpt.receipient_number == 0)
{
continue;
}
newRecpt.receipient_name = recpt.receipient_name;
newRecpt.receipient_number = Int32.Parse(recpt.receipient_number.ToString());
IBsmsRepo.insertReceipient(newRecpt);
IBsmsRepo.save();
}
After some research I found a way to get the value from excel file with LinqToExcel and get the list of all Cells. Check this MVC C# Sample.
using LinqToExcel;
using Syncfusion.Olap.Reports;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace YourProject.Controllers
{
public class DefaultController : Controller
{
// GET: Default1
public ActionResult Index()
{
return View();
}
public dynamic UploadExcel(HttpPostedFileBase FileUpload)
{
string PathToyurDirectory = ConfigurationManager.AppSettings["Path"].ToString();//This can be in Anywhere, but you have to create a variable in WebConfig AppSettings like this <add key="Path" value="~/Doc/"/> This directory in my case is inside App whereI upload the files here, and I Delete it after use it ;
if (FileUpload.ContentType == "application/vnd.ms-excel"
|| FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|| FileUpload.ContentType == "application/vnd.ms-excel.sheet.binary.macroEnabled.12"
)
{
string filename = FileUpload.FileName;
string PathToExcelFile = Server.MapPath(PathToyurDirectory + filename);
// string targetpath = ;
FileUpload.SaveAs(PathToyurDirectory);
var connectionString = string.Empty;
string sheetName = string.Empty;
yourmodel db = new yourmodel();
Employee Employee = New Employee(); //This is your class no matter What.
try
{
if (filename.EndsWith(".xls") || filename.EndsWith(".csv") || filename.EndsWith(".xlsx") || filename.EndsWith(".xlsb"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", PathToExcelFile);
sheetName = GetTableName(connectionString);
}
var ExcelFile = new ExcelQueryFactory(PathToExcelFile);
var Data = ExcelFile.Worksheet(sheetName).ToList();
foreach (var item in Data)
{
//if yout excel file does not meet the class estructure.
Employee = new Employee
{
Name = item[1].ToString(),
LastName = item[2].ToString(),
Address = item[3].ToString(),
Phone = item[4].ToString(),
CelPghone = item[5].ToString()
};
db.Employee.Add(Employee);
db.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
return View();
}
private string GetTableName(string connectionString)
{
// You can return all Sheets for a Dropdown if you want to, for me, I just want the first one;
OleDbConnection oledbconn = new OleDbConnection(connectionString);
oledbconn.Open();
// Get the data table containg the schema guid.
var dt = oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheet = dt.Rows[0]["TABLE_NAME"].ToString().Replace("$", string.Empty);
oledbconn.Close();
return sheet;
}
}
}
Since the property names on the BulkSmsModel class do not correlate directly to the column names in the spreadsheet, you will need to map the property names to the column names.
Assuming messages is the ExcelQueryFactory object, this would be the code.
var messages = new ExcelQueryFactory("excelFileName");
messages.AddMapping<BulkSmsModel>(x => x.receipient_name, "Name");
messages.AddMapping<BulkSmsModel>(x => x.receipient_number, "Number");
var receipients = from n in messages.Worksheet<BulkSmsModel>(sheetName)
select n;

Advantage database throws an exception when attempting to delete a record with a like statement used in the where clause

The code below shows that a record is deleted when the sql statement is:
select * from test where qty between 50 and 59
but the sql statement:
select * from test where partno like 'PART/005%'
throws the exception:
Advantage.Data.Provider.AdsException: Error 5072: Action requires read-write access to the table
How can you reliably delete a record with a where clause applied?
Note: I'm using Advantage Database v9.10.1.9, VS2008, .Net Framework 3.5 and WinXP 32 bit
using System.IO;
using Advantage.Data.Provider;
using AdvantageClientEngine;
using NUnit.Framework;
namespace NetworkEidetics.Core.Tests.Dbf
{
[TestFixture]
public class AdvantageDatabaseTests
{
private const string DefaultConnectionString = #"data source={0};ServerType=local;TableType=ADS_CDX;LockMode=COMPATIBLE;TrimTrailingSpaces=TRUE;ShowDeleted=FALSE";
private const string TestFilesDirectory = "./TestFiles";
[SetUp]
public void Setup()
{
const string createSql = #"CREATE TABLE [{0}] (ITEM_NO char(4), PARTNO char(20), QTY numeric(6,0), QUOTE numeric(12,4)) ";
const string insertSql = #"INSERT INTO [{0}] (ITEM_NO, PARTNO, QTY, QUOTE) VALUES('{1}', '{2}', {3}, {4})";
const string filename = "test.dbf";
var connectionString = string.Format(DefaultConnectionString, TestFilesDirectory);
using (var connection = new AdsConnection(connectionString)) {
connection.Open();
using (var transaction = connection.BeginTransaction()) {
using (var command = connection.CreateCommand()) {
command.CommandText = string.Format(createSql, filename);
command.Transaction = transaction;
command.ExecuteNonQuery();
}
transaction.Commit();
}
using (var transaction = connection.BeginTransaction()) {
for (var i = 0; i < 1000; ++i) {
using (var command = connection.CreateCommand()) {
var itemNo = string.Format("{0}", i);
var partNumber = string.Format("PART/{0:d4}", i);
var quantity = i;
var quote = i * 10;
command.CommandText = string.Format(insertSql, filename, itemNo, partNumber, quantity, quote);
command.Transaction = transaction;
command.ExecuteNonQuery();
}
}
transaction.Commit();
}
connection.Close();
}
}
[TearDown]
public void TearDown()
{
File.Delete("./TestFiles/test.dbf");
}
[Test]
public void CanDeleteRecord()
{
const string sqlStatement = #"select * from test";
Assert.AreEqual(1000, GetRecordCount(sqlStatement));
DeleteRecord(sqlStatement, 3);
Assert.AreEqual(999, GetRecordCount(sqlStatement));
}
[Test]
public void CanDeleteRecordBetween()
{
const string sqlStatement = #"select * from test where qty between 50 and 59";
Assert.AreEqual(10, GetRecordCount(sqlStatement));
DeleteRecord(sqlStatement, 3);
Assert.AreEqual(9, GetRecordCount(sqlStatement));
}
[Test]
public void CanDeleteRecordWithLike()
{
const string sqlStatement = #"select * from test where partno like 'PART/005%'";
Assert.AreEqual(10, GetRecordCount(sqlStatement));
DeleteRecord(sqlStatement, 3);
Assert.AreEqual(9, GetRecordCount(sqlStatement));
}
public int GetRecordCount(string sqlStatement)
{
var connectionString = string.Format(DefaultConnectionString, TestFilesDirectory);
using (var connection = new AdsConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
command.CommandText = sqlStatement;
var reader = command.ExecuteExtendedReader();
return reader.GetRecordCount(AdsExtendedReader.FilterOption.RespectFilters);
}
}
}
public void DeleteRecord(string sqlStatement, int rowIndex)
{
var connectionString = string.Format(DefaultConnectionString, TestFilesDirectory);
using (var connection = new AdsConnection(connectionString)) {
connection.Open();
using (var command = connection.CreateCommand()) {
command.CommandText = sqlStatement;
var reader = command.ExecuteExtendedReader();
reader.GotoBOF();
reader.Read();
if (rowIndex != 0) {
ACE.AdsSkip(reader.AdsActiveHandle, rowIndex);
}
reader.DeleteRecord();
}
connection.Close();
}
}
}
}
LIKE results in a static cursor instead of a live cursor, meaning it is a read-only dataset. To remove a row in this situation it would be better to use an SQL DELETE statement.
DELETE FROM test where partno LIKE 'PART/005%'
I'm assuming your tests are just that, only tests. They are using some fairly inefficient mechanisms to locate and remove rows.
Update after comment that there is no key field:
How about using the LEFT scalar instead of LIKE (might not work for all cases, but does for your example). If the size is always the same you could also add an index on left(partno,8) to increase the performance:
select * from test where left(partno,8) = 'PART/005'
Then you could use the Delete function of the extended data reader directly on this live result set (no gotop and skip).
Update after Alex's ROWID comment
I didn't know our ROWID came from the base table, even in static cursors. Alex's comment is the solution to your problem. First:
SELECT t.*, t.rowid FROM test t WHERE x LIKE 'PART/005%'
then:
DELETE FROM test WHERE rowid = :thisid

VSTO 3.0 Get/Change an excel 2007 workbook connection

I've struggling to find a way to get and change and excel 2007 workbook connection (Menu Data -> Existing Connections -> Connections on this Workbook).It's a connection (several actually) to a SQL Server and used in a pivot table.
I've tried using Application.ActiveWorkbook.Connections or Globals.ThisWorkbook.Connections but they both return always Null..I've tried in an sheet event as well as in a custom ribbon's button event as well.
The only way left I can think of is use to code a VBA method that does the work and then invoke it in my VSTO code, but it's not very elegant is it...
Existing connections in Excel (this works in 2007) are not active connections. You must connect using an existing connection before being able to acquire that connection (I did this manually before clicking a button that executed this code).
var application = Globals.ThisAddIn.Application;
//This must be an active connection otherwise handle exceptions
// such as 'Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'
var connection = application.ActiveWorkbook.Connections["EXISTING_CONNECTION_NAME"];
var oledb = connection.OLEDBConnection;
var settings = oledb.Connection;
Here I adjust connection string of Excel Connections. Take in account that I have only ONE connection in Workbook.
public class WorkbookConnectionsManager
{
public static void AdjustConnectionToSqlConnectionString(Excel.WorkbookConnection connection, String connectionString)
{
char[] propertiesSeparator = new char[] { ';' };
char[] propertyValueSeparator = new char[] { '=' };
Excel.OLEDBConnection oleDbConn = connection.OLEDBConnection;
Dictionary<string, string> dictExcelConnStrProperties = GetConnStrDictionary(oleDbConn.Connection, propertiesSeparator, propertyValueSeparator);
Dictionary<string, string> dictActualConnStrProperties = GetConnStrDictionary(connectionString, propertiesSeparator, propertyValueSeparator);
string[] reggedPropertyies = new string[] { "Integrated Security", "Persist Security Info", "User ID", "Password", "Initial Catalog", "Data Source", "Workstation ID" };
foreach (string property in reggedPropertyies)
if (dictExcelConnStrProperties.ContainsKey(property) && dictActualConnStrProperties.ContainsKey(property)
&& null != dictActualConnStrProperties[property] && !String.IsNullOrEmpty(dictActualConnStrProperties[property].ToString()))
dictExcelConnStrProperties[property] = dictActualConnStrProperties[property];
string connStr = GetConnStrFromDict(dictExcelConnStrProperties, propertiesSeparator[0], propertyValueSeparator[0]);
oleDbConn.Connection = connStr;
}
private static string GetConnStrFromDict(Dictionary<string, string> dictConnStrProperties, char propertiesSeparator, char propertyValueSeparator)
{
StringBuilder connStrBuilder = new StringBuilder();
foreach (KeyValuePair<string, string> keyValuePair in dictConnStrProperties)
{
connStrBuilder.Append(keyValuePair.Key);
if (!String.IsNullOrEmpty(keyValuePair.Value))
{
connStrBuilder.Append(propertyValueSeparator);
connStrBuilder.Append(keyValuePair.Value);
}
connStrBuilder.Append(propertiesSeparator);
}
string connStr = String.Empty;
if (connStrBuilder.Length > 1)
{
connStr = connStrBuilder.ToString(0, connStrBuilder.Length - 1);
}
return connStr;
}
private static Dictionary<string, string> GetConnStrDictionary(string connString, char[] propertiesSeparator, char[] propertyValueSeparator)
{
string[] keyAndValue;
string[] arrayConnStrProperties = connString.Split(propertiesSeparator);
Dictionary<string, string> dictConnStrProperties = new Dictionary<string, string>();
foreach (string excelConnStrProperty in arrayConnStrProperties)
{
keyAndValue = excelConnStrProperty.Split(propertyValueSeparator);
if (keyAndValue.Length > 1)
{
dictConnStrProperties.Add(keyAndValue[0], keyAndValue[1]);
}
else if (keyAndValue.Length > 0)
{
//standalone attribute
dictConnStrProperties.Add(keyAndValue[0], String.Empty);
}
}
return dictConnStrProperties;
}
}
I can't remember where but I remember reading somewhere that the Connections collection was of limited use for writing ODBC type connections. It has several enum values for a "connection" but I'm not sure if some of those are readonly from that interface.
Regardless it should be quite easy to implement new connections and edit existing ones from VSTO. The best option would be to use COM interop to call the SQLConfigDataSource() function from the ODBCCP32.DLL win32 library.
Also check out the following addin which makes it easier to work with query tables in Excel.

Resources