Method called infinite times in Web Service - c#

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;
}
}

Related

System.StackOverflowException in C# discord bot

I am programming a discord bot in Discord .NET 0.9 and I get a stack overflow error when I try to run it. The problem a occurs when I make a instance of my Program.cs in my Functions.cs
My Program.cs:
using System;
using System.Linq;
using Discord;
using Discord.Commands;
using System.IO;
using fatobg;
namespace fatobg
{
class Program
{
CommandManager cm = new CommandManager();
public static Program _instance = new Program();
static void Main(string[] args)
{
new Program().Start();
}
public DiscordClient _client;
public void Start()
{
Console.Title = "Matchmaking Discord BOT";
_client = new DiscordClient(x =>
{
x.AppName = "Gerry";
x.AppUrl = "www.google.com";
x.LogLevel = LogSeverity.Info;
x.LogHandler = Log;
});
_client.UsingCommands(x =>
{
x.PrefixChar = '?';
x.AllowMentionPrefix = true;
x.HelpMode = HelpMode.Public;
});
var token = "Changed";
cm.Commands(_client);
onJoin();
_client.ExecuteAndWait(async () =>
{
await _client.Connect(token, TokenType.Bot);
setGame(_client, "?help");
});
}
public void setGame(DiscordClient _client, string game)
{
_client.SetGame(game);
}
public void onJoin()
{
_client.UserJoined += async (s, e) =>
{
await e.Server.GetChannel(318558393759694849).SendMessage($":loudspeaker: | Everyone welcome {e.User.Mention} to the server!");
};
}
public void Log(Object sender, LogMessageEventArgs e)
{
Console.WriteLine($"[{e.Severity}] [{e.Source}] {e.Message}");
}
}
}
My CommandManager.cs:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading.Tasks;
using Discord;
using System.Net.Http;
using Discord.Commands;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.IO;
using System.Threading;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace fatobg
{
class CommandManager
{
public static CommandManager _instance = new CommandManager();
Functions function = new Functions();
public void Commands(DiscordClient _client)
{
var cService = _client.GetService<CommandService>();
cService.CreateCommand("say")
.Description("returns commands")
.Parameter("message", ParameterType.Unparsed)
.Do(async (e) =>
{
Message[] messageToDelete;
int deleteNumber = 1;
messageToDelete = await e.Channel.DownloadMessages(deleteNumber);
await e.Channel.DeleteMessages(messageToDelete);
var toReturn = $":envelope: | {e.GetArg("message")}";
await e.Channel.SendMessage(toReturn);
Console.WriteLine(toReturn);
});
cService.CreateCommand("updatedb")
.Description("updates database")
.Do(async (e) =>
{
Message[] messageToDelete; //deletes command
int deleteNumber = 1;
messageToDelete = await e.Channel.DownloadMessages(deleteNumber);
await e.Channel.DeleteMessages(messageToDelete);
try
{
if (e.User.ServerPermissions.Administrator)
{
foreach (User user in e.Server.Users)
{
if(!user.IsBot)
function.UpdateDB(user);
}
var toReturn = $":white_check_mark: | Done updateing the database. {e.User.Mention}";
await e.Channel.SendMessage(toReturn);
Console.WriteLine(toReturn);
}
else
{
var toReturn = $":exclamation: | Get out of here {e.User.Mention} you have no power over me!";
await e.Channel.SendMessage(toReturn);
Console.WriteLine(toReturn);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
}
});
cService.CreateCommand("duo")
.Description("returns commands")
.Do(async (e) =>
{
Message[] messageToDelete;
int deleteNumber = 1;
messageToDelete = await e.Channel.DownloadMessages(deleteNumber);
await e.Channel.DeleteMessages(messageToDelete);
});
cService.CreateCommand("yamikage")
.Description("Animated gingy")
.Do(async (e) =>
{
Message[] messageToDelete;
int deleteNumber = 1;
messageToDelete = await e.Channel.DownloadMessages(deleteNumber);
await e.Channel.DeleteMessages(messageToDelete);
await e.Channel.SendFile("Gifs/gingy.gif");
Console.WriteLine("Send epic gingy meme");
});
}
}
}
My Functions.cs:
using Discord;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace fatobg
{
class Functions
{
Program main = new Program();
public void UpdateDB(User user)
{
if (File.Exists(#"D:\Databases\DiscordUsers\" + user.Id + ".duser"))
{
System.IO.File.Delete(#"D:\Databases\DiscordUsers\" + user.Id + ".duser");
string[] Data = { user.Name, Roles(user) };
System.IO.File.WriteAllLines(#"D:\Databases\DiscordUsers\" + user.Id + ".duser", Data);
}
else
{
string[] Data = { user.Name, Roles(user) };
System.IO.File.WriteAllLines(#"D:\Databases\DiscordUsers\" + user.Id + ".duser", Data);
}
}
public string Roles(User user)
{
string toreturn = string.Empty;
foreach (Role role in user.Roles)
{
if (role.Name!="Admin"||role.Name!="Mod"||role.Name!="#everyone")
{
toreturn += role.Name + "|";
}
}
return toreturn;
}
public string GetUsername(string uid)
{
if (File.Exists(#"D:\Databases\DiscordUsers\" + uid + ".duser"))
{
string[] Data = File.ReadAllLines(#"D:\Databases\DiscordUsers\" + uid + ".duser");
return Data[0];
}
else
{
return null;
}
}
public void AddToQueue(User user)
{
List<User> NA = new List<User>();
List<User> EU = new List<User>();
List<User> OC = new List<User>();
List<User> AS = new List<User>();
List<User> SA = new List<User>();
Server server = main._client.FindServers("Find A Team On Battlegrounds (Bot Testing)").FirstOrDefault();
User usr = server.FindUsers(user.Name).FirstOrDefault();
if (File.Exists(#"D:\Databases\Duo.queue"))
{
string[] UData = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach(String uid in UData)
{
User tempuser = user.Server.FindUsers(GetUsername(uid)).FirstOrDefault();
List<Role> roles = tempuser.Roles.ToList();
foreach(Role role in roles)
{
if (role.Name == "[NA]")
NA.Add(tempuser);
else if (role.Name == "[EU]")
EU.Add(tempuser);
else if (role.Name == "[OC]")
OC.Add(tempuser);
else if (role.Name == "[AS]")
AS.Add(tempuser);
else if (role.Name == "[SA]")
SA.Add(tempuser);
}
}
List<Role> uroles = usr.Roles.ToList();
foreach (Role role in uroles)
{
if (role.Name == "[NA]")
NA.Add(usr);
else if (role.Name == "[EU]")
EU.Add(usr);
else if (role.Name == "[OC]")
OC.Add(usr);
else if (role.Name == "[AS]")
AS.Add(usr);
else if (role.Name == "[SA]")
SA.Add(usr);
}
File.WriteAllLines(#"D:\Databases\Duo.queue", UData);
File.AppendAllText(#"D:\Databases\Duo.queue", usr.Id.ToString() + Environment.NewLine);
if (NA.Count == 2)
{
server.GetChannel(319281246746312714).SendMessage($":exclamation: | A new team has been found for NA servers. {NA[0].Mention} and {NA[1].Mention} prepare to fight.");
string[] Data = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach (String id in Data)
{
if(id!=NA[0].Id.ToString()&&id!=NA[1].Id.ToString())
File.AppendAllText(#"D:\Databases\Duo.queue", id + Environment.NewLine);
}
NA.Clear();
}
else if (EU.Count == 2){
server.GetChannel(319281246746312714).SendMessage($":exclamation: | A new team has been found for EU servers. {EU[0].Mention} and {EU[1].Mention} prepare to fight.");
string[] Data = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach (String id in Data)
{
if (id!=EU[0].Id.ToString()&&id!=EU[1].Id.ToString())
File.AppendAllText(#"D:\Databases\Duo.queue", id + Environment.NewLine);
}
EU.Clear();
}
else if (OC.Count == 2)
{
server.GetChannel(319281246746312714).SendMessage($":exclamation: | A new team has been found for OC servers. {OC[0].Mention} and {OC[1].Mention} prepare to fight.");
string[] Data = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach (String id in Data)
{
if (id!=OC[0].Id.ToString()&&id!=OC[1].Id.ToString())
File.AppendAllText(#"D:\Databases\Duo.queue", id + Environment.NewLine);
}
OC.Clear();
}
else if (AS.Count == 2)
{
server.GetChannel(319281246746312714).SendMessage($":exclamation: | A new team has been found for AS servers. {AS[0].Mention} and {AS[1].Mention} prepare to fight.");
string[] Data = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach (String id in Data)
{
if (id != AS[0].Id.ToString() && id != AS[1].Id.ToString())
File.AppendAllText(#"D:\Databases\Duo.queue", id + Environment.NewLine);
}
AS.Clear();
}
else if (SA.Count == 2)
{
server.GetChannel(319281246746312714).SendMessage($":exclamation: | A new team has been found for SA servers. {SA[0].Mention} and {SA[1].Mention} prepare to fight.");
string[] Data = System.IO.File.ReadAllLines(#"D:\Databases\Duo.queue");
System.IO.File.Delete(#"D:\Databases\Duo.queue");
foreach (String id in Data)
{
if (id != SA[0].Id.ToString()&&id!=SA[1].Id.ToString())
File.AppendAllText(#"D:\Databases\Duo.queue", id + Environment.NewLine);
}
SA.Clear();
}
}
else
{
File.AppendAllText(#"D:\Databases\Duo.queue", usr.Id.ToString() + Environment.NewLine);
}
}
}
}
This is what happens:
Instantiate Program;
Program instantiates CommandManager;
CommandManager instantiates Functions;
Functions instantiates Program;
Return to 1.
What you should do:
Pass along an instance of Program to CommandManager and Functions. In that way, you have no circular reference any more.
For example your Functions class should start with this:
class Functions
{
Program main;
public Functions(Program p)
{
this.main = p;
}
And your CommandManager:
class CommandManager
{
Program main;
Functions function;
public CommandManager(Program p)
{
this.main = p;
this.function = new Function(p);
}

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);

Save and load data to xml

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
}

Correct way to store encryption key for SqlCipher database

I have a Xamarin application and have managed to download my data from my server to my device. I have also got it set up so that it can take a SqlCipher Encryption key to encrypt the data.
My question is where is the correct location to store my key that I use to encrypt this data? Is it to you KeyStore / KeyChain? Which mono classes should I be looking to use?
Due to the popularity of this question I am going to post my implementation of this:
PCL interface
public interface IAuth
{
void CreateStore();
IEnumerable<string> FindAccountsForService(string serviceId);
void Save(string pin,string serviceId);
void Delete(string serviceId);
}
Android
public class IAuthImplementation : IAuth
{
Context context;
KeyStore ks;
KeyStore.PasswordProtection prot;
static readonly object fileLock = new object();
const string FileName = "MyProg.Accounts";
static readonly char[] Password = null;
public void CreateStore()
{
this.context = Android.App.Application.Context;
ks = KeyStore.GetInstance(KeyStore.DefaultType);
prot = new KeyStore.PasswordProtection(Password);
try
{
lock (fileLock)
{
using (var s = context.OpenFileInput(FileName))
{
ks.Load(s, Password);
}
}
}
catch (Java.IO.FileNotFoundException)
{
//ks.Load (null, Password);
LoadEmptyKeyStore(Password);
}
}
public IEnumerable<string> FindAccountsForService(string serviceId)
{
var r = new List<string>();
var postfix = "-" + serviceId;
var aliases = ks.Aliases();
while (aliases.HasMoreElements)
{
var alias = aliases.NextElement().ToString();
if (alias.EndsWith(postfix))
{
var e = ks.GetEntry(alias, prot) as KeyStore.SecretKeyEntry;
if (e != null)
{
var bytes = e.SecretKey.GetEncoded();
var password = System.Text.Encoding.UTF8.GetString(bytes);
r.Add(password);
}
}
}
return r;
}
public void Delete(string serviceId)
{
var alias = MakeAlias(serviceId);
ks.DeleteEntry(alias);
Save();
}
public void Save(string pin, string serviceId)
{
var alias = MakeAlias(serviceId);
var secretKey = new SecretAccount(pin);
var entry = new KeyStore.SecretKeyEntry(secretKey);
ks.SetEntry(alias, entry, prot);
Save();
}
void Save()
{
lock (fileLock)
{
using (var s = context.OpenFileOutput(FileName, FileCreationMode.Private))
{
ks.Store(s, Password);
}
}
}
static string MakeAlias(string serviceId)
{
return "-" + serviceId;
}
class SecretAccount : Java.Lang.Object, ISecretKey
{
byte[] bytes;
public SecretAccount(string password)
{
bytes = System.Text.Encoding.UTF8.GetBytes(password);
}
public byte[] GetEncoded()
{
return bytes;
}
public string Algorithm
{
get
{
return "RAW";
}
}
public string Format
{
get
{
return "RAW";
}
}
}
static IntPtr id_load_Ljava_io_InputStream_arrayC;
void LoadEmptyKeyStore(char[] password)
{
if (id_load_Ljava_io_InputStream_arrayC == IntPtr.Zero)
{
id_load_Ljava_io_InputStream_arrayC = JNIEnv.GetMethodID(ks.Class.Handle, "load", "(Ljava/io/InputStream;[C)V");
}
IntPtr intPtr = IntPtr.Zero;
IntPtr intPtr2 = JNIEnv.NewArray(password);
JNIEnv.CallVoidMethod(ks.Handle, id_load_Ljava_io_InputStream_arrayC, new JValue[]
{
new JValue (intPtr),
new JValue (intPtr2)
});
JNIEnv.DeleteLocalRef(intPtr);
if (password != null)
{
JNIEnv.CopyArray(intPtr2, password);
JNIEnv.DeleteLocalRef(intPtr2);
}
}
Call Create Store in the main activity of Android app first. - This could possibly be improved and remove CreateStrore() from the interface by checking if ks == null in Save and Delete and calling the method if true
iOS
public class IAuthImplementation : IAuth
{
public IEnumerable<string> FindAccountsForService(string serviceId)
{
var query = new SecRecord(SecKind.GenericPassword);
query.Service = serviceId;
SecStatusCode result;
var records = SecKeyChain.QueryAsRecord(query, 1000, out result);
return records != null ?
records.Select(GetAccountFromRecord).ToList() :
new List<string>();
}
public void Save(string pin, string serviceId)
{
var statusCode = SecStatusCode.Success;
var serializedAccount = pin;
var data = NSData.FromString(serializedAccount, NSStringEncoding.UTF8);
//
// Remove any existing record
//
var existing = FindAccount(serviceId);
if (existing != null)
{
var query = new SecRecord(SecKind.GenericPassword);
query.Service = serviceId;
statusCode = SecKeyChain.Remove(query);
if (statusCode != SecStatusCode.Success)
{
throw new Exception("Could not save account to KeyChain: " + statusCode);
}
}
//
// Add this record
//
var record = new SecRecord(SecKind.GenericPassword);
record.Service = serviceId;
record.Generic = data;
record.Accessible = SecAccessible.WhenUnlocked;
statusCode = SecKeyChain.Add(record);
if (statusCode != SecStatusCode.Success)
{
throw new Exception("Could not save account to KeyChain: " + statusCode);
}
}
public void Delete(string serviceId)
{
var query = new SecRecord(SecKind.GenericPassword);
query.Service = serviceId;
var statusCode = SecKeyChain.Remove(query);
if (statusCode != SecStatusCode.Success)
{
throw new Exception("Could not delete account from KeyChain: " + statusCode);
}
}
string GetAccountFromRecord(SecRecord r)
{
return NSString.FromData(r.Generic, NSStringEncoding.UTF8);
}
string FindAccount(string serviceId)
{
var query = new SecRecord(SecKind.GenericPassword);
query.Service = serviceId;
SecStatusCode result;
var record = SecKeyChain.QueryAsRecord(query, out result);
return record != null ? GetAccountFromRecord(record) : null;
}
public void CreateStore()
{
throw new NotImplementedException();
}
}
WP
public class IAuthImplementation : IAuth
{
public IEnumerable<string> FindAccountsForService(string serviceId)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] auths = store.GetFileNames("MyProg");
foreach (string path in auths)
{
using (var stream = new BinaryReader(new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, store)))
{
int length = stream.ReadInt32();
byte[] data = stream.ReadBytes(length);
byte[] unprot = ProtectedData.Unprotect(data, null);
yield return Encoding.UTF8.GetString(unprot, 0, unprot.Length);
}
}
}
}
public void Save(string pin, string serviceId)
{
byte[] data = Encoding.UTF8.GetBytes(pin);
byte[] prot = ProtectedData.Protect(data, null);
var path = GetAccountPath(serviceId);
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, store))
{
stream.WriteAsync(BitConverter.GetBytes(prot.Length), 0, sizeof(int)).Wait();
stream.WriteAsync(prot, 0, prot.Length).Wait();
}
}
public void Delete(string serviceId)
{
var path = GetAccountPath(serviceId);
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
store.DeleteFile(path);
}
}
private string GetAccountPath(string serviceId)
{
return String.Format("{0}", serviceId);
}
public void CreateStore()
{
throw new NotImplementedException();
}
}
This is an adaptation of the Xamarin.Auth library (Found Here) but removes the dependency from the Xamarin.Auth library to provide cross platform use through the interface in the PCL. For this reason I have simplified it to only save one string. This is probably not the best implementation but it works in my case. Feel free to expand upon this
There is a nuget package called KeyChain.NET that encapsulated this logic for iOs, Android and Windows Phone.
It's open source and you have find sample at its github repository
More info at this blog post

How can I extend the OOTB Content Editor Web Part in Sharepoint 2010?

I need a webpart that has a plaintext field for a title, an image for a thumbnail and a HTML content-editable block, so I thought the best way to do this would be to try and extend the existing Content Editor Web Part. Unfortunately, the CEWP is marked as sealed so I can't subclass it. I've reflected and tried to recreate the functionality in my own custom webpart (see the end of the question for code), but the content of my custom version of the CEWP is not persisted.
Does anyone know how I can:
safely subclass the ContentEditableWebPart, or
include a rich text block (including the RTE Ribbon) in a custom web part, or
host multiple web parts in one "wrapper" web part?
Thanks in advance!
code follows below (stuff that was stopping it compiling that was copied from reflector has been commented out/altered/removed)
using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace Public.Webparts
{
[ToolboxItemAttribute(false)]
[XmlRoot(Namespace="Webparts/ProductItem")]
public class ProductItemWebPart :System.Web.UI.WebControls.WebParts.WebPart
{
// Fields
private string _content;
private bool _contentHasToken;
private string _contentLink;
private string _partContent;
private string _partStorage;
private HtmlGenericControl editableRegion = new HtmlGenericControl();
private HtmlGenericControl emptyPanel = new HtmlGenericControl();
private const string EmptyPanelHtmlV4 = "<A href=\"#\" title=\"{0}\" style=\"padding:8px 0px\" class=\"ms-toolbar ms-selectorlink\" >{0}</A>";
internal const string InputContentClientId = "content";
// Methods
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public ProductItemWebPart()
{
//base.PreRender += new EventHandler(this.OnPreRender);
if (this.Title.Length == 0)
{
this.Title = "Product Item Webpart";
}
if (this.Description.Length == 0)
{
this.Description = "This web part contains a title, content and image for a product item.";
}
}
private string GetContent()
{
if (this._partContent != null)
{
return SPHttpUtility.NoEncode(ReplaceTokens(this._partContent));
}
return "";
}
protected internal string ReplaceTokens(string input)
{
string str = string.Empty;
if (this.WebPartManager != null)
{
return SPWebPartManager.ReplaceTokens(HttpContext.Current, SPContext.Current.Web, this, input);
}
if (input != null)
{
str = input;
}
return str;
}
private string getEmptyPanelHtml()
{
return "<A href=\"#\" title=\"Click to enter content.\" style=\"padding:8px 0px\" class=\"ms-toolbar ms-selectorlink\" >Click to enter content.</A>";
}
//private void HttpAsyncCallback(object state)
//{
// ULS.SendTraceTag(0x38393969, ULSCat.msoulscat_WSS_WebParts, ULSTraceLevel.Medium, "ASYNC: Http Callback: UniqueID={0}", new object[] { this.UniqueID.ToString() });
// if ((HttpStatusCode.OK != base.GetHttpWebResponse(this._contentLink, out this._partContent)) && (this._content == null))
// {
// this._partContent = "<p class=\"UserGeneric\">" + SPHttpUtility.HtmlEncode(WebPartPageResource.GetString("CannotRetrieveContent", new object[] { WebPartPageResource.GetString("ContentLinkLiteral") })) + "</p>";
// }
//}
private bool inEditMode()
{
SPWebPartManager currentWebPartManager = (SPWebPartManager) WebPartManager.GetCurrentWebPartManager(this.Page);
return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
}
//[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//public override string LoadResource(string id)
//{
// string str = WebPartPageResource.GetString(id);
// if (str != null)
// {
// return str;
// }
// return id;
//}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.ShowContentEditable())
{
SPRibbon current = SPRibbon.GetCurrent(this.Page);
if (current != null)
{
current.MakeTabAvailable("Ribbon.EditingTools.CPEditTab");
current.MakeTabAvailable("Ribbon.Image.Image");
current.MakeTabAvailable("Ribbon.EditingTools.CPInsert");
current.MakeTabAvailable("Ribbon.Link.Link");
current.MakeTabAvailable("Ribbon.Table.Layout");
current.MakeTabAvailable("Ribbon.Table.Design");
//if (!(this.Page is WikiEditPage))
//{
// current.TrimRTEWikiControls();
//}
}
}
}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
protected override void OnLoad(EventArgs e)
{
this.Controls.Add(this.editableRegion);
this.Controls.Add(this.emptyPanel);
this.editableRegion.Visible = false;
this.emptyPanel.Visible = false;
base.OnLoad(e);
string str = this.Page.Request.Form[this.ClientID + "content"];
if ((str != null) && (this._content != str))
{
this._content = str;
try
{
SPWebPartManager currentWebPartManager = (SPWebPartManager) WebPartManager.GetCurrentWebPartManager(this.Page);
Guid storageKey = currentWebPartManager.GetStorageKey(this);
currentWebPartManager.SaveChanges(storageKey);
}
catch (Exception exception)
{
Label child = new Label();
child.Text = exception.Message;
this.Controls.Add(child);
}
}
if (this.ShowContentEditable())
{
string str2;
//if (this.ContentHasToken)
//{
// str2 = ReplaceTokens(this._content);
//}
//else
//{
// str2 = this._content;
//}
str2 = this._content;
this.Page.ClientScript.RegisterHiddenField(this.ClientID + "content", str2);
this.editableRegion.Visible = true;
this.emptyPanel.Visible = true;
this.emptyPanel.TagName = "DIV";
this.emptyPanel.Style.Add(HtmlTextWriterStyle.Cursor, "hand");
this.emptyPanel.Controls.Add(new LiteralControl(this.getEmptyPanelHtml()));
this.emptyPanel.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
base.Attributes["RteRedirect"] = this.editableRegion.ClientID;
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.UI.Rte.js", false);
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.js", false);
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Runtime.js", false);
this.editableRegion.TagName = "DIV";
this.editableRegion.InnerHtml = str2;
this.editableRegion.Attributes["class"] = "ms-rtestate-write ms-rtestate-field";
this.editableRegion.Attributes["contentEditable"] = "true";
this.editableRegion.Attributes["InputFieldId"] = this.ClientID + "content";
this.editableRegion.Attributes["EmptyPanelId"] = this.emptyPanel.ClientID;
this.editableRegion.Attributes["ContentEditor"] = "True";
this.editableRegion.Attributes["AllowScripts"] = "True";
this.editableRegion.Attributes["AllowWebParts"] = "False";
string script = "RTE.RichTextEditor.transferContentsToInputField('" + SPHttpUtility.EcmaScriptStringLiteralEncode(this.editableRegion.ClientID) + "');";
this.Page.ClientScript.RegisterOnSubmitStatement(base.GetType(), "transfer" + this.editableRegion.ClientID, script);
if (string.IsNullOrEmpty(this._content))
{
this.emptyPanel.Style["display"] = "";
this.editableRegion.Style["display"] = "none";
}
else
{
this.emptyPanel.Style["display"] = "none";
this.editableRegion.Style["display"] = "";
}
}
}
//private void OnPreRender(object sender, EventArgs e)
//{
// Uri fullURLPath = base.GetFullURLPath(this._contentLink);
// if ((fullURLPath != null) && !base.TryToGetFileFromDatabase(fullURLPath, out this._partContent))
// {
// ULS.SendTraceTag(0x38393968, ULSCat.msoulscat_WSS_WebParts, ULSTraceLevel.Medium, "ASYNC: Begin Fetch: UniqueID={0}", new object[] { this.UniqueID.ToString() });
// base.RegisterWorkItemCallback(new WaitCallback(this.HttpAsyncCallback), null);
// }
//}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//protected override void RenderWebPart(HtmlTextWriter writer)
protected override void Render(HtmlTextWriter writer)
{
//if (this.ShowContentEditable() && base.WebPartManager.IsAllowedToScript(this))
if (this.ShowContentEditable())
{
base.Render(writer);
}
else
{
writer.Write(this.GetContent());
}
}
//[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//protected internal override bool RequiresWebPartClientScript()
//{
// return true;
//}
//public bool ShouldSerializeContent()
//{
// if (!base.SerializeAll)
// {
// return (this.WebPartDefault._content != this._content);
// }
// return true;
//}
//public bool ShouldSerializeContentHasToken()
//{
// return ((this.WebPartDefault._contentHasToken != this._contentHasToken) && !base.SerializeAll);
//}
//public bool ShouldSerializeContentLink()
//{
// if (!base.SerializeAll)
// {
// return (this.WebPartDefault._contentLink != this._contentLink);
// }
// return true;
//}
public bool ShouldSerializePartStorage()
{
//if (!base.SerializeAll)
//{
//return (this.WebPartDefault._partStorage != this._partStorage);
//}
return true;
}
internal bool ShowContentEditable()
{
return (((SPContext.Current.Web.UIVersion > 3) && (this._partContent == null)) && this.inEditMode());
}
//[XmlElement("ContentHasToken", IsNullable=false), Browsable(false), WebPartStorage(Storage.Shared)]
//public bool ContentHasToken
//{
// get
// {
// return this._contentHasToken;
// }
// set
// {
// this._contentHasToken = value;
// }
//}
//private string EncodedInvalidContentError
//{
// get
// {
// string str2;
// string str = "<a id=\"" + this.ID + "HelpLink\" href=\"javascript:HelpWindowUrl('" + SPHttpUtility.NoEncode("sts/html/dpvwpabt.htm") + "');\">" + SPHttpUtility.HtmlEncode(WebPartPageResource.GetString("InvalidContentErrorHelpLink")) + "</a>";
// if ((this.Context != null) && Utility.BrowserIsIE(this.Context.Request.Browser))
// {
// str2 = "InvalidContentError";
// }
// else
// {
// str2 = "InvalidContentErrorDL";
// }
// return ("<p><div class=\"UserGeneric\">" + string.Format(CultureInfo.InvariantCulture, SPHttpUtility.HtmlEncodeAllowSimpleTextFormatting(WebPartPageResource.GetString(str2)), new object[] { str }) + "</div></p>");
// }
//}
[Resources("PartStorageLiteral", "Advanced", "PartStorage"), WebPartStorage(Storage.Personal), XmlElement("PartStorage", IsNullable=false)]
public string PartStorage
{
get
{
//return Utility.GetMemberString(this._partStorage);
return this._partStorage ?? String.Empty;
}
set
{
//Utility.SetMemberString(ref this._partStorage, value);
if (value != null && value.Length > 0)
{
this._partStorage = value;
}
else
{
this._partStorage = null;
}
}
}
//internal ContentEditorWebPart WebPartDefault
//{
// get
// {
// return (ContentEditorWebPart) base.WebPartDefault;
// }
//}
}
}
Think this may solve your problem - you were on the right track when you got Reflector out :)
http://zootfroot.blogspot.com/2010/09/develop-custom-editable-visual-web-part.html
You can use ControlAdapter, as described in this article: http://blog.mastykarz.nl/inconvenient-content-editor-web-part/
Why not create a "Visual Web Part" and use a rich text editor (like Telerik or others)? I think trying to reverse engineer the code for CEWP is probably overkill and probably against SharePoint's license.

Categories