I'm facing currently a problem regarding Subsonic configuration.
What I want to achieve is using subsonic data access in a System.Web.UI.Design.ControlDesigner class.
This class is hosted in Visual Studio Environment and enables design time operations on the attached System.Web.UI.WebControls.Control.
The only problem is SubSonic seems always looking for SubSonicSection in the application configuration regardless passing connection string to it.
The relevant code snippet:
using (SharedDbConnectionScope dbScope = new SharedDbConnectionScope(new SqlDataProvider(), ConnectionString))
{
Table1 _table1 = new Select().From<..().Where(...).IsEqualTo(...).ExecuteSingle<...>();
Throws exception on ExecuteSingle() method (configuration section was not found)
while
using (SharedDbConnectionScope dbScope = new SharedDbConnectionScope(ConnectionString))
{
Throws exception on new SharedDbConnectionScope() (configuration section was not found)
So the question is:
Is there any way to pass the settings runtime to bypass the configuration section lookup as I don't want to add any subsonic specific configuration to devenv.configuration
Thanks
I don't think you can do this in 2.x without customising the templates (which can obviously give support issues when a newer version of SubSonic is released).
Sorry, don't know about 3.0
I'm assuming you're using SubSonic 2.x based on your query syntax. Have a look at the following two forum posts which should point you in the right direction. What you're trying to do is possible, in fact SubCommander does exactly this, download the source and have a look at the SetProviderManually() method.
http://forums.subsonicproject.com/forums/t/1617.aspx
http://forums.subsonicproject.com/forums/t/1502.aspx
The method to use Subsonic runtime provider configuration:
(example):
private void SetSubsonicProviderManually(string ConnectionString)
{
//clear the providers and reset
DataService.Provider = new SqlDataProvider();
DataService.Providers = new DataProviderCollection();
//instance a section - we'll set this manually for the DataService
SubSonicSection section = new SubSonicSection();
section.DefaultProvider = __SubsonicProviderName__;
//set the properties
DataProvider provider = DataService.Provider;
NameValueCollection config = new NameValueCollection();
//need to add this for now
config.Add("connectionStringName", __ConnectionString__);
//initialize the provider
provider.Initialize(__SubsonicProviderName__, config);
provider.DefaultConnectionString = ConnectionString;
DataService.Providers.Add(provider);
}
Related
I have the following code which is intended to fetch a list of all the user of an organisation.
public static IEnumerable<Member> ListTrelloUsers()
{
var serializer = new ManateeSerializer();
TrelloConfiguration.Serializer = serializer;
TrelloConfiguration.Deserializer = serializer;
TrelloConfiguration.JsonFactory = new ManateeFactory();
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
TrelloAuthorization.Default.AppKey = ApplicationKey;
TrelloAuthorization.Default.UserToken = GrandToken;
var myOrganization = Member.Me.Organizations.FirstOrDefault().Id; //Exception thrown here.
var orgToAddTo = new Organization(myOrganization);
return orgToAddTo.Members.AsEnumerable();
}
But I'm getting a
System.MissingMethodException
thrown on
RestSharp.IRestRequest RestSharp.RestRequest.AddFile(System.String, Byte[], System.String)
So why is this exception thrown and what should the correctly working code look like?
Clarifications
I will also accept working C#/ASP.Net MVC code that isn't based on Manatee.Trello as an answer. (Including pure API-calls.)
I have tried using the Organisation ID directly as
var orgToAddTo = new Organization(OrganisationId);
but that just caused the same exception to be thrown later when I make a call to the method's returned object (e.g. using Count()).
UPDATE: I tried setting the build to Release instead of Debug and now the (same) exception is instead thrown at
TrelloConfiguration.RestClientProvider = new RestSharpClientProvider();
This is an issue with RestSharp that I reported quite some time ago, though they deny that it's a problem. If you're using .Net 4.5+, you can try the Manatee.Trello.WebApi package instead of Manatee.Trello.RestSharp.
TrelloConfiguration.RestProvider = new WebApiClientProvider();
Here's my Trello card for tracking the issue. This and this are the RestSharp issues I created.
I have been able to recreate this as well, but have received no help from them to resolve it.
Apperently, the class with missing method is located in an assembly, which differ from the one, which you used while compiling the project. Double check and make sure both at compiling and at execution you use the same assembly with the aforementioned class.
That is my best clue based on the info you've provided.
basically, check project references and make sure, you use correct ones for the class-holding assembly.
I'm getting a warning while building my asp.net project that V1APIConnector is deprecated and requesting me to use VersionOneAPIConnector.
Using the new VersionOneAPIConnector I had to do the following to get a child projects:
build a string (ex: https://abc.org/V1/rest-1.v1/Data/Scope?where=Scope.Name='FOO'&sel=Children.Name) for the data we require and then pass it on to GetData method.
read the returned stream and then create an xml.
Read the xml to extract the required data.
Retrieving data using V1APIconnector was much simpler.
create a IMetaModel and services instance
query the appropriate assettype (GetAssetType method) and the attributes
(getAttributedefinition)
Is the above approach still valid using VersionOneAPIConnector?
If yes do we have any example on how to get the childprojects of a project?
Thanks
The compilation warnings that you are getting are because VersionOne.SDK.APIClient is currently using internally V1APIconnector, and this warnings are only shown because, I guess, you are including VersionOne.SDK.APIClient inside your project, this approach is, sometimes, not advisable because you may miss updates. The best thing to do should be to use nuget. Add to VS a reference (Tools -> Options -> Packate Manager -> Package Sources) to V1 gallery on myget.org (https://www.myget.org/F/versionone/), in this way you'll have your DLLs updated.
Regarding your questions:
There's no need for you to directly use VersionOneAPIConnector, but here you have two examples of listing child projects: one using Metamodel as you mention that you were using, and another using VersionOneAPIConnector.
//Example 1: Listing all child projects of 'Foo' with MetaModel
var assetType = _context.MetaModel.GetAssetType("Scope");
var query = new Query(assetType);
//Filter Attribute
var parentNameAttribute = assetType.GetAttributeDefinition("Parent.Name");
//Filter
var filter = new FilterTerm(parentNameAttribute);
filter.Equal("Foo");
query.Filter = filter;
var result = _context.Services.Retrieve(query);
Example 2: Listing all child projects of 'Foo' with VersionOneAPIConnector and V1 user and password.
Stream streamResult = new VersionOneAPIConnector("https://abc.org/v1sdktesting/rest-1.v1/Data/Scope?where=Parent.Name=%27Foo%27").WithVersionOneUsernameAndPassword("usr","pwd").GetData();
I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.
I've searched all over and I now have to ask SO. I'm trying to construct a simple dataflow using EzAPI. It's been anything but easy, but I'm committed to figuring this out. What I can't figure out is how to get the EzOleDBDestination working. Here's my complete code
var a = new Application();
// using a template since it's impossible to set up an ADO.NET connection to MySQL
// using EzAPI and potentially even with the raw SSIS API...
var pkg = new EzPackage(a.LoadPackage(#"C:\...\Package.dtsx", null));
pkg.Name = "Star";
var df = new EzDataFlow(pkg);
df.Name = "My DataFlow";
var src = new EzAdoNetSource(df);
src.Name = "Source Database";
src.SqlCommand = "SELECT * FROM enum_institution";
src.AccessMode = AccessMode.AM_SQLCOMMAND;
src.Connection = new EzConnectionManager(pkg, pkg.Connections["SourceDB"]);
src.ReinitializeMetaData();
var derived = new EzDerivedColumn(df);
derived.AttachTo(src);
derived.Name = "Prepare Dimension Attributes";
derived.LinkAllInputsToOutputs();
derived.Expression["SourceNumber"] = "id";
derived.Expression["Name"] = "(DT_STR,255,1252)description";
// EDIT: reordered the operation here and I no longer get an error, but
// I'm not getting any mappings or any input columns when I open the package in the designer
var dest = new EzOleDbDestination(df);
dest.AttachTo(derived, 0, 0);
dest.Name = "Target Database";
dest.AccessMode = 0;
dest.Table = "[dbo].[DimInstitution]";
dest.Connection = new EzConnectionManager(pkg, pkg.Connections["TargetDB"]);
// this comes from Yahia's link
var destInput = dest.Meta.InputCollection[0];
var destVirInput = destInput.GetVirtualInput();
var destInputCols = destInput.InputColumnCollection;
var destExtCols = destInput.ExternalMetadataColumnCollection;
var sourceColumns = derived.Meta.OutputCollection[0].OutputColumnCollection;
foreach(IDTSOutputColumn100 outputCol in sourceColumns) {
// Now getting COM Exception here...
var extCol = destExtCols[outputCol.Name];
if(extCol != null) {
// Create an input column from an output col of previous component.
destVirInput.SetUsageType(outputCol.ID, DTSUsageType.UT_READONLY);
var inputCol = destInputCols.GetInputColumnByLineageID(outputCol.ID);
if(inputCol != null) {
// map the input column with an external metadata column
dest.Comp.MapInputColumn(destInput.ID, inputCol.ID, extCol.ID);
}
}
}
Basically, anything that involves calls to ReinitializeMetadata() results in 0xC0090001, because that method is where the error happens. There's no real documentation to help me, so I have to rely on any gurus here.
I should mention that the source DB is MySQL and the target DB is SQL Server. Building packages like this using the SSIS designer works fine, so I know it's possible.
Feel free to tell me if I'm doing anything else wrong.
EDIT: here's a link to the base package I'm using as a template: http://www.filedropper.com/package_1 . I've redacted the connection details, but any MySQL and SQL Server database will do. The package will read from MySQL (using the MySQL ADO.NET Connector) and write to SQL Server.
The database schema is mostly irrelevant. For testing, just make a table in MySQL that has two columns: id (int) and description (varchar), with id being the primary key. Make equivalent columns in SQL Server. The goal here is simply to copy from one to the other. It may end up being more complex at some point, but I have to get past this hurdle first.
I can't test this now BUT I am rather sure that the following will help you get it working:
Calling ReinitializeMetadata() causes the component to fetch the table metadata. This should only be called after setting the AccessMode and related property. You are calling it before setting AccessMode...
Various samples including advice on debugging problems
define the derived column(s) directly in the SQL command instead of using a EzDerivedColumn
try to get it working with 2 SQL Server DBs first, some of the available MySQL ADO.NET provider have some shortcomings under some circumstances
UPDATE - as per comments some more information on debugging this and a link to a complete end-to-end sample with source:
http://blogs.msdn.com/b/mattm/archive/2009/08/03/looking-up-ssis-hresult-comexception-errorcode.aspx
http://blogs.msdn.com/b/mattm/archive/2009/08/03/debugging-a-comexception-during-package-generation.aspx
Complete working sample with source
I've had this exact same issue and been able to resolve it with a lot of experimentation. In short you must set the connection for both the source and destination, and then call the attachTo after both connections are set. You must call attachTo for every component.
I've written a blog about starting with an SSIS package as a template, and then manipulating it programmatically to produce a set of new packages.
The article explains the issue more.
I'm trying to create a program in C# that should be able to create, backup and restore a SQL Server database.
For this, the user needs to be able to setup a connection string to the desired SQL Server (and database).
I would like to use the same dialog as for example Visual Studio for creating the connection string.
Is this possible?
The data connection dialog component linked to in this answer is no longer available for download.
However, a (apparently somewhat altered) DataConnectionDialog component has since become available on NuGet.
Installation:
Add the component to your Visual Studio project via the NuGet package manager console:
Install-Package DataConnectionDialog
Usage example:
// using Microsoft.Data.ConnectionUI;
// using System.Windows.Forms;
bool TryGetDataConnectionStringFromUser(out string outConnectionString)
{
using (var dialog = new DataConnectionDialog())
{
// If you want the user to select from any of the available data sources, do this:
DataSource.AddStandardDataSources(dialog);
// OR, if you want only certain data sources to be available
// (e.g. only SQL Server), do something like this instead:
dialog.DataSources.Add(DataSource.SqlDataSource);
dialog.DataSources.Add(DataSource.SqlFileDataSource);
…
// The way how you show the dialog is somewhat unorthodox; `dialog.ShowDialog()`
// would throw a `NotSupportedException`. Do it this way instead:
DialogResult userChoice = DataConnectionDialog.Show(dialog);
// Return the resulting connection string if a connection was selected:
if (userChoice == DialogResult.OK)
{
outConnectionString = dialog.ConnectionString;
return true;
}
else
{
outConnectionString = null;
return false;
}
}
}
Note: The dialog component referred to below is no longer available for download. Unless you have retrieved it in the past, you will probably not get this answer's sample code to work.
Alternative: There is now a different DataConnectionDialog available on
NuGet. See this answer for details.
"Data Connection Dialog" on MSDN Archive Gallery (broken as of 1 Sept. 2015)
The data connection dialog is a database tool component released with Visual Studio. It allows users to build connection strings and to connect to specific data sources. try this..
C# Sample:
static void Main(string[] args)
{
DataConnectionDialog dcd = new DataConnectionDialog();
DataConnectionConfiguration dcs = new DataConnectionConfiguration(null);
dcs.LoadConfiguration(dcd);
if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
{
// load tables
using (SqlConnection connection = new SqlConnection(dcd.ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM sys.Tables", connection);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.HasRows);
}
}
}
}
dcs.SaveConfiguration(dcd);
}
Here source code also available. we can integrate and redistribute the source code with our application according to license.
Yes and no.
Yes, it is technically possible, but I urge you not to; that dialog is part of Visual Studio and is lot listed in "redist". My interpretation is that you are not free to redistribute this dll.
I think all the other answers here are out-of-date, but I found a current solution at code.msdn.microsoft.com:
Using Microsoft Visual Studio Connection Dialog at runtime
In Visual Studio when a developer wants to create strong typed classes for database tables either for the conventional TableAdapter or Entity Framework there is a place in the process where a dialog is displayed as shown below. I will show you how to do this at runtime and a bit more.
The download is a solution that builds the following dlls:
Microsoft.Data.ConnectionUI.Dialog.dll
Microsoft.Data.ConnectionUI.dll
Microsoft.Data.DataConnectionConfiguration.dll
The solution also contains a sample application showing how to use them.
Worked a treat for me and it is super easy.
You can use UDL file.
Configuring Data Controls to Use Universal Data Link (.udl) Files
You can use SQLConnectionStringUI Nuget package.
I created some code that will do this. The code is in GitHub and you can learn about it here: https://csharpdeveloper.wordpress.com/2020/05/07/a-c-net-dialog-for-connecting-to-sql-server/
Lin
Create your own form similar to Server Explorer Connection Setting window, and implement it. You cannot use that form meant for VS