How to do a simple C# import? - c#

Okay, this may seem silly. But, I don't know how to do an "import" in C#, in visual studio 2008. I know java, but not C#. Currently, I don't have the time to read a c# book. So, I need some help to get it right.
I was trying to use the code here - SSIS Getting Execute Sql Task result set object
DataTable dt = new DataTable();
OleDbDataAdapter oleDa = new OleDbDataAdapter();
oleDa.Fill(dt, Dts.Variables["User::objShipment"].Value);
And I get the error - The type or namespace name 'OledDbDataAdapter' could not be found (are you missing a using directive or an assembly reference?)
I tried to do a java style import. But it failed.
using System.Data.OleDb::OleDbDataAdapter
Full code given below -
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
namespace ST_LongCodeGoesHere.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
//To see the comment here, look at beyond end of this code.
public void Main()
{
// TODO: Add your code here
DataTable table = new DataTable();
OledDbDataAdapter oleDbA = new OleDbDataAdapter();
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
The comment was -
/*
The execution engine calls this method when the task executes.
To access the object model, use the Dts property. Connections, variables, events,
and logging features are available as members of the Dts property as shown in the following examples.
To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
To post a log entry, call Dts.Log("This is my log text", 999, null);
To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
To use the connections collection use something like the following:
ConnectionManager cm = Dts.Connections.Add("OLEDB");
cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
To open Help, press F1.
*/

In C#, you don't import individual types, you import whole namespaces. Something like this
should work:
using System.Data.OleDb;
...
OleDbDataAdapter oleDa = new OleDbDataAdapter();
Or you could create a type alias like this:
using OleDbDataAdapter = System.Data.OleDb.OleDbDataAdapter;
Further Reading
using Directive (C# Reference)

In Solution Explorer under your Solution find 'References' and add System.Data by right-clicking and 'Add reference'. You probably also want to type your import as: using System.Data.OleDb;

Have a look at this http://msdn.microsoft.com/en-us/library/vstudio/wkze6zky.aspx
You need to add the reference, before you can use it.

Related

Write to XML file using existing dataset created in Visual Basic

Please bear with me. I don't have any knowledge of C# or Visual Basic but I've been tasked with a complex project that wasn't properly scoped. This is way outside the scope of my normal work but no one in the organization appears to have this knowledge so I'm trying to assist since this data is a state requirement. I have been googling, watching tutorials, and testing things out for weeks.
I have multiple tables that I've used to create a dataset using Visual Studio 2019. Now I need to write the data in that dataset to XML. Most of what I've seen online just has a few lines of code like:
private void WriteXmlToFile(DataSet thisDataSet)
{
if (thisDataSet == null) { return; }
// Create a file name to write to.
string filename = "XmlDoc.xml";
// Write to the file with the WriteXml method.
thisDataSet.WriteXml(filename);
}
or
string filePath = "ENTER A VALID FILEPATH";
northwindDataSet.WriteXml(filePath);
but doesn't really say where or how they should be utilized (there obviously has to be more to it). I did try this by replacing 'thisDataSet' with my existing dataset but got an error that the modifier private is not valid for this item. I think because it's inside of another private void for the button click.
I found a tutorial that helped me create a form and then code for creating and filling a dataset and then writing that to XML and I was able to do that successfully and I understand what is being done.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NEMSIS_Project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnCreate_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("Age");
DataColumn dc3 = new DataColumn("Gender");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Rows.Add("Mourya", "25", "Male");
dt.Rows.Add("Steve", "40", "Male");
dt.Rows.Add("Jasmine", "19", "Female");
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml("Contacts.xml");
}
}
}
My disconnect is how to use my own dataset. I've tried piecing together code from around the internet but I keep getting different errors depending on the code. I've tried searching my issue/question different ways but have yet to come up with anything. I'm not sure if I need to write something to call my dataset or if I have to "write" a query to pull the data from my dataset into a new dataset and then write to XML. Any guidance would be greatly appreciated.

