[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Reference external file C#

Posted on 2010-01-07
28
Medium Priority
?
497 Views
Last Modified: 2013-12-17
Ok I have created s a windows form application that has mutiply files. How do I link/add/reference these files to the form and call functions within those files? The application is written in C#.
0
Comment
Question by:seahna
  • 15
  • 13
28 Comments
 
LVL 6

Expert Comment

by:Tribmos
ID: 26203576
What type of files are they?

dll?  then you use [dllimport]

text files? then you just use a stream reader

sub forms? Form frm = new FormX(...);  frm.Show();

More info please.
0
 

Author Comment

by:seahna
ID: 26203670
I am trying to link this file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Security.Principal;
using System.Xml;
using Stentofon.AlphaCom.AlphaNet.Client;
using Stentofon.AlphaCom.Data.State;


namespace ExchangeConnection
{
    public class Connect
    {
        private AlphaComState _stateStorage;
        private AlphaNetClient _alphaNetClient;

        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"]; 

        public void exchange_Connect(string ConfigFileName)
        {
            XmlDocument configFile = new XmlDocument();
            configFile.Load(ConfigFileName);
            string alphaComIP = string.Format("Setup/ACSP/Primary/IPAddress");
            string ipPort = string.Format("Setup/ACSP/Primary/IPPort");

            string ipPortString = ReadValueFromXmlDocumentAtXPath(configFile, ipPort);
            int alphaComPort = int.Parse(ipPortString);

            // Initialiaze inMemory State Data Storage
            _stateStorage = new AlphaComState(AlphaComStateStorages.IN_MEMORY);

            _alphaNetClient = new AlphaNetClient(alphaComIP, alphaComPort)
            {
                AutoDiscoverAllNodes = true,
                AutoGetStationState = true,
                VerboseLevel = VerboseLevel.NONE
            };

            // Register for TCP connection Down event
            _alphaNetClient.OnNodeConnectionDown += HandleOnNodeConnectionDown;

            _alphaNetClient.StartListening();
            _alphaNetClient.StartMonitorThread();
        }

        public string ReadValueFromXmlDocumentAtXPath(XmlDocument configFile, string xpath)
        {
            string value = string.Empty;
            XmlNode myNode = configFile.SelectSingleNode(xpath);
            if (myNode != null && myNode.InnerText != null)
            {
                value = myNode.InnerText;
            }
            return value;
        }

        //method for handling event above
        private void HandleOnNodeConnectionDown(int node, int status)
        {
            //do something
        }
    }
}

Open in new window

0
 

Author Comment

by:seahna
ID: 26203678
To this form after validation happens
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows;
using System.Security.Principal;
using System.Xml;

namespace AV4._1_ClientTool.Dialogs1
{
    public partial class Login1 : Form
    {
        public Login1()
        {
            InitializeComponent();
        }

        private int no_of_attempts = 0; //must be defined outside scope of event handler
        private static string ConfigFileName = ConfigurationManager.AppSettings["ConfigFileName"]; 
        private static int maxLoginAttempts = 2;

        private void evLoginOk1_Click(object sender, EventArgs e)
        {
            no_of_attempts++;               //Variable to count the number of attempts made by the user

            bool valid = IsLoginValid(ConfigFileName, LoginIDTextBox1.Text, LoginPWTextBox1.Text);

            //If information is validated the login window will close and the application main window will diplay.
             //If the incorrect information is input then the error message will display if the incorrect informaiton
             //is input more then three time then the exceed login attempt window will display and the application will close. 
            if (valid)
            {
                AV4._1_ClientTool.Dialogs1.MainWin1 mainWin1 = new AV4._1_ClientTool.Dialogs1.MainWin1();
                mainWin1.Show();
                this.Hide();
            }
            else
            {//if the user and password come back invalid the error message will appear on the screen
                //and the user will need to click ok to try again. 
                if (no_of_attempts <= maxLoginAttempts)            //tracks the number of attempts made by the user to login to the system.
                {
                    AV4._1_ClientTool.Dialogs1.Error errorWin1 = new AV4._1_ClientTool.Dialogs1.Error();
                    errorWin1.Show();
                }
                else
                {
                    AV4._1_ClientTool.Dialogs1.ExceedsAttempts exceedWin1 = new AV4._1_ClientTool.Dialogs1.ExceedsAttempts();
                    exceedWin1.Show();
                }
            }
        }

        public bool IsLoginValid(string ConfigFileName, string username, string password)
        {
            XmlDocument myDoc = new XmlDocument();
            myDoc.Load(ConfigFileName);
            string passwordXPath = string.Format("Setup/Logins/Login[ID='{0}']/PW", username);
            XmlNode passwordNode = myDoc.SelectSingleNode(passwordXPath);
            if (passwordNode == null)
            {
                return false;
            }
            if (passwordNode.InnerText.Equals(password)) //username and password match! 
            {
                return true;
            }
            return false;
        }
      
        //cancel entery into application
        private void evCancel1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Open in new window

0
Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 

Author Comment

by:seahna
ID: 26203694
The file I am trying to link is code to connect my application to a sever after a user is validated that is all.
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26203829
Login1 seems like a login page where you have an OK/Cancel
and the Connect class tries to do a connection

Not sure what your are asking help on.

In my mind i see a client/server connect doing the following: routine to start a connection, shows a dialog to ask for username/pass, returns that back to the connection class which tries to login.  If succede return the connection to the caller  else throw an error and/or reprompt user/pass dialog.

Is that what you are trying to accomplish?

0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26203915
see your 3rd post now.

Login1 frm = new Login1();
DialogResult dr = frm.ShowDialog();
if (dr == DialogResult.OK)
{
frm.UserName
frm.Password
//do connection stuff
} else if (dr == DialogResult.Cancel)
{
//user hit cancel
} else if (dr == DialogResult.Abort)
{
//Invalid tries used
}

Then inside your Login1 routine change those hide/shows to
DialogResult = DialogResult.OK (or cancel/abort)

What you are doing there is passing the control back to the caller rather then having the login page handle the actions.

For example in the OK click routine.  Check the validation, if its ok  set DialogResult = DialogResult.OK and return.  otherwise just let the user try again (maybe stick a wait in there that increases with failures)

On a form called with ".ShowDialog" when the DialogResult of that form is set, it considers it finished and will hide and return control back to the caller.  Since in the caller you still have the form object. you can reference any public properties/methods of it (in this case you know the login is valid so get the .Username and .Password property [a simple get/set routine that references the text box works])

0
 

Author Comment

by:seahna
ID: 26203983
I an confused you didn't say how to connect the two files. I have file 1 which if the user login form and I have file two which is the connection code they are in the same project but not in the same file so I don't understand what it is you are saying.
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26204045
Hmmm.. how to best describe an abstract concept.  One moment
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26204074
Does the connect class need to happen first or does that need to be used after you login?
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26204150
if the connect should happen after the login info.  then one method is to put the connect class as a public static member of class.
example:
global.cs
public static class global
{
  public static Connect my_connect = null;
}

so you do the login and after you verify that its an ok login and need to go to the next step you can do
global.my_connect = new Connect();
then open up whatever form you want.

then any form can access this connect class either by subscribing to a custom event queue (handle incoming events) or write out their own messages global.my_connect.CustomMethodHere(...)

Just make sure that before closing the application you "shutdown" the connect class (if it needs anything like closed connections/thread aborts/etc) so that everything is handled gracefully.

If you need to do the login after the connection. then something similar can work; its just in a different order.
0
 

Author Comment

by:seahna
ID: 26204167
the connection happens after validation of the users login information.
0
 

Author Comment

by:seahna
ID: 26204200
I am not understanding you I have the connection code already written. in the code label ExchangeConnection above. All I want to know how to do is get the methods written in this file read into my file Login1 then run and execute that code to connect to the server.
0
 

Author Comment

by:seahna
ID: 26204208
Maybe if you use my code I have written above and use it as a base for your example I will understand you better.
0
 
LVL 6

Accepted Solution

by:
Tribmos earned 2000 total points
ID: 26204322
using ExchangeConnection; //at top

Connect my_connection_class = new Connect(); //in code

OR (without the using)

ExchangeConnection.Connect my_connection_class = new ExchangeConnection.Connect();

you do the following

my_connection_class.exchange_Connect(.....<filename>....);

However do you only want the login page or do you want the whole program to be able to access the connection?
if just the login you can do the above, if you want the whole application you will need to declare the "my_connection_class" variable at a higher scope (like in a global package as 'public static')
0
 

Author Comment

by:seahna
ID: 26204404
I want the whole application to be able to access the connection.
0
 
LVL 6

Assisted Solution

by:Tribmos
Tribmos earned 2000 total points
ID: 26204515
Use the below code then  as a quick method.

Then when you are ready to make the connection just call

ExchangeConnection.ActiveConnection.MakeConnection(....);

and henceforth in the app you can reference the connection by

ExchangeConnection.ActiveConnection.my_connect

if you have the using clause for "ExchangeConnection" you can omit that portion.
namespace ExchangeConnection
{
    public static class ActiveConnection
   {
      public static Connect my_connect = null;
      public static void MakeConnection(string ConfigFileName)
      {
          ActiveConnection.my_connect = new Connect();
          ActiveConnection.my_connect.exchange_Connect(ConfigFileName);
      }
   }

    public class Connect
    {
 ...what you had...
    }
}

Open in new window

0
 

Author Comment

by:seahna
ID: 26204657
Ok so I do this and the application will stay connected until the user loges out...Right?
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26204728
Well you could make a "logout" routine.

What that is doing is moving the scope of the object.

Normally if you declare an object (like an int) inside a class. it can only be accessed in that class.   If it was declared in a method, then its only usable in the method.   With what i described; the whole application can access it

So yes, until you close that object (or otherwise destroy it) it can be used.    You "may" have to check if its null before referencing it; or you could write some 'helper functions' in the ActiveConnection class that do it for you.

and FYI the file was not "external" it was just in a different namespace.  
0
 

Author Comment

by:seahna
ID: 26204835
Ok I am am not sur eI understand where to put everything and I am sorry I am being such a pain I just never done something like this before and am still learning.

I want the application to have a constant connection while the user is loged into the application. I added this where you said to:

using ExchangeConnection;

and I added :

    public static class ActiveConnection
   {
      public static Connect my_connect = null;
      public static void MakeConnection(string ConfigFileName)
      {
          ActiveConnection.my_connect = new Connect();
          ActiveConnection.my_connect.exchange_Connect(ConfigFileName);
      }
   }

and this line I added in the login namespace after the validation happens:

Connect my_connection_class = new Connect();

but I am not sure what to do with these lines:

ExchangeConnection.ActiveConnection.MakeConnection(....); ...what is the (...) mean?

&

ExchangeConnection.ActiveConnection.my_connect

once the connection is made I want it to stay until the application is closed because the apllication need to be able to communicate with the exchange while running.
0
 
LVL 6

Assisted Solution

by:Tribmos
Tribmos earned 2000 total points
ID: 26205082
MakeConnect(...)  i use "..." to mean "whatever should go there"  since as you see in the defination it takes a string, but i'm leaving that to you to fill in

If your using the global method.  then you do not need to use the
Connect my_connection_class = new Connect();
because that will only exist in the small scope (ie the ok click procedure)

Thats why i listed to use the

ExchangeConnection.ActiveConnection.MakeConnection(....);

<namespace>.<public static class>.<public static method>(<function parms>);
so in this case  your telling the code to look at the "exchangeConnection" namespace for the class "ActiveConnection" and you want to call the function "makeconnection"

which if you look at what that class/function does.  it sets the public static "my_connection" to a new connect object.

Then anywhere else in the program you can do.

if (ExchangeConnection.ActiveConnection.my_connect != null)
  ExchangeConnection.ActiveConnection.my_connect.SomeMethod(....);

This will verify that the connection was created (which logicallly it should be if the code is executed in order, but that is more of a sanity check)
0
 

Author Comment

by:seahna
ID: 26205151
ok so what string should go in the ExchangeConnection.ActiveConnection.MakeConnection(....);
0
 

Author Comment

by:seahna
ID: 26205233
Ok wiat I think I got my configfilename goes there.
0
 

Author Comment

by:seahna
ID: 26205283
Ok you said I could use this to test the connection

if (ExchangeConnection.ActiveConnection.my_connect != null)
  ExchangeConnection.ActiveConnection.my_connect.SomeMethod(....);

So use this that if the connection was made display this message in texbox1

Connection estblished.
0
 

Author Comment

by:seahna
ID: 26205368
For instance:
private void connection_state()
        {
            if (ExchangeConnection.ActiveConnection.my_connect != null)
            {
                richTextBox1.AppendText("Connection Established");

            }
        }

Open in new window

0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26292999
correct.   There is a very LOW chance that the my_connect will be null (unset) but that can only happen if somehow they bypass the login screen.

So  mostly for sanity sake you do that check when calling.  I would do an else case to throw a meaningful exception.  It could save you the headache of a "null pointer reference" 3 months down the road.
0
 

Author Comment

by:seahna
ID: 26293559
I forgot to ask you one last question. how does the dialogResult you were talking about work if I want to show another form?
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26297017
DialogResult acts like a return code; the act of setting it hides that form and gives control back to the caller.

See http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.aspx for more info about MesageBox
See http://msdn.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx for more info about DialogResult

An example of where I use DialogResult:

user requests to edit Preferences of MainForm
MainForm makes a PrefForm and initiates a showdialog
PrefForm is shown and current stored settings are loaded
User makes changes
User hits cancel : DialogResult.Cancel initiated and code returns control to mainform
User hits OK (or apply) : form runs checks on values aborting if errors are located and flagged.  If no errors set DialogResult.OK and then code return control to mainform
MainForm sees the DialogResult and if it was OK then reads the values from PrefForm and comits them to the stored settings

There are other ways to do this such as using bool or other variables you request from the form but to me and my coding style this ends up being a lot cleaner.  
0
 
LVL 6

Expert Comment

by:Tribmos
ID: 26297098
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Whether it be Exchange Server Crash Issues, Dirty Shutdown Errors or Failed to mount error, Stellar Phoenix Mailbox Exchange Recovery has always got your back. With the help of its easy to understand user interface and 3 simple steps recovery proced…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question