0

I am trying to execute a WPF Class library from a console app built in the same solution in VS2012. I have established I need to do this after my first encounter with this error

A project with an output type of class library cannot be started directly. In order to debug this project, add an executable project to this solution which references the library project. Set the executable project as the startup project.

This is when I added another console project and added the initial WPF as a reference for the console app. I have also right-click on the solution>Properties>Startup project> I have selected the Console project and checked "Single startup project"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Interfaces.Connection;

namespace API
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Do I need to do something in here to call the initializecomponent() method from the WPF project???");

        Console.ReadLine();            
    }
}

}

As the code writeLine says, do I need to do something in the Main() method in program.Cs of the console application to call initializecomponent or something within that WPF?? Because when I run the solution when Main() is fully empty, it seems to just run the console app. It opens and closes the command line really quick.

Here are all the code for the WPF project if you need.

Client.cs

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Interfaces.Connection.ApplicationService;

namespace Interfaces.Connection
{
/// <summary>
/// This class is used to operate on the  web service.
/// </summary>
public class Client
{
    public ApplicationServiceClient Client { get; private set; }
    public string Username { get; set; }
    public string Context { get; set; }
    public string Password { get; set; }

    /// <summary>
    /// Initializes a new instance of the <see cref="Client"/> class.
    /// </summary>
    /// <param name="client">The client.</param>
    public Client(ApplicationServiceClient client)
    {
        Client = client;
    }

    /// <summary>
    /// Pings the web service.
    /// </summary>
    /// <returns></returns>
    public bool Ping()
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            PingResponse pingResponse = (PingResponse)Client.Run(new PingRequest());
            return pingResponse != null;
        }
    }

    /// <summary>
    /// Creates an instance of a given entity.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="pivotMember">The pivot member.</param>
    /// <param name="parent">The parent.</param>
    /// <returns></returns>
    public Instance Create(string entityName, Guid? pivotMember, ParentReference parent)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.Create(entityName, pivotMember, parent);
        }
    }

    /// <summary>
    /// Saves the specified instance.
    /// </summary>
    /// <param name="instance">The instance.</param>
    public void Save(Instance instance)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            Client.Save(instance);
        }
    }

    /// <summary>
    /// Deletes the instance with the specified primary key.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="id">The id.</param>
    public void Delete(string entityName, Guid id)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            Client.Delete(entityName, id);
        }
    }

    /// <summary>
    /// Selects an instance by its primary key.
    /// </summary>
    /// <param name="entityName">Name of the entity.</param>
    /// <param name="id">The id.</param>
    /// <returns></returns>
    public Instance SelectById(string entityName, Guid id)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.SelectById(entityName, id);
        }
    }

    /// <summary>
    /// Executes the given QueryBase and returns the result.
    /// </summary>
    /// <param name="query">The query.</param>
    /// <returns></returns>
    public QueryResult SelectByQuery(QueryBase query)
    {
        using (OperationContextScope scope = new OperationContextScope(Client.InnerChannel))
        {
            AddCredentials();
            return Client.SelectByQuery(query);
        }
    }

    private void AddCredentials()
    {
        const string contextNamespace = "http://.com/2011/servicecontracts/headers";
        const string contextName = "ContextualPerspective";
        const string userNameHeaderName = "UserName";
        const string passwordHeaderName = "Password";

        MessageHeader activeMember = MessageHeader.CreateHeader(contextName, contextNamespace, Context);
        OperationContext.Current.OutgoingMessageHeaders.Add(activeMember);

        MessageHeader userNameHeader = MessageHeader.CreateHeader(userNameHeaderName, contextNamespace, Username);
        OperationContext.Current.OutgoingMessageHeaders.Add(userNameHeader);

        MessageHeader userPasswordHeader = MessageHeader.CreateHeader(passwordHeaderName, contextNamespace, Password);
        OperationContext.Current.OutgoingMessageHeaders.Add(userPasswordHeader);
    }
}
}

MainWindowXAML(this is the window)

<Window x:Class="Interfaces.Connection.ConnectionDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="API Connector" Height="Auto" Width="525">
<Grid Background="#F0F0F0">
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Margin" Value="10,10,5,5"/>
        </Style>
        <Style TargetType="Button">
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Height" Value="26"/>
            <Setter Property="Width" Value="100"/>
        </Style>
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Text="Varasset Server Url" />
    <TextBox x:Name="txtVarassetServer" Grid.Column="1" Margin="5,10,10,5" />

    <TextBlock Grid.Row="1" Text="Username" />
    <TextBox x:Name="txtUsername" Grid.Row="1" Grid.Column="1" Margin="5,5,10,5" />

    <TextBlock Grid.Row="2" Text="Member Code" />
    <TextBox x:Name="txtContext" Grid.Row="2" Grid.Column="1" Margin="5,5,10,5" />

    <TextBlock Grid.Row="3" Text="Password" />
    <PasswordBox x:Name="txtPassword" Grid.Row="3" Grid.Column="1" Margin="5,5,10,5" />

    <Border Grid.Row="4" Grid.ColumnSpan="2" Margin="10,10,10,0" Height="1" BorderBrush="Gray" BorderThickness="0,1,0,0"/>

    <StackPanel Grid.Row="5" Grid.Column="1" Orientation="Horizontal" Margin="10"
                HorizontalAlignment="Right" VerticalAlignment="Bottom">
        <Button x:Name="btnOk"  Click="btnOk_Click">OK</Button>
        <Button x:Name="btnCancel" Margin="10,0,0,0" Click="btnCancel_Click">Cancel</Button>
    </StackPanel>