What reference should I use for 'Data.ValueRange'?

I'm following a guide to write output data from Visual Studio into a google spreadsheet.
At the end of the guide there is a code block that I pasted inside my project:
using OpenQA.Selenium.Support.UI;
using System;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections;
using System.Collections.Generic;
using Google.Apis.Sheets.v4;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Services;
using Newtonsoft.Json;
using WikipediaTests.Foundation_Class;
using System.Web;
using System.Data;
using Google.Apis.Sheets.v4.Data;
namespace AutomationProjects
{
[TestFixture]
public class TestClass : TestFoundation
{
public class SpreadSheetConnector
{
//Codeblock from guide pasted here!
}
[Test]
public void test1()
{
//Test case 1. Do XYZ...
}
}
}
In the code block included in the guide there is a section about creating a list and passing data into it:
// Pass in your data as a list of a list (2-D lists are equivalent to the 2-D spreadsheet structure)
public string UpdateData(List<IList<object>> data)
{
String range = "My Tab Name!A1:Y";
string valueInputOption = "USER_ENTERED";
// The new values to apply to the spreadsheet.
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
var dataValueRange = new Data.ValueRange();
dataValueRange.Range = range;
dataValueRange.Values = data;
updateData.Add(dataValueRange);
Data.BatchUpdateValuesRequest requestBody = new Data.BatchUpdateValuesRequest();
requestBody.ValueInputOption = valueInputOption;
requestBody.Data = updateData;
var request = _sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, _spreadsheetId);
Data.BatchUpdateValuesResponse response = request.Execute();
// Data.BatchUpdateValuesResponse response = await request.ExecuteAsync(); // For async
return JsonConvert.SerializeObject(response);
}
The problem is that I get an error for the 'Data.ValueRange' and the 'Data.BatchUpdateValuesRequest' :
CS0246 The type or namespace name 'Data' could not be found (are you missing a using directive or an assembly reference?)
I tried adding "System.Data" as a assembly reference to my project and then added it at the top (using). But it did not remove the error.
'Data.' seems to belong to "Google.Apis.Sheets.v4" but I have already added that reference as the guide instructed.
The only fix that gets rid of the error is adding Google.Apis.Sheets.v4 before every 'Data.' like this:
List<Google.Apis.Sheets.v4.Data.ValueRange>
But when I run my tests the output does not get exported to my spreadsheet. So I'm assuming this is not the correct solution. And also I'm assuming that the guide should have included this in the code block if it was necessary.
Could there be some other reference about 'Data' I need?
According to the documentation, the ValueRange Class depends of Sheets.v4.Data, so you should add:
using Google.Apis.Sheets.v4.Data;
Also, change:
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
to:
List<ValueRange> updateData = new List<ValueRange>();

fakeXrmEasy for crm testing initialization issues

I'm trying to follow the basic tutorial for FakeXrmEasy, but I'm not sure why I'm getting errors. I installed everything that needs to be installed to mock Dynamics 365, but I'm still getting errors. I can't figure out what I'm missing, I really want to be able to use this tool.
CS1950 The best overloaded Add method 'List.Add(Entity)' for the collection initializer has some invalid arguments unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 48 Active
CS0246 The type or namespace name 'Account' could not be found (are you missing a using directive or an assembly reference?) unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 45 Active
Didn't know if I was suppose to create an account class, I also tried that but that didn't work either. I got
CS1503 Argument 1: cannot convert from 'unitTest.Account' to 'Microsoft.Xrm.Sdk.Entity' unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 48 Active
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using FakeItEasy;
using FakeXrmEasy;
using Microsoft.Xrm.Sdk;
namespace unitTest
{
class Program
{
static void Main(string[] args)
{
}
}
class unitTest
{
public object ProxyTypesAssembly { get; private set; }
public void MyFirstTest()
{//test method body
var context = new XrmFakedContext();
//You can think of a context like an Organisation database which stores entities In Memory.
//We can also use TypedEntities but we need to tell the context where to look for them,
//this could be done, easily, like this:
context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
//We have to define our initial state now,
//by calling the Initialize method, which expects a list of entities.
var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" };
context.Initialize(new List<Entity>() {
account
});
}
}
}
Do you use early binding in your CRM project and got the references right? If you do not use early binding, you can try late binding, e.g.
//context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
var account = new Entity();
account.LogicalName = "account";
account.Attributes["name"] = "your account name";

How to release COM handle in .NET

I am using the following code under ASP.NET 4.0 framework to obtain the version of MSI file from a web app:
string strVersion = "";
try
{
Type InstallerType;
WindowsInstaller.Installer installer;
InstallerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
installer = (WindowsInstaller.Installer)Activator.CreateInstance(InstallerType);
WindowsInstaller.Database db = installer.OpenDatabase(strMSIFilePath, 0);
WindowsInstaller.View dv = db.OpenView("SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'");
WindowsInstaller.Record record = null;
dv.Execute(record);
record = dv.Fetch();
strVersion = record.get_StringData(1).ToString();
dv.Close();
//db.Commit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(dv);
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(db);
}
catch
{
//Failed
strVersion = "";
}
It works fine except that when the code finishes running it holds an internal MSI file handle so when I try to move or rename the MSI file I get the error that the file is still in use. This continues until I actually navigate away from the ASPX page that calls the method above.
My question is, I obviously didn't close some handle or object in the code above. But what could that be?
PS. I'm testing it in a development IDE from VS2010.
EDIT: Edited the code like it should be after Adriano's suggestion. Thanks!
The COM object has not been released (it should be auto-released when it goes out of scope but in .NET this doesn't work really well). Because it does not implement the IDisposable interface you can't call its Dispose() method and you can't use it inside an using statement. You have to explicitly call Marshal.FinalReleaseComObject. For example:
try
{
// Your stuffs
}
finally
{
dv.Close();
Marshal.FinalReleaseComObject(dv);
Marshal.FinalReleaseComObject(db);
}
Moreover note that you do not really need a call to the Commit() method because you didn't make any change but just a query.
FWIW, you should be using Windows Installer XML (WiX) Deployment Tools Foundation (DTF). It's an FOSS project from Microsoft that can be found on CodePlex. It has MSI interop libraries with classes that are very similar to the COM classes but implement IDisosable and use P/Invoke instead of COM behind the scenes. There is even support for Linq to MSI if you want. And the full source code is available.
DTF is the gold standard for MSI interop in a .NET world. Here are two examples:
using System;
using System.Linq;
using Microsoft.Deployment.WindowsInstaller;
using Microsoft.Deployment.WindowsInstaller.Linq;
namespace ConsoleApplication3
{
class Program
{
const string DATABASE_PATH = #"C:\FOO..MSI";
const string SQL_SELECT_PRODUCTVERSION = "SELECT `Value` FROM `Property` WHERE `Property`='ProductVersion'";
static void Main(string[] args)
{
using (Database database = new Database(DATABASE_PATH, DatabaseOpenMode.ReadOnly))
{
Console.WriteLine(database.ExecuteScalar(SQL_SELECT_PRODUCTVERSION).ToString());
}
using (QDatabase database = new QDatabase(DATABASE_PATH, DatabaseOpenMode.ReadOnly))
{
var results = from property in database.Properties where property.Property == "ProductVersion" select property.Value;
Console.WriteLine(results.AsEnumerable<string>().First());
}
}
}
}
try to Dispose the Objects.
dv.Dispose();
db.Dispose();

what namespaces used to remove the following errors?

my question is that if the user click on button(which is placed in default.aspx,for example) then the database table is created in database(database is placed in sql express 2005)how can do ?.
I try this task by another method but the following errors are occurred:
1.'system.Web.UI.Page.Server' is a 'property' but is used like a 'type'.
2.The type or namespace name 'Database' could not be found(are you
missing a using directive or an
assembly reference?)
3.The name 'DataType' does not exist in the current context.
4.'System.Web.UI.WebControls.Table' does not contain a definition for
'columns' and no extension method
'columns' accepting a first argument
of type
'System.Web.UI.WebControls.Table' could be found(are you missing a using
directive or an assembly reference.
5.'System.Data.Index' is inaccessible due to its protection
level.
6.'System.Data.Index' does not contain a constructor that takes '2'
arguments.
7.'System.Data.Index' does not contain a definition for
'IndexKeyType' and no extension method
'IndexKeyType' accepting a first
argument of type 'System.Data.Index'
could be found(are you missing a using
directive or an assembly reference?)
8.The name 'IndexKeyType' does not exist in the current context.
9.'System.Data.Index' does not contain a definition
for'IndexedColumns' and no extension
method 'IndexedColumns' accepting a
first argument of type
'System.Data.Index' could be found(are
you missing a using directive or
assembly reference?)
10.The type or namespace name 'Indexedcolumn' could not be found(are
you missing a using directive or an
assembly reference?)
11.'System.Web.UI.WebControls.Table' does not contain a definition for
'Indexes' and no extension method
'Indexes' accepting a first argument
of type
'System.Web.UI.Webcontrols.Table'
could be found(are you missing a using
directive or an assembly reference?)
13.'System.Web.UI.WebControls.Table' does not Contain a definition for
'Create' and no extension method
'Create' accepting a first argument of
type 'Systen.Web.UI.WebControls.Table'
could be found(are you missing a using
directive or an assembly reference?)
The code written in c# behind the button is that:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
//using System.Data.OleDb;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Data.SqlClient;
//using System.Data.Odbc;
using Microsoft.SqlServer.Management.Common;
//using ADOX;
//using ADODB;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
// Establish the database server
string connectionString = ConfigurationManager.ConnectionStrings["gameConnectionString"].ConnectionString;
SqlConnection connection =
new SqlConnection(connectionString);
Server server =
new Server(new ServerConnection(connection));
// Create table in my personal database
Database db = server.Databases["game"];
// Create new table, called TestTable
Table newTable = new Table(db, "TestTable");
// Add "ID" Column, which will be PK
Column idColumn = new Column(newTable, "ID");
idColumn.DataType = DataType.Int;
idColumn.Nullable = false;
idColumn.Identity = true;
idColumn.IdentitySeed = 1;
idColumn.IdentityIncrement = 1;
// Add "Title" Column
Column titleColumn = new Column(newTable, "Title");
titleColumn.DataType = DataType.VarChar(50);
titleColumn.Nullable = false;
// Add Columns to Table Object
newTable.Columns.Add(idColumn);
newTable.Columns.Add(titleColumn);
// Create a PK Index for the table
Index index = new Index(newTable, "PK_TestTable");
index.IndexKeyType = IndexKeyType.DriPrimaryKey;
// The PK index will consist of 1 column, "ID"
index.IndexedColumns.Add(new IndexedColumn(index, "ID"));
// Add the new index to the table.
newTable.Indexes.Add(index);
// Physically create the table in the database
newTable.Create();
}
}
sir please solve these errors and also give the solution in detail through which i can easily understand.I am very confused in this task please help me.Thank sir
Suggest abandoning your current approach. The problems go beyond namespacing. Suggest taking these steps:
create a brand new test project for the following
determine the SQL statements for
creating a table with all columns
creating the index
execute the SQL statements above using ADO.NET. Suggest a SqlConnection and SqlCommand.
Something like this:
using (var conn = new SqlConnection(connString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = createTableStatement; //CREATE TABLE Foo (ID int);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = createIndexStatement;
cmd.ExecuteNonQuery();
}
}
This will get you started on accomplishing your task. Be sure that any user-entered data aren't simply placed into your strings to create your objects. If so, change the approach to use parameters with your SqlCommand.
Here's an article on Beginner's Guide to Accessing SQL Server Through C#

Categories

Resources