I am creating a windows desktop application using c# , my solution has 2 projects
the first one is a project that hold all the GUI and classes for a Login system (using SQL db) , after the a success login my function return the full data of the actual user :
private void Login(string User, string Pass)
{
DataTable Table = new DataTable();
Table = UserConnecction.Log_in(User, Pass);
int Count = Table.Rows.Count;
switch (Count)
{
case 1:
User_info.UserID = Convert.ToInt32(Table.Rows[0][0]);
User_info.UserName = Table.Rows[0][1].ToString();
User_info.Password = Table.Rows[0][2].ToString();
User_info.Email = Table.Rows[0][3].ToString();
User_info.Pack = Convert.ToInt32(Table.Rows[0][4]);
MessageBox.Show("" + User_info.UserID);
Main Main = new Main(User_info.UserName);
Main.ShowDialog();
this.Hide();
break;
case 0:
default:
MessageBox.Show("Incorrect Login ! ");
break;
}
}
And my second solution holds some functions that need the ID of the connected user , so I want basically to pass that parameter to the seonce project when the user login
I already tried to use the first project as a reference but it seems like you can only uses functions and classes and not passing a parameter cause it will always displays 0 !
Thank you !
Your 'main' project is the form-application. You need to reference the second project by Add reference (and click project-tab) and check the project you need.
Then in your first project, in a button_click handler or something you can use:
public void Button_loginHandler()
{
var x = new namespaceSecondProject.Class(constructor info);
}
So if I have one project (the second project in your class):
namespace TestProject
{
public class User
{
public string Username {get; set;}
public string Password {get; set;}
public datetime LastLoginDate {get;set;}
public void SetLastLogin()
{
LastLoginDate = datetime.now;
}
}
}
in your first project (your windows forms): you can use:
var newUser = new TestProject.User{ Username = "me", Password = "you"};
And if you want to use a function it is
newUser.SetLastLogin();
Pls note that this makes no sense, but hope to see that you can use classes and function like you want..
Related
I have developed an accounting program that is working beautifully, but now a new need has arisen.
When I enter the program, by default it reads the DB that I put in the file WinSCM.exe.config and if I want to change I have to exit the program and edit the file changing the DB name.
I did not want it to be this way, because my client does accounting for several companies and each company is a DB, so I wanted a way to select a company and when selecting this company the database is automatically changed in the release version.
I'm using Entity Framework to connect to Sql Server DB
Can someone help me?
I'm not sure what reading your DB is, but normally when you use Entity Framework you create a DbContext object whenever you need to do a query, or at utmost a few queries. You are not supposed to keep this DbContext alive for longer periods of time, say more than a few seconds. A minute would be very rare.
Whenever you create the Dbcontext instance you could use the default constructor that uses the config file to get the connection string to the database.
However one of the other constructors let you define the connection string to the database in the constructor. So if you want to construct your DbContext and connect it to a different database, just use that constructor
If you don't know the connection string, but you have a DbConnection to the database, there will be even a constructor for this case.
Hi Everybody Thank alot for your Answer. I just Solved My Question like this:
Fisrt of all, I created a class wich I called ConnetionTolls with this Content://.
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
********the way to use it is like this***************
//I use this method in a diferent Class
//This method returns the Entity i use with new connections
public static MyEntities SelectDb(String DataBase,String sqlUser,String pw, String serverInstance){
var selectedDbase = new MyEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDbase.ChangeDatabase
(
initialCatalog: DataBase,
userId: sqlUser,
password: pw,
dataSource: serverInstance// could be ip address 100.23.45.67 etc
);
return selectedDbase;
}
I want to thank everyone here and on other forums because this was the result of Your Contributions
I am trying to make sense of the dotMailer API for C#.
I have a class library where I intend to store the functionality that will consume the dotMailer API which references version 1.5 of the API. I also have a Service Reference set up from this WSDL
I was looking through the C# examples, but already I'm stumped! The following was pulled directly from here
Example of use in C#
/// <summary>
/// Adds a contact to an address book
/// </summary>
public void AddContactToAddressBook()
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
Console.WriteLine("AddContactToAddressBook");
Console.WriteLine("-----------------------");
// Get an instance to the web reference
com.apiconnector.API api = new com.apiconnector.API();
try
{
// we need a new contact
com.apiconnector.APIContact contact = new com.apiconnector.APIContact();
// populate the contact
contact.AudienceType = com.apiconnector.ContactAudienceTypes.B2B;
// populate the data fields
contact.DataFields = new com.apiconnector.ContactDataFields();
contact.DataFields.Keys = new string[3];
contact.DataFields.Values = new object[3];
contact.DataFields.Keys[0] = "FIRSTNAME";
contact.DataFields.Values[0] = "John";
contact.DataFields.Keys[1] = "LASTNAME";
contact.DataFields.Values[1] = "Smith";
contact.DataFields.Keys[2] = "POSTCODE";
contact.DataFields.Values[2] = "IP4 1XU";
// email address
contact.Email = "joe.smith#example.com";
contact.EmailType = com.apiconnector.ContactEmailTypes.PlainText;
contact.Notes = "This is a test only email";
contact.OptInType = com.apiconnector.ContactOptInTypes.Single;
// This method will create the contact required if it doesn't already exist within the dotMailer system,
// so we don't have to call CreateContact as a prerequisite.
//
// This method will also overwrite an existing contact, with the information provided here.
//
// This method will fail if you try to add a contact to the "Test" or "All Contacts" address books.
//
com.apiconnector.APIContact newContact = api.AddContactToAddressBook(username, password, contact, addressBookId);
// Did we get something back from the API ?
if (newContact != null)
{
Console.WriteLine("Contact added to address book {0} -> {1}", newContact.ID, addressBookId);
}
}
catch (SoapException ex) // catch any soap issues/errors from the web service
{
Console.WriteLine("Error -> {0}", ex.Message);
}
Console.WriteLine();
}
My problem is that the following line does not resolve.
com.apiconnector.API api = new com.apiconnector.API();
I have looked in namespace dotMailer.Sdk.com.apiconnector for API but it does not exist, so where is it?
Am I missing something?
Add the wsdl as a service reference. In the example below I've called it "ServiceReference1" (because that's the default and I was lazy). You then use the reference to the APISoapClient (I've called it Client) instead of "api" that you're having trouble declaring.
All compiles fine, I'm not going to execute it because I've no idea what shenanigans my random code snippet is going to cause for the server! Should point you in the right direction?
using WindowsFormsApplication1.ServiceReference1;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string username = "apiuser-XXXXXXXXXXXX#apiconnector.com";
const string password = "password";
const int addressBookId = 1; // ID of the target address book
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddContactToAddressBook();
}
private void AddContactToAddressBook()
{
using (ServiceReference1.APISoapClient Client = new ServiceReference1.APISoapClient())
{
APIContact Contact = new APIContact();
Contact.AudienceType = ContactAudienceTypes.B2B;
APIContact NewContact = Client.AddContactToAddressBook(username, password, Contact, addressBookId); // etc. etc.
}
}
}
}
I am using android SDK with Microsoft VS2010 C#. I want to use string values from my /resources/values/strings file in my C# code. Here is a piece of code that illustrates what I want to do. I am not getting the string value. I know that the resource id is an int, but what I need is the actual string value behind that id.
void vx2OkButton_Click(object sender, EventArgs e)
{
Log.Info(LOG_TAG, "Hello from OkButton|Enter()button"); // also used as Enter button
strVx20kButtonText = vx2OkButton.Text.ToString();
mDwnLdCodeEnteredByUser = vxxDwnldCodeEntered.Text.Trim();
string strDwnldCodeOut = mActCode.Bad.ToString();
if(strVx20kButtonText == Resource.String.Enter.ToString())
{
if (mDwnLdCodeEnteredByUser.Length < 1)
{
vxxSystemMsgBox.SetText(Resource.String.FieldRequried_);
m_txvEnterDwnLdCode.SetTextAppearance(this,Resource.Color.Red);
return;
}
// verify the dwnldcodeenter by the user matches the assigned to user when at the time the downloaded the app
mDwnLoadStatus = VerifyDwnLoadCode(mDwnLdCodeEnteredByUser);
if (mDwnLoadStatus == mDwnLdStatCode.BadDwnLdCode.ToString())
{
vxxSystemMsgBox.SetText(Resource.String.InvalidValueEntered);
m_txvEnterDwnLdCode.SetTextAppearance(this, Resource.Color.Red);
return;
}
mActionCD = mActCode.Ok.ToString();
vx2OkButton.SetText(Resource.String.OkButtonText);
vxxSystemMsgBox.SetText(Resource.String.ThanksPressOkButton);
m_txvEnterDwnLdCode.SetTextAppearance(this,Resource.Color.White);
return;
}
As you noticed, Resource.String.Enter is an integer generated for you that you can use to access the string resource. You can access it using the Android.Content.Res.Resources.GetString() method:
string enter = Resources.GetString(Resource.String.Enter);
I have an object which contains 2 pieces of information in objData[0]. The information is System_ID and Network_ID. The data is coming from a query to a database.
I want to get the data out of the object and display it in two separate text boxes, one for system_ID and one for Network_ID. Right now I am putting them into a combo box.
See below my code:
//get network ID and systenm name
private void cmbAddItem_SelectedIndexChanged(object sender, EventArgs e)
{
FASystems fSys = new FASystems(sConn);
object objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
cmbNetworkID.DataSource = objData;
cmbNetworkID.DisplayMember = "Network_ID";
cmbSysName.DataSource = objData;
cmbSysName.DisplayMember = "System_Name";
// txtNetworkID.Text = objData[0].Network_ID;
}
Assuming your C# compiler is 3.0 or up use the var keyword on the api call
var objData = fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
Let's assume you're correct that there is an array now in objData with a type in it that has at least Network_ID as a member...
txtNetworkID.Text = objData[0].Network_ID;
should work then.
Can you post the function declaration for getSystemNetworkIDFriendlyName and show how you are populating the return type?
I recommend creating a new class to store the NetworkID and SystemID
class SystemInfo
{
public string NetworkID { get; set; }
public string SystemId { get; set; }
}
Rewrite the function getSystemNetworkIDFriendlyName to return an instance of SystemInfo. Then populating your textbox becomes:
FASystems fSys = new FASystems(sConn);
SystemInfo inf o= fSys.getSystemNetworkIDFriendlyName(cmbAddItem.Text.ToString());
txtNetworkID.Text = info.NetworkID;
Hope this helps,
KenC
I am writing my first C# application, which in this case is just a "learning exercise" This example is a simplified block of code that I have used many times in VB.Net so I know that it works correctly. This is what the VB code looks like.
Public Class User
Private Const CN_LoginId As String = "Login"
Private Const CN_Password As String = "Password"
Private _password As String
Public Property Password() As String
Get
Return _password
End Get
Set(ByVal value As String)
_password = value
End Set
End Property
Public Shared Function Create(ByVal Login As String) As User
Dim usr = New User()
Using dt As DataTable = DAC.ExecuteDataTable("usp_PasswordSelect", _
DAC.Parameter(CN_LoginId, Login))
With dt.Rows(0)
usr.Password = CStr(.Item(CN_Password))
End With
End Using
Return usr
End Function
End Class
So in C# I have tried converting it by hand and by using Telerik's online conversion utility, which is what I am posting below because I am assuming that it is closer to the right answer then what I did myself.
public class User
{
private const string CN_LoginId = "Login";
private const string CN_Password = "Password";
private string _password;
public string Password
{
get { return _password; }
set { _password = value; }
}
public static User Create(string Login)
{
object usr = new User();
using (DataTable dt = DAC.ExecuteDataTable("usp_PasswordSelect",
DAC.Parameter(CN_LoginId, Login)))
{
{
usr.Password = Convert.ToString(dt.Rows(0).Item(CN_Password));
}
}
return usr;
}
}
The first error I get is on this line usr.Password = Convert.ToString(dt.Rows(0).Item(CN_Password));. The error is "Error 1 'object' does not contain a definition for 'Password' and no extension method 'Password' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
At this point I am assuming the second error will go away when I fix the first one. So my question is how do I correctly set the property for this Object using the DataTable in C#?
Here's how I'd write it:
public class User
{
private const string CN_LoginId = "Login";
private const string CN_Password = "Password";
public string Password { get; set; }
public static User Create(string Login)
{
User usr = new User();
using (DataTable dt = DAC.ExecuteDataTable("usp_PasswordSelect",
DAC.Parameter(CN_LoginId, Login)))
{
usr.Password = Convert.ToString(dt.Rows[0][CN_Password]);
}
return usr;
}
}
Some notes:
C# accesses arrays using square brackets, not parens. So Rows(0) isn't correct - it should be Rows[0].
I agree with Bernard that you should declare the User object as a User, and not as an object. You'll lose all visibility into it's properties. You can also use var, but if you're learning C#, you may be better off explicitly declaring your variable types. It can make for duplicate declarations (e.g. User u = new User()) but at least you'll see clearly what types your variables are.
You don't need to access array items using Item...just get it as an element in the row element you're working with. That's why I have the double array for dt.Rows[0][CN_Password]. Again, C# uses square brackets, not parens for accessing array elements.
This is just a style thing, but I removed your _password field and just used an automatic property for Password. I didn't see _password being used in your code and thought it would just clutter things up. Automatic properties have a backing field automatically created by the compiler, so you don't have to keep track of the variable and the property. If you're using a lot of properties, this can be a big time saver.
You need to declare the type of user (in your code user is an object that is at runtime a USer, but not at compiletime). You can do the following:
var user = new User();
or
User user = new User();
In addition to the comments.
As Jonathan Dickinson correctly says ,
user.Password = dt.Rows[0]["Password"];
should do it since this is an indexer.