</Grid>

MainWindowxaml.cs(its CS)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.SqlServer.Dts.Runtime.Design;
using Microsoft.SqlServer.Dts.Runtime;

namespace Interfaces.Connection
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class ConnectionDialog : Window
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ConnectionDialog"/> class.
    /// </summary>
    /// <param name="context">The context.</param>
    public ConnectionDialog(ConnectionManagerUI context)
    {
        InitializeComponent();
        DataContext = context;

        txtPassword.Password = context.Password;
        txtUsername.Text = context.Username;
        txtContext.Text = context.Context;
        txtServer.Text = context.Address;
    }

    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        ConnectionManagerUI manager = ((ConnectionManagerUI)DataContext);
        manager.Password = txtPassword.Password;
        manager.Username = txtUsername.Text;
        manager.Context = txtContext.Text;
        manager.Address = txtServer.Text;
        Close();
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}
}

There are couple more files, but I do not think they are relevant at this point.

I have tried calling initializeComponent from main like this as well.

Interfaces.Connection.ConnectionDialog app = new Interfaces.Connection.ConnectionDialog();
app.InitializeComponent();

But it then gives error saying

Interfaces.Connection.ConnectionDialog' does not contain a constructor that takes 0 arguments.

And I am not sure what arguments it expects.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime.Design;
using Microsoft.SqlServer.Dts.Runtime;

namespace Interfaces.Connection
{
/// <summary>
/// This class extends the class Microsoft.SqlServer.Dts.Runtime.Design.IDtsConnectionManagerUI.
/// </summary>
public class ConnectionManagerUI : IDtsConnectionManagerUI
{
    private ConnectionManager _connectionManager;
    private IServiceProvider _serviceProvider;

    /// <summary>
    /// Gets or sets the username.
    /// </summary>
    /// <value>
    /// The username.
    /// </value>
    public string Username
    {
        get
        {
            var property = _connectionManager.Properties["Username"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Username"].SetValue(_connectionManager, value); }
    }

    /// <summary>
    /// Gets or sets the context (member code).
    /// </summary>
    /// <value>
    /// The context.
    /// </value>
    public string Context
    {
        get
        {
            var property = _connectionManager.Properties["Context"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Context"].SetValue(_connectionManager, value); }
    }

    /// <summary>
    /// Gets or sets the password.
    /// </summary>
    /// <value>
    /// The password.
    /// </value>
    public string Password
    {
        get 
        {
            var property = _connectionManager.Properties["Password"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Password"].SetValue(_connectionManager, value); }
    }

    /// <summary>
    /// Gets or sets the address.
    /// </summary>
    /// <value>
    /// The address.
    /// </value>
    public string Address
    {
        get
        {
            var property = _connectionManager.Properties["Address"].GetValue(_connectionManager);
            return property == null ? string.Empty : property.ToString();
        }
        set { _connectionManager.Properties["Address"].SetValue(_connectionManager, value); }
    }

    /// <summary>
    /// Method not implemented.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    public void Delete(System.Windows.Forms.IWin32Window parentWindow)
    {
        throw new NotImplementedException("Delete");
    }

    /// <summary>
    /// Edits an existing connection manager.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    /// <param name="connections">The connections available for editing.</param>
    /// <param name="connectionUIArg">A class that implements the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.ConnectionManagerUIArgs"/>, such as the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.FileConnectionManagerUIArgs"/> or <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.MultiFileConnectionManagerUIArgs"/>.</param>
    /// <returns>
    /// true if the connection manager was modified.
    /// </returns>
    public bool Edit(System.Windows.Forms.IWin32Window parentWindow, Microsoft.SqlServer.Dts.Runtime.Connections connections, ConnectionManagerUIArgs connectionUIArg)
    {
        return new ConnectionDialog(this).ShowDialog().GetValueOrDefault();
    }

    /// <summary>
    /// Initializes the connection manager user interface. This method is called when you need to create connections of a specific type.
    /// </summary>
    /// <param name="connectionManager">The connection manager to initialize.</param>
    /// <param name="serviceProvider">The object used to get registered services. Defines a mechanism for retrieving services offered by the designer for such activities as monitoring changes to components.</param>
    public void Initialize(Microsoft.SqlServer.Dts.Runtime.ConnectionManager connectionManager, IServiceProvider serviceProvider)
    {
        _connectionManager = connectionManager;
        _serviceProvider = serviceProvider;
    }

    /// <summary>
    /// Provides notification to tasks of newly created connection managers. This method is called after a new connection manager is added to the package.
    /// </summary>
    /// <param name="parentWindow">The IWin32Window interface of the designer hosting the task.</param>
    /// <param name="connections">The connections collection to add the new connection to, or the connections to show in a drop-down or other control in the user interface.</param>
    /// <param name="connectionUIArg">A class that implements the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.ConnectionManagerUIArgs"/>, such as the <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.FileConnectionManagerUIArgs"/> or <see cref="T:Microsoft.SqlServer.Dts.Runtime.Design.MultiFileConnectionManagerUIArgs"/>.</param>
    /// <returns>
    /// true if a new connection was created.
    /// </returns>
    public bool New(System.Windows.Forms.IWin32Window parentWindow, Microsoft.SqlServer.Dts.Runtime.Connections connections, ConnectionManagerUIArgs connectionUIArg)
    {
        return new ConnectionDialog(this).ShowDialog().GetValueOrDefault();
    }
}
}

Thanks in advance!

EDIT I have changed program.cs Main() method to:

class Program
{
    static void Main(string[] args)
    {
        ConnectionManagerUI connectionManagerUI = new ConnectionManagerUI;
        ConnectionDialog dialog = new ConnectionDialog(ConnectionManagerUI);          
    }
}

It runs now, but it gives error

An unhandled exception of type "System.InvalidOperationException' occurred in PresentationCore.dll Additional Information: The calling thread must be STA, because many UI components require this.

If I need to create a new post or I can research first before posting. But Tim was able to solve this post's issue.

END of EDIT

11
  • Why are you not just creating a WPF app project and running that? I ask because you refer to it as an WPF app... if it has to be a class library (with WPF windows in it) then ok, we can help you. Just want to make sure we're not missing the forest for the trees. Commented Jul 10, 2013 at 17:32
  • that's how it was originally. Just a WPF project. But when I ran it, it gave error: The first error in my question at very top. I researched and found that it needed to be called by either console/web app. Commented Jul 10, 2013 at 17:35
  • oh well, then it's just a WPF class library. Sorry I am new to c# development:) I can edit my post to avoid confusion. Commented Jul 10, 2013 at 17:37
  • Yeah, if you made it a WPF Application instead of a class library, you'd be able to just run it. There's no reason to go through the hoops you're trying to go through if you don't have to. You say its in the same solution, right? So you have the code and could make it a WPF App? Commented Jul 10, 2013 at 17:39
  • As Tim said you have to create and object of ConnectionManagerUI and pass it to the Constructor of ConnectionUI. Commented Jul 10, 2013 at 17:46

1 Answer 1

1

While we're sorting out the real issue, I'll go ahead and say that the final problem you're having is that the constructor for your ConnectionDialog is defined as

public ConnectionDialog(ConnectionManagerUI context)
{
    ...
}

See how it takes a ConnectionManagerUI object as a parameter? I don't know what that class is (you didn't share that code), but you'll need to pass one of those into the constructor

Edit: Now that you've added the code for that I can see that it has a default constructor so I'll change that code to this:

ConnectionManagerUI connectionManagerUI = new ConnectionManagerUI();
ConnectionDialog dialog = new ConnectionDialog(connectionManagerUI);

Also, don't call .InitializeComponent() on the dialog. That should only really be called from the constructor (which it is). calling it twice would be bad.

That said, that doesn't solve your root problem, which is that you just want to be doing a WPF app it seems :)

Edit: Still, like I said, that's not your root problem. You shouldn't be doing things this way unless you have to, and I doubt you have to.

Sign up to request clarification or add additional context in comments.

14 Comments

ok, i am including that Class as well. That was one of the files i thought irrelevant at this point. shows how much i know..lol...i added it to my post. let me know, i would appreciate it :)
Tim it calls it correctly now, but it gave error. An error obviously i haven't seen yet since i haven't been able to get this far....lo..but your solution worked. If you want to check on that new EDIT i have which shows the new error, you can..but i'm going to research that error through the net...thanks man!
@Tim, would you advise someone to make an instance of ConnectionManagerUI if they didn't know what it was? And then pass it to a dialog they don't know what it is?
Certainly not. I've been trying to convince the OP that this wasn't the actual problem. I wanted to answer his specific question of how to use the constructor, but I also wanted to point out that his true problem probably lay elsewhere. Not sure that's gotten across.
LOL! I'm with you. Opening a black-box dialog, and if he already has local admin rights? and presumably the app is running in full trust?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.