First Off I have a File That Looks Like This:
//Manager Ids
ManagerName: FirstName_LastName
ManagerLoginId: 12345
And a Text Box That has a five digit code(ex. 12345) That gets entered. When the Enter Key Is pressed it is assigned to a String called: "EnteredEmployeeId", Then What I need is to search the Entire file above for "EnteredEmployeeId" and if it matches then it will open another page, if it doesn't find that number then display a message(That tells you no employee Id found).
So essentially Im trying to open a file search the entire document for the Id then return true or false to allow it too either display an error or open a new page, and reset the EnteredEmployeeId to nothing.
My Code So Far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Rent_a_Car
{
public partial class Employee_Login_Page : Form
{
public Employee_Login_Page()
{
InitializeComponent();
}
string ManagersPath = #"C:\Users\Name\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
string EnteredEmployeeId;
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && //Checks Characters entered are Numbers Only and allows them
(e.KeyChar != '0'))
{
e.Handled = true;
}
else if (e.KeyChar == (char)13) //Checks if The "Enter" Key is pressed
{
EnteredEmployeeId = Employee_Id_TextBox.Text; //Assigns EnteredEmployeeId To the Entered Numbes In Text Box
bool result = ***IsNumberInFile***(EnteredEmployeeId, "ManagerLoginId:", ManagersPath);
if (result)
{
//open new window
}
else
{
MessageBox.Show("User Not Found");
}
}
}
}
}
This function will read through whole file and find if there is inserted code. It will work with strings (as it is output of your text box) and will return only true or false (employee is or is not in file) not his name, surname etc.
static bool IsNumberInFile(string numberAsString, string LineName, string FileName)
{
var lines = File.ReadAllLines(FileName);
foreach(var line in lines)
{
var trimmedLine = line.Replace(" ", ""); //To remove all spaces in file. Not expecting any spaces in the middle of number
if (!string.IsNullOrEmpty(trimmedLine) && trimmedLine.Split(':')[0].Equals(LineName) && trimmedLine.Split(':')[1].Equals(numberAsString))
return true;
}
return false;
}
//Example of use
String ManagersPath = #"C:\Users\Name\Visual Studios Project Custom Files\Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
String EnteredEmployeeId;
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && //Checks Characters entered are Numbers Only and allows them
(e.KeyChar != '0'))
{
e.Handled = true;
}
else if (e.KeyChar == (char)13) //Checks if The "Enter" Key is pressed
{
EnteredEmployeeId = Employee_Id_TextBox.Text; //Assigns EnteredEmployeeId To the Entered Numbes In Text Box
bool result = IsNumberInFile(EnteredEmployeeId, "ManagerLoginId" , ManagersPath)
if(result)
//User is in file
else
//User is not in file
}
}
}
Short answer
Is your question about how to read your file?
private bool ManagerExists(int managerId)
{
return this.ReadManagers().Where(manager => manager.Id == managerId).Any();
}
private IEnumerable<Manager> ReadManagers()
{
using (var reader = System.IO.File.OpenText(managersFileName))
{
while (!reader.EndOfStream)
{
string lineManagerName = reader.ReadLine();
string lineMangerId = reader.ReadLine();
string managerName = ExtractValue(lineManagerName);
int managerId = Int32.Parse(ExtractValue(lineManagerId));
yield return new Manager
{
Id = managerId,
Name = managerName,
}
}
}
private string ExtractValue(string text)
{
// the value of the read text starts after the space:
const char separator = ' ';
int indexSeparator = text.IndexOf(separator);
return text.SubString(indexSeparator + 1);
}
Long Answer
I see several problems in your design.
The most important thing is that you intertwine your manager handling with your form.
You should separate your concerns.
Apparently you have the notion of a sequence of Managers, each Manager has a Name (first name, last name) and a ManagerId, and in future maybe other properties.
This sequence is persistable: it is saved somewhere, and if you load it again, you have the same sequence of Managers.
In this version you want to be able to see if a Manager with a given ManagerId exists. Maybe in future you might want more functionality, like fetching information of a Manager with a certain Id, or Fetch All managers, or let's go crazy: Add / Remove / Change managers!
You see in this description I didn't mention your Forms at all. Because I separated it from your Forms, you can use it in other forms, or even in a class that has nothing to do with a Form, for instance you can use it in a unit test.
I described what I needed in such a general from, that in future I might even change it. Users of my persistable manager collection wouldn't even notice it: I can put it in a JSON file, or XML; I can save the data in a Dictionary, a database, or maybe even fetch it from the internet.
All that users need to know, is that they have to create an instance of the class, using some parameters, and bingo, you can fetch Managers.
You also give users the freedom to decide how the data is to be saved: if they want to save it in a JSON file, changes in your form class will be minimal.
An object that stores sequences of objects is quite often called a Repository.
Let's create some classes:
interface IManager
{
public int Id {get;}
public string Name {get; set;}
}
interface IManagerRepository
{
bool ManagerExists(int managerId);
// possible future extensions: Add / Retrieve / Update / Delete (CRUD)
IManager Add(IManager manager);
IManager Find(int managerId);
void Update(IManager manager);
void Delete(int ManagerId);
}
class Manager : IManager
{
public Id {get; set;}
public string Name {get; set;}
}
class ManagerFileRepository : IManagerRepository,
{
public ManagerFileRepository(string fileName)
{
// TODO implement
}
// TODO: implement.
}
The ManagerFileRepository saves the managers in a file. It hides for the outside world how the file is internally structured. It could be your file format, it could be a CSV-file, or JSON / XML.
I also separated an interface, so if you later decide to save the data somewhere else, for instance in a Dictionary (for unit tests), or in a database, users of your Repository class won't see the difference.
Let's first see if you can use this class.
class MyForm : Form
{
const string managerFileName = ...
private IManagerRepository ManagerRepository {get;}
public MyForm()
{
InitializeComponent();
this.ManagerRepository = new ManagerFileRepository(managerFileName);
}
public bool ManagerExists(int managerId)
{
return this.ManagerRepository.ManagerExists(managerId);
}
Now let's handle your keyPress:
private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox textBox = (TextBox)sender;
... // code about numbers and enter key
int enteredManagerId = Int32.Parse(textBox.Text);
bool managerExists = this.ManagerExists(enteredManagerId);
if (managerExists) { ... }
}
This code seems to do what you want in an easy way. It looks transparent. The managerRepository is testable, reusable, simple to extend or change, because users won't notice this. So the class looks good. Let's implement
Implement ManagerFileRepository
There are several ways to implement reading the file:
(1) Read everything at construction time
and keep the read data in memory. If you add Managers they are not saved until you say so. Advantages: after initial startup it is fast. You can make changes and later decide not to save them anyway, so it is just like editing any other file. Disadvantage: if your program crashes, you have lost your changes.
(2) Read the file every time you need information
Advantage: data is always up-to-date, even if others edited the file while your program runs. If you change the manager collection it is immediately saved, so other can use it.
Which solution you choose depends on the size of the file and the importance of never losing data. If you file contains millions of records, then maybe it wasn't very wise to save the data in a file. Consider SQLite to save it in a small fairly fast database.
class ManagerFileRepository : IManagerRepository, IEnumerable<IManager>
{
private readonly IDictionary<int, IManager> managers;
public ManagerFileRepository(string FileName)
{
this.managers = ReadManagers(fileName);
}
public bool ManagerExists(int managerId)
{
return this.Managers.HasKey(managerId);
}
private static IEnumerable<IManager> ReadManagers(string fileName)
{
// See the short answer above
}
}
Room for improvement
If you will be using your manager repository for more things, consider to let the repository implement ICollection<IManager> and IReadOnlyCollection<IManager>. This is quite simple:
public IEnumerable<IManager> GetEnumerator()
{
return this.managers.Values.GetEnumerator();
}
public void Add(IManager manager)
{
this.managers.Add(manager.Id, manager);
}
// etc.
If you add functions to change the manager collection you'll also need a Save method:
public void Save()
{
using (var writer = File.CreateText(FullFileName))
{
const string namePrefix = "ManagerName: ";
const string idPrefix = "ManagerLoginId: ";
foreach (var manager in managers.Values)
{
string managerLine = namePrefix + manager.Name;
writer.WriteLine(managerLine);
string idLine = idPrefix + manager.Id.ToString();
writer.WriteLine(idLine);
}
}
}
Another method of improvement: your file structure. Consider using a more standard file structure: CSV, JSON, XML. There are numerous NUGET packages (CSVHelper, NewtonSoft.Json) that makes reading and writing Managers much more robust.
Summary
Because you separated the concerns of persisting your managers from your form, you can reuse the manager repository, especially if you need functionality to Add / Retrieve / Update / Delete managers.
Because of the separation it is much easier to unit test your functions. And future changes won't hinder users of the repository, because they won't notice that the data has changed.
If your Manager_Ids.txt is in the following format, you can use File.ReadLine() method to traverse the text and query it.
ManagerName: FirstName_LastName1
ManagerLoginId: 12345
ManagerName: FirstName_LastName2
ManagerLoginId: 23456
...
Here is the demo that traverse the .txt.
string ManagersPath = #"D:\Manager_Ids.txt";
string EnteredEmployeeId;
private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
int counter = 0;
bool exist = false;
string line;
string str = "";
if (e.KeyCode == Keys.Enter)
{
EnteredEmployeeId = textBox_id.Text;
System.IO.StreamReader file =
new System.IO.StreamReader(ManagersPath);
while ((line = file.ReadLine()) != null)
{
str += line + "|";
if (counter % 2 != 0)
{
if (str.Split('|')[1].Split(':')[1].Trim() == EnteredEmployeeId)
{
str = str.Replace("|", "\n");
MessageBox.Show(str);
exist = true;
break;
}
str = "";
}
counter++;
}
if (!exist)
{
MessageBox.Show("No such id");
}
file.Close();
}
}
Besides, I recommend to use "xml", "json" or other formats to serialize the data. About storing the data in "xml", you can refer to the following simple demo.
<?xml version="1.0"?>
<Managers>
<Manager>
<ManagerName>FirstName_LastName1</ManagerName>
<ManagerLoginId>12345</ManagerLoginId>
</Manager>
<Manager>
<ManagerName>FirstName_LastName2</ManagerName>
<ManagerLoginId>23456</ManagerLoginId>
</Manager>
</Managers>
And then use LINQ to XML to query the id.
string ManagersPath = #"D:\Manager_Ids.xml";
string EnteredEmployeeId;
private void textBox_id_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
EnteredEmployeeId = textBox_id.Text;
XElement root = XElement.Load(ManagersPath);
IEnumerable<XElement> manager =
from el in root.Elements("Manager")
where (string)el.Element("ManagerLoginId") == EnteredEmployeeId
select el;
if(manager.Count() == 0)
{
MessageBox.Show("No such id");
}
foreach (XElement el in manager)
MessageBox.Show("ManagerName: " + (string)el.Element("ManagerName") + "\n"
+ "ManagerLoginId: " + (string)el.Element("ManagerLoginId"));
}
}
I'm writing a visual studio extension based on the Concord Samples Hello World project. The goal is to let the user filter out stack frames by setting a list of search strings. If any of the search strings are in a stack frame, it is omitted.
I've got the filter working for a hardcoded list. That needs to be in a non-package-based dll project in order for the debugger to pick it up. And I have a vsix project that references that dll with an OptionPageGrid to accept the list of strings. But I can't for the life of me find a way to connect them.
On the debugger side, my code looks something like this:
DkmStackWalkFrame[] IDkmCallStackFilter.FilterNextFrame(DkmStackContext stackContext, DkmStackWalkFrame input)
{
if (input == null) // null input frame indicates the end of the call stack. This sample does nothing on end-of-stack.
return null;
if (input.InstructionAddress == null) // error case
return new[] { input };
DkmWorkList workList = DkmWorkList.Create(null);
DkmLanguage language = input.Process.EngineSettings.GetLanguage(new DkmCompilerId());
DkmInspectionContext inspection = DkmInspectionContext.Create(stackContext.InspectionSession, input.RuntimeInstance, input.Thread, 1000,
DkmEvaluationFlags.None, DkmFuncEvalFlags.None, 10, language, null);
string frameName = "";
inspection.GetFrameName(workList, input, DkmVariableInfoFlags.None, result => GotFrameName(result, out frameName));
workList.Execute();
CallstackCollapserDataItem dataItem = CallstackCollapserDataItem.GetInstance(stackContext);
bool omitFrame = false;
foreach (string filterString in dataItem.FilterStrings)
{
if (frameName.Contains(filterString))
{
omitFrame = true;
}
}
The CallstackCollapserDataItem is where I theoretically need to retrieve the strings from user settings. But I don't have access to any services/packages in order to e.g. ask for WritableSettingsStore, like in You've Been Haacked's Example. Nor can I get my OptionPageGrid, like in the MSDN Options Example.
The other thing I tried was based on this StackOverflow question. I overrode the LoadSettingsFromStorage function of my OptionPageGrid and attempted to set a static variable on a public class in the dll project. But if that code existed in the LoadSettingsFromStorage function at all, the settings failed to load without even entering the function. Which felt like voodoo to me. Comment out the line that sets the variable, the breakpoint hits normally, the settings load normally. Restore it, and the function isn't even entered.
I'm at a loss. I really just want to pass a string into my Concord extension, and I really don't care how.
Ok, apparently all I needed to do was post the question here for me to figure out the last little pieces. In my CallstackCollapserDataItem : DkmDataItem class, I added the following code:
private CallstackCollapserDataItem()
{
string registryRoot = DkmGlobalSettings.RegistryRoot;
string propertyPath = "vsix\\CallstackCollapserOptionPageGrid";
string fullKey = "HKEY_CURRENT_USER\\" + registryRoot + "\\ApplicationPrivateSettings\\" + propertyPath;
string savedStringSetting = (string)Registry.GetValue(fullKey, "SearchStrings", "");
string semicolonSeparatedStrings = "";
// The setting resembles "1*System String*Foo;Bar"
if (savedStringSetting != null && savedStringSetting.Length > 0 && savedStringSetting.Split('*').Length == 3)
{
semicolonSeparatedStrings = savedStringSetting.Split('*')[2];
}
}
vsix is the assembly in which CallstackCollapserOptionPageGrid is a DialogPage, and SearchStrings is its public property that's saved out of the options menu.
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..
Ok. So this question might be a bit stupid but as I've searched and searched and haven't found a working solution I thought I might ask here.
I've put up a simple PHP page that gets 2 parameters from the url myusername and mypassword. Then gets 3 int values from a database according to the username and password given.
(tested it By typing the url in with the parameters and the PHP script itself works. Even made it to echo the 3 integers on the page to make sure)
Now to the problematic part. I'm using Visual Studio 2013 and making an Universal App for Windows 8.1. And I just can't seem to get the httpClient to get me any data from there. Through browsing the forums I haven't been able to find anything that works. Couldn't have tested all either as most use GetResponse() which doesn't work in VS 2013. As I'm fairly new to the C# coding it could be as simple as to a little mistake in the dozens of tests I've done.
Made a login screen with 2 text fields. And I can build the url in form of "www.something.com/something/somephp?myusername=UserNameGiven&mypassword=PasswordGiven"
If anyone could give a simple solution on how I might be able to get the results from the page that address opens (only shows the 3 integers through echo... can remove those too if those arent required for the C# code to work. String format would probably be ideal if not too much to ask...
Ok made a new GetScores async method for the code you gave SnyderCoder. Throwing that Task on login button would have required coding beyond my knowhow for the moment atleast.
Still Results.Text field remains at the default status and shows no change.
Changed the LoginButton back to async without task.
the state of my code from the c# is atm is
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName, Password;
UserName = UserNameFeedField.Text.ToString();
Password = PasswordFeedField.Text.ToString();
string url = "something.com/something/GetScores.php?myusername=" + UserName + "&mypassword=" + Password;
URL.Text = url;
// GetScores(url);
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOFPage = await client.GetStringAsync(new Uri(url));
Results.Text = contentOFPage;
}
}
incase it matters here is the PHP code portion
<?php
$host="db_host"; // Host name
$username="db_user"; // Mysql username
$password="db_pswd"; // Mysql password
$db_name="db_name"; // Database name
$tbl_name="db_table"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_GET["myusername"];
$mypassword=$_GET["mypassword"];
// To protect MySQL injection (more detail about MySQL injection )
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT field1 as LowB, field2 as LongB, field3 as Bs FROM $tbl_name WHERE UserID='$myusername' and UserPSWD='$mypassword'";
$result=mysql_query($sql);
// this part only shows the variables gotten from the query and echoes those on the page
// was only made to test that the PHP works.
while ($row = mysql_fetch_assoc($result)) {
echo ($row["LowB"] . " " . $row["LongB"] . " " . $row["Bs"]);
}
?>
First a async method always needs to return a task. For the rest:
private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
string UserName = UserNameFeedField.Text.ToString();
string Password = PasswordFeedField.Text.ToString();
string url = "www.something.com/something/some.php?myusername=" + UserName + "&mypassword=" + Password;
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
string contentOfPage = await client.GetStringAsync(new Uri(url));
//Do something with the contentOfPage
}
}
I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx