Save and load data to xml - c#

so i am making a login application with a register form but i need some help. i want to save all the account info in xml which i kinda can do, i've created a form where i can save and load 1 user to xml use savefiledialog, here's the code:
The xml Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
namespace Login_Form
{
public class xmlSave
{
public static void SaveData(object IClass, string filename)
{
StreamWriter writer = null;
try
{
XmlSerializer xml = new XmlSerializer((IClass.GetType()));
writer = new StreamWriter(filename);
xml.Serialize(writer, IClass);
}
finally
{
if (writer != null)
writer.Close();
writer = null;
}
}
}
public class xmlLoad<T>
{
public static Type type;
public xmlLoad()
{
type = typeof(T);
}
public T LoadData(string filename)
{
T result;
XmlSerializer xml = new XmlSerializer(type);
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
result = (T)xml.Deserialize(fs);
fs.Close();
return result;
}
}
}
and here is the save and load code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Xml.Serialization;
namespace Login_Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
saveFileDialog.InitialDirectory = #"C:\Users\Felix\Documents\visual studio 2013\Projects\Login Form\Login Form\bin\Debug";
saveFileDialog.Filter = "xml Files (*.xml)|*.xml";
saveFileDialog.FilterIndex = 2;
saveFileDialog.RestoreDirectory = true;
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
User user = new User();
user.FName = textBox1.Text;
user.LName = textBox2.Text;
user.Username = textBox3.Text;
user.Email = textBox4.Text;
user.Password = textBox5.Text;
xmlSave.SaveData(user, saveFileDialog.FileName);
}
}
private void Form1_Load(object sender, EventArgs e)
{
User user = new User();
xmlLoad<User> loadUser = new xmlLoad<User>();
user = loadUser.LoadData("test.xml");
textBox1.Text = user.FName;
textBox2.Text = user.LName;
textBox3.Text = user.Username;
textBox4.Text = user.Email;
textBox5.Text = user.Password;
}
}
public class User
{
private string fName;
private string lName;
private string username;
private string email;
private string password;
public string FName
{
get { return fName; }
set { fName = value; }
}
public string LName
{
get { return lName; }
set { lName = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
}
}
this allows me to save the info from 5 textboxes into a xml file but only 1 user, i want to know how to save multiple users and also how to use this as a login system(no servers, only local for now), and how to load the right info in the main application, for example if im logged in to user 1 i want that users info displayd and the same with other users. im sorry if i explaind myself badly.

your answer. I have saved user info in xml and loaded it on form load.
while saving give file name as test.xml
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
namespace Login_Form
{
public partial class Form1 : Form
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
saveFileDialog.Filter = "xml Files (*.xml)|*.xml";
saveFileDialog.FilterIndex = 2;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (File.Exists(saveFileDialog.FileName))
File.Delete(saveFileDialog.FileName);
User user = new User();
user.FName = textBox1.Text;
user.LName = textBox2.Text;
user.Username = textBox3.Text;
user.Email = textBox4.Text;
user.Password = textBox5.Text;
XmlWriter xmlWriter = XmlWriter.Create(saveFileDialog.FileName);
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("UserInfo");
xmlWriter.WriteStartElement("FName");
xmlWriter.WriteString(user.FName);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("LName");
xmlWriter.WriteString(user.LName);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Username");
xmlWriter.WriteString(user.Username);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Email");
xmlWriter.WriteString(user.Email);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Password");
xmlWriter.WriteString(user.Password);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
User user = new User();
string filePath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
filePath += "\\test.xml";
if (File.Exists(filePath))
{
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
XmlNode VersionNode = null;
VersionNode = doc.SelectSingleNode("UserInfo");
if (null == VersionNode) return;
user.FName = VersionNode.SelectSingleNode("FName").InnerText;
user.LName = VersionNode.SelectSingleNode("LName").InnerText;
user.Username = VersionNode.SelectSingleNode("Username").InnerText;
user.Email = VersionNode.SelectSingleNode("Email").InnerText;
user.Password = VersionNode.SelectSingleNode("Password").InnerText;
textBox1.Text = user.FName;
textBox2.Text = user.LName;
textBox3.Text = user.Username;
textBox4.Text = user.Email;
textBox5.Text = user.Password;
}
}
}
public class User
{
private string fName;
private string lName;
private string username;
private string email;
private string password;
public string FName
{
get { return fName; }
set { fName = value; }
}
public string LName
{
get { return lName; }
set { lName = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Email
{
get { return email; }
set { email = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
}
}

The best way i think if you use a database if you don't need complex Db, I think SQLite is perfect for you.
My suggest , if you want store the data in xml you must save the whole UserList or you can save the XML files to the users temp folder Path.GetTempPath() but it wokrks only if the users login with different Windows user.

As mentioned above, the best way is using SQL or at least store all users in one xml file. But if you actually need to store all users information in separated files you can create some directory for users info files only and every time you are logging in or getting some user information you should iterate throw all files and deserialize each one.
something like that:
string[] files = Directory.GetFiles('your user storage directory');
foreach (string file in files) {
user = loadUser.loadData(file);
//your logic goes here
}

Related

The main menu doesn't load with correct permissions assigned (C#)

I'm developing a windows form application with C# and the issue is as follows.
The requirement is to change properties in my main menu items (Ex: Make certain menu strip items invisible, etc.), according to the role of logged-in users (Ex: The main menu of a student shouldn't contain the "Lecturer" menu strip item)
The code for my login form is as follows.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using DBL;
namespace Interfaces
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
public string UserID;
public string Password;
public string Role;
private void btnLogin_Click(object sender, EventArgs e)
{
String SQL = "SELECT * FROM LoginInfo";
string connectionString;
SqlConnection con;
connectionString = #"Data Source=DESKTOP-U9V5QGE\CL_HNDCSE_86_16;Initial Catalog=UNIMAP_WAD;Integrated Security=True";
con = new SqlConnection(connectionString);
con.Open();
SqlCommand comm = new SqlCommand(SQL, con);
SqlDataReader sqlDReader = comm.ExecuteReader();
UserID = txtUserID.Text;
Password = txtPassword.Text;
while (sqlDReader.Read())
{
Role = sqlDReader["Role"].ToString();
}
if (UserID == sqlDReader["UserID"].ToString() && Password == sqlDReader["Password"].ToString())
{
con.Close();
if (Role == "SuperAdmin")
{
CurrentCredentials.LoggedInUID = UserID;
CurrentCredentials.LoggedInRole = Role;
frmMainMenu objmainmenu = new frmMainMenu();
objmainmenu.Show();
}
else if (Role == "Admin")
{
CurrentCredentials.LoggedInUID = UserID;
CurrentCredentials.LoggedInRole = Role;
frmMainMenu objmainmenu = new frmMainMenu();
objmainmenu.Show();
objmainmenu.credentialsToolStripMenuItem.Visible = false;
}
else if (Role == "StudentCoordinator")
{
CurrentCredentials.LoggedInUID = UserID;
CurrentCredentials.LoggedInRole = Role;
frmMainMenu objmainmenu = new frmMainMenu();
objmainmenu.Show();
objmainmenu.credentialsToolStripMenuItem.Visible = false;
objmainmenu.lecturerToolStripMenuItem.Visible = false;
}
else if (Role == "Lecturer")
{
CurrentCredentials.LoggedInUID = UserID;
CurrentCredentials.LoggedInRole = Role;
frmMainMenu objmainmenu = new frmMainMenu();
objmainmenu.Show();
objmainmenu.credentialsToolStripMenuItem.Visible = false;
objmainmenu.studentToolStripMenuItem.Visible = false;
}
else if (Role == "Student")
{
CurrentCredentials.LoggedInUID = UserID;
CurrentCredentials.LoggedInRole = Role;
frmMainMenu objmainmenu = new frmMainMenu();
objmainmenu.Show();
objmainmenu.credentialsToolStripMenuItem.Visible = false;
objmainmenu.lecturerToolStripMenuItem.Visible = false;
}
else
{
MessageBox.Show("Invalid credentials", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Invalid credentials", "ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Also, using a static class "CurrentCredentials" to store the current users' User ID and Role.
Resides in the Class Library "DBL".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using DBL;
namespace DBL
{
public static class CurrentCredentials
{
private static string _LoggedInUID;
private static string _LoggedInRole;
public static String LoggedInUID
{
get
{
return _LoggedInUID;
}
set
{
_LoggedInUID = value;
}
}
public static String LoggedInRole
{
get
{
return _LoggedInRole;
}
set
{
_LoggedInRole = value;
}
}
}
}
You may see that I've changed the properties from the Login code itself. I've made changes to the Main menu > menu strip items (private > public), so I can access those from anywhere in the program.
Additionally, just now received this error on the following part of the login screen.
//error
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
//received from the line
if (UserID == sqlDReader["UserID"].ToString() && Password == sqlDReader["Password"].ToString())
Your expertise provided in this matter is really appreciated.
Thanks in advance.
You probably meant the part
if (UserID == sqlDReader["UserID"].ToString() && Password == sqlDReader["Password"].ToString())...
to be in the while loop? If it is after the while loop you cannot access the sqldreader as there is no more data left to read.

Index out of range with less than 6 rows of data

Small brief of what i need and what i currently have
I connect to a database and get my data from it and i get ( Name , LongNumber) and basically i have an event (action) that fires when the event occurs (this action gives me a LongNumber aswell).
I need to compare the LongNumbers between the one i got from the event (action) and the one from my database, and if they are similar i take the name and use it.
for example Hello, Alex ( alex is taken from the database)
Issue
I get Index out of range, and using my logic all texts will change what i'm trying to achieve is to change the text to the name of the person that got the Long number the same as the longNumber from the event
Code: Gettings Data from the database
using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;
public class MySqlTestScript : MonoBehaviour
{
private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
return _instnace;
}
string row = "";
public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";
public List<Data> userData = new List<Data>();
Data data;
void Awake()
{
_instnace = this;
}
// Use this for initialization
public void Start()
{
GetDataFromDatabase();
}
public string GetDataFromDatabase()
{
string myConnectionString = "Server="+host+";Database="+database+";Uid="+usrename+ ";Pwd="+password+";";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Users";
MySqlDataReader Reader;
try
{
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
{
//rfid_tags.Add (Reader.GetString("UserName"));
//rfid_tags.Add(Reader.GetString("RFID_Tag"));
data = new Data(Reader.GetString("UserName"), Reader.GetString("RFID_Tag"));
userData.Add(data);
// ws.DomainUrl = reader.GetString("DomainUrl");
// rfid_tags.Add(Reader.GetValue(i).ToString() + ",");
// row += Reader.GetValue(i).ToString() + ", ";
}
Debug.Log(row);
}
}
catch (Exception x)
{
Debug.Log(x.Message);
return x.Message;
}
connection.Close();
return row;
}
}
public class Data {
public string username { get; set; }
public string rfid { get; set; }
public Data(string _name, string _rfid)
{
username = _name;
rfid = _rfid;
}
public void SetUserName(string _userName) { username = _userName; }
public void SetRFID(string _rfid) { rfid = _rfid; }
}
Code for Comparing the values from the event(action) and showing the text
void OnTagsReported(ImpinjReader sender, TagReport report)
{
Debug.Log("OnTagsReported");
// This event handler is called asynchronously
// when tag reports are available.
// Loop through each tag in the report
// and print the data.
foreach (Tag tag in report)
{
Debug.Log(tag.Epc);
// Debug.Log(MySqlTestScript.sharedInstance().rfid_tags[0]);
Debug.Log("STEP ONE");
for (int i = 0; i < MySqlTestScript.sharedInstance().userData.Count; i++)
{
Debug.Log("STEP TWO");
if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().userData[i].rfid)
{
Debug.Log("STEP THREE");
// TODO References the Name
Loom.QueueOnMainThread(() => {
namesTxt[i].text = MySqlTestScript.sharedInstance().userData[i].username;
});
}
}
As you can see in the Event script it's so unflexible and it gives index out of range if my database has less than 6 rows. I need to make it more friendly and generic
Any help would be appreciated and i hope my question is clear Thank you :)!
This should make more sense:
Database:
using UnityEngine;
using System.Collections;
using MySql.Data.MySqlClient;
using System;
using System.Linq;
using System.Collections.Generic;
public class MySqlTestScript : MonoBehaviour
{
private static MySqlTestScript _instnace;
public static MySqlTestScript sharedInstance()
{
return _instnace;
}
string row = "";
public string host = "*****";
public string database = "*******";
public string usrename= "*******";
public string password = "******";
public List<AppUser> users = new List<AppUser>();
void Awake()
{
_instnace = this;
}
// Use this for initialization
public void Start()
{
GetDataFromDatabase();
}
public string GetDataFromDatabase()
{
string myConnectionString = "Server=" + host + ";Database=" + database + ";Uid=" + usrename + ";Pwd=" + password + ";";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM users";
MySqlDataReader Reader;
try
{
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
users.Add(new AppUser() {
username = Reader.GetString("UserName").Trim(),
rfid = Reader.GetString("longNumbers ").Trim()
});
}
}
catch (Exception x)
{
Debug.Log(x.Message);
return x.Message;
}
connection.Close();
return row;
}
}
Data object:
public Class AppUser
{
public string rfid { get; set; }
public string username { get; set; }
}
Event/data comparison:
void OnTagsReported(ImpinjReader sender, TagReport report)
{
Debug.Log("OnTagsReported");
// This event handler is called asynchronously
// when tag reports are available.
// Loop through each tag in the report
// and print the data.
foreach (Tag tag in report)
{
Debug.Log(tag.Epc);
List<AppUser> appUsers = MySqlTestScript.sharedInstance().users;
int numUsers = appUsers.Count;
Debug.Log(numUsers);
for (int i = 0; i < numUsers; i++)
{
if (tag.Epc.ToString().Trim() == appUsers[i].rfid)
{
// TODO References the Name
Loom.QueueOnMainThread(() => {
if (i < namesTxt.Count) namesTxt[i].Text = appUsers[i].username; //assumes textnames is a "List" of textboxes and is already populated with instances of text1, text2 text3 etc. The if is just to guard against there being more rows in the DB than textboxes
});
}
}
}
}
One way to get around this is to wrap each of your cases in another if statement to check if the database has that many rows
if (MySqlTestScript.sharedInstance().longNumbers.Length > 1) {
if (tag.Epc.ToString().Trim() == MySqlTestScript.sharedInstance().longNumbers[0].ToString()) {
if(MySqlTestScript.sharedInstance().userNames[0] != null)
txt1.text = "Hello "+ MySqlTestScript.sharedInstance().userNames[0];
}
}
}
else {
txt1.text = "";
}
This will avoid your index out of range exception. In each wrapping case you will need to increment the comparison to be 1, 2, 3, etc.
It is not the prettiest solution but will avoid the exception. Another option would be to wrap in a try-catch block. Again not the prettiest but would accomplish the task.

C# How to build list of objects and change their properties

I just scrapped the entire previous question for a more basic situation:
I want to make a simple load + display program such as when I load a text file, the file name, the file path and the contents are displayed in 3 different textboxes.
Here is the code:
using System.IO;
using System.Windows.Forms;
namespace ListBuilderTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public class TextFile
{
public string TextFilePath {get;set;}
public string TextFileTitle {get;set;}
public string TextFileString {get;set;}
}
List<TextFile> TextFileList = new List<TextFile>();
string pathToFile = "";
private void button_Click(object sender, RoutedEventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text files|*.txt", ValidateNames = true, Multiselect = true })
{
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in ofd.FileNames)
{
TextFile CurrentFile = new TextFile();
CurrentFile.TextFilePath = ofd.SafeFileName;
CurrentFile.TextFileTitle = ofd.FileName;
if (File.Exists(pathToFile)) {
using (StreamReader sr = new StreamReader(pathToFile))
{
CurrentFile.TextFileString = sr.ReadLine();
}
}
TextFileList.Add(CurrentFile);
/*
textBox.Text = CurrentFile.TextFileTitle+"\r\n";
textBox_Copy.Text = CurrentFile.TextFilePath+"\r\n";
textBox_Copy1.Text = CurrentFile.TextFileString+"\r\n";*/
/* I would like to simplify this preceeding code into displaying it as a reference to the list rather than the current object.*/
}
}
}
}
}
}
The OFD works and I can select multiple files however, it will only obtain the properties of the first file.
My files are Apple.txt, Banana.txt and Cherry.txt and they each respectively contain "Red", "Yellow" and "Black".
you will add something to list like this:
PDFList.Add(new PDFfile { PDFFileName = "name", PDFText = "text" });
your foreach cycle should be like this:
foreach (PDFfile file in PDFList){
if(Regex.IsMatch(file.PDFText, "statement") == true)
{
file.PDFresult1 = "true";
}
else
{
file.PDFresult1 = "false";
}
}
the rest should be fine

How to write a method to open an image in C# that will use the default image viewer on a mobile device...?

Apologizes for the long title!
I'm fairly new to C# (probably only 2-3 months of concrete knowledge) that I learned in College...
I've been experimenting with Xamarin Forms XAML and I was wondering how I would write a method in the code-behind that opens the tapped image to be opened in the default image viewer for Android or iOS.
I say Android or iOS because I'm doing cross-platform Xamarin Forms PCL.
Thanks :) Happy Holidays and a Great New Year :D!
Try following code :
PCL interface :
namespace MyApp.Common.Interfaces
{
public interface IDataViewer
{
void showPhoto(string AttachmentName, byte[] AttachmentBytes);
string ImageExists(string Filename, byte[] ImageData);
}
}
Platform Specific (Droid) :
using Android.Content;
using Android.Webkit;
using Android.Widget;
using System;
using System.IO;
using MyApp.Common.Interfaces;
using Xamarin.Forms;
[assembly: Dependency(typeof(DataViewer))]
namespace MyApp.Droid.Common
{
public class DataViewer : IDataViewer
{
public void showPhoto(string AttachmentName, byte[] AttachmentBytes)
{
string dirPath = Xamarin.Forms.Forms.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures).Path;
var FileName = AttachmentName;
Java.IO.File file = new Java.IO.File(dirPath, FileName);
if (!file.Exists())
{
var filename = Path.Combine(dirPath, AttachmentName);
File.WriteAllBytes(filename, AttachmentBytes);
}
Device.BeginInvokeOnMainThread(() =>
{
//var oDir = Xamarin.Forms.Forms.Context.FilesDir.AbsolutePath;
Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
Intent intent = new Intent(Intent.ActionView);
String mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl((string)uri).ToLower());
intent.SetDataAndType(uri, mimeType);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
try
{
Xamarin.Forms.Forms.Context.StartActivity(intent);
}
catch (System.Exception ex)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View this file", ToastLength.Short).Show();
}
});
}
public string ImageExists(string FileName, byte[] Imagedata)
{
string dirPath = Xamarin.Forms.Forms.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures).Path;
Java.IO.File file = new Java.IO.File(dirPath, FileName);
if (!file.Exists())
{
var filename = Path.Combine(dirPath, FileName);
File.WriteAllBytes(filename, Imagedata);
return filename;
}
else
{
var filename = Path.Combine(dirPath, FileName);
return filename;
}
}
}
}
Platform Specific (iOS) :
using Foundation;
using QuickLook;
using System;
using System.IO;
using UIKit;
using MyApp.Common.Interfaces;
[assembly: Dependency(typeof(DataViewer))]
namespace MyApp.iOS.Common
{
public class DataViewer : IDataViewer
{
public void showPhoto(string AttachmentName, byte[] AttachmentBytes)
{
var FileName = AttachmentName;
string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(dirPath, FileName);
FileInfo fi = new FileInfo(filename);
if (!NSFileManager.DefaultManager.FileExists(filename))
{
Stream stream = new MemoryStream(AttachmentBytes);
NSData imgData = NSData.FromStream(stream);
NSError err;
imgData.Save(filename, false, out err);
}
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
QLPreviewController previewController = new QLPreviewController();
previewController.DataSource = new PDFPreviewControllerDataSource(fi.FullName, fi.Name);
UINavigationController controller = FindNavigationController();
if (controller != null)
controller.PresentViewController(previewController, true, null);
});
}
private UINavigationController FindNavigationController()
{
foreach (var window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController.NavigationController != null)
return window.RootViewController.NavigationController;
else
{
UINavigationController val = CheckSubs(window.RootViewController.ChildViewControllers);
if (val != null)
return val;
}
}
return null;
}
private UINavigationController CheckSubs(UIViewController[] controllers)
{
foreach (var controller in controllers)
{
if (controller.NavigationController != null)
return controller.NavigationController;
else
{
UINavigationController val = CheckSubs(controller.ChildViewControllers);
if (val != null)
return val;
}
}
return null;
}
public string ImageExists(string Filename, byte[] Bytedata)
{
string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(dirPath, Filename);
FileInfo fi = new FileInfo(filename);
if (!NSFileManager.DefaultManager.FileExists(filename))
{
Stream stream = new MemoryStream(Bytedata);
NSData imgData = NSData.FromStream(stream);
NSError err;
imgData.Save(filename, false, out err);
return filename;
}
else
{
return filename;
}
}
}
public class PDFItem : QLPreviewItem
{
string title;
string uri;
public PDFItem(string title, string uri)
{
this.title = title;
this.uri = uri;
}
public override string ItemTitle
{
get { return title; }
}
public override NSUrl ItemUrl
{
get { return NSUrl.FromFilename(uri); }
}
}
public class PDFPreviewControllerDataSource : QLPreviewControllerDataSource
{
string url = "";
string filename = "";
public PDFPreviewControllerDataSource(string url, string filename)
{
this.url = url;
this.filename = filename;
}
public override IQLPreviewItem GetPreviewItem(QLPreviewController controller, nint index)
{
return (IQLPreviewItem)new PDFItem(filename, url);
}
public override nint PreviewItemCount(QLPreviewController controller)
{
return 1;
}
}
}
Usage :
IDataViewer dataViewer = DependencyService.Get<IDataViewer>();
dataViewer.showPhoto(FileName, AttachmentBytes);

Method called infinite times in Web Service

For my class on Web Services I am trying to create an EXTREMELY simple login system. I ham having a problem where createAccounts() keeps getting infinite times whenever checkCredentials is called. Any idea why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.IO;
public class Service : IService
{
static String path = #"PATH REMOVED";
List<Account> accounts = new List<Account>();
StreamWriter sw = null;
private void createAccounts()
{
String data = File.ReadAllText(path);
string[] data2 = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string[] temp;
for (int i = 0; i < data2.Length; i++)
{
temp = data2[i].Split(',');
if(!usernameExists(temp[0]) && temp[0] != "")
{
accounts.Add(new Account(temp[0],temp[1]));
}
}
}
public bool CreateAccount(String username, String password)
{
createAccounts();
sw = File.AppendText(path);
if (!usernameExists(username))
{
sw.WriteLine(username + "," + password + "\n");
sw.Close();
sw = null;
return true;
}
else
{
sw.Close();
sw = null;
return false;
}
}
public bool usernameExists(String username)
{
createAccounts();
if(accounts.Exists(a => a.username == username))
return true;
else
return false;
}
public bool CheckCredentials(String username, String password)
{
createAccounts();
if (usernameExists(username))
{
if(accounts.Find(a => a.username == username).username == username && accounts.Find(a => a.username == username).password == password)
return true;
else
return false;
}
else
return false;
}
}
class Account
{
public String username;
public String password;
public Account(String u, String p)
{
username = u;
password = p;
}
}
You have a loop between createAccounts and usernameExists. As long as data2.Length is non-zero you'll loop endlessly.
you save data in a file,you should not write it in infinite times.when you request frequently,it will write the file in muliththreading,a thread will lock the file.
i suggest you use try...catch...write the file to find problem:
public bool CreateAccount(String username, String password)
{
createAccounts();
try
{
sw = File.AppendText(path);
}
catch (Exception ex)
{
throw ex;
}
if (!usernameExists(username))
{
sw.WriteLine(username + "," + password + "\n");
sw.Close();
sw = null;
return true;
}
else
{
sw.Close();
sw = null;
return false;
}
}

Categories