How save session in xamarin ios, i must use Xamarin.Auth? - c#

How save session in xamarin ios, i must use Xamarin.Auth?
I also need to be able to check if a session already exists when the app starts that way I skip the login page if they are already signed in
public class SettingsManager : ISettingsManager
{
public string PersonalFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
// Write Information to a Local File
public void WriteLocalFile(string FileName, string Data)
{
string filePath = Path.Combine(PersonalFolderPath, FileName);
File.WriteAllText(filePath, Data);
}
}
i found this thread https://forums.xamarin.com/discussion/117141/save-and-grab-session-id-and-other-data

To save session data, you can use Xamarin.Essentials
To save a value for a given key in preferences:
Preferences.Set("my_key", "my_value");
To retrieve a value from preferences or a default if not set:
var myValue = Preferences.Get("my_key", "default_value");

Related

How do I take a screenshot of the current view of my desktop app in Unity using C#?

I have a desktop application that I have made on Unity and I want to take a screenshot of my current view in the application using a C# script attached to the main camera. Please help.
I have browsed other code snippets that I found on this platform and nothing seemed to help.
You can use CaptureScreenshot.
public class ScreenCapture : MonoBehaviour
{
//here you can set the folder you want to use,
//IMPORTANT - use "#" before the string, because this is a verbatim string
//IMPORTANT - the folder must exists
string pathToYourFile = #"C:\Screenshots\";
//this is the name of the file
string fileName = "filename";
//this is the file type
string fileType = ".png";
private int CurrentScreenshot { get => PlayerPrefs.GetInt("ScreenShot"); set => PlayerPrefs.SetInt("ScreenShot", value); }
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
UnityEngine.ScreenCapture.CaptureScreenshot(pathToYourFile + fileName + CurrentScreenshot + fileType);
CurrentScreenshot++;
}
}
}
A few notes.
I used a verbatim string to define your folder
The folder where you store the screenshot must exist (if you want to create it in the script you can follow this answer)
AFTER COMMENT REQUEST - 1: If you do not set the folder the file will be saved in the default directory of the application (that changes based on the system - you can check it from Application.dataPath)
AFTER COMMENT REQUEST - 2: If you use the same path and filename the file will be overriden, so I added a way to let you save multiple screenshots, also in different sessions using PlayerPrefs.
You can use CaptureScreenshot method as answered above but it might be confusing for you if you are new to unity. It stores your captures image in a filepath which you should pass to CaptureScreenshot method as parameter for example
public class ScreenShotManager : MonoBehaviour {
const string FilePath = #"C:\Users\UserName\Desktop\ScreenShots";
public void CaptureScreenShot() {
ScreenCapture.CaptureScreenshot(FilePath);
}
void Update(){
if(Input.GetKeyDown(Keycode.C))
CaptureScreenShot();
}
this code shows that if you press 'c' key on keyboard it would be captured what main camera is rendering at that moment and stored in that file path

The process cannot access the file 'C:\file.txt' because it is being used by another process

I am trying to log each method on my program, I have the application deployed on IIS Server and the user just called me and said the email functionality is not working so I need to basically run the application but log each step into a txt file.
I am declaring the below as a global value:
StreamWriter writer = new StreamWriter("C:\\file.txt");
Then I use it like below in my code:
Method 1
{
if (file1.HasFile)
{
writer.WriteLine("Has File");
}
}
Method 2
private Boolean InsertUpdateData(SqlCommand cmd)
{
writer.WriteLine("Insert Started" + DateTime.Now.ToString());
}
So in my case method one runs fine and it writes Has File but when it goes into the second method I get the file is already open which is correct how can I work around this?
Thanks
Global Value - declared at top
namespace WorkOrderManagement
{
public partial class CreateWorkOrder : System.Web.UI.Page
{
bool successfull;
string path;
string name;
string content;
string datas;
string ext;
bool affectedrows;
string seasonalsupervisor;
private string sLogFormat;
private string sErrorTime;
StreamWriter writer = new StreamWriter("C:\\file.txt");
I really suggest you to discard the idea to have a global variable to represent a stream and then try to use it in different methods. This is simple in a desktop application, but a lot more complex in an ASP.NET application.
There are simple alternatives that could atomically write your log text and leave the file unlocked.
For example you could have a method like this
public static class Log
{
public static string _file = "log.txt";
public static object _locked = new object();
public static void AppendToLog(string text)
{
lock(_locked)
{
string path = Server.MapPath("~/APP_DATA");
File.AppendAllText(Path.Combine(path, _file), text + Environment.NewLine);
}
}
}
Now you can call the log write with
Log.AppendToLog("My message");
I want to underline two important things here. First I don't write in the root drive of the server. This is a bad practice and always a source of problems when you deploy your ASP.NET application in a server where you have not permissions to use anything outside your site root. Thus the ASP.NET system defines a particular folder called APP_DATA under your site root where your application should have read/write permissions.
Second point to notice is the use of the lock keyword. This is necessary in an environment like ASP.NET where two users could reach a point of the code where you need to write to the common log file. As MSDN explains it
The lock keyword ensures that one thread does not enter a critical
section of code while another thread is in the critical section. If
another thread tries to enter a locked code, it will wait, block,
until the object is released.
you can also do this to close the file stream
using (StreamWriter writer = new StreamWriter("C:\\file.txt"))
{
//your code here
}
//this automatically closes the stream, and it is more recommended.
Close the stream after writing the file
Method 1
{
if (file1.HasFile)
{
writer.WriteLine("Has File");
writer.Close();
}
}

Sending multiple responses from a Web Service

I want to create a Web Service that receives images in the form of byte[] and Saves them in the FileSystem.
I want to keep sending the response as I'm saving the files on the FileSystem so that user can show the progress on the mobile device.
Currently I have built a Web Service that can receive only single image.
Here's my code to save single image-
[WebMethod]
public string upload(byte[] postedFile, string folderName, string fileName)
{
try
{
string to_post_in = Path.Combine(HttpContext.Current.Server.MapPath("~/"), folderName);
File.WriteAllBytes(Path.Combine(to_post_in, fileName), postedFile);
SortedList slResult = new SortedList();
slResult.Add("0", "Success");
return JsonConvert.SerializeObject(slResult);
}
catch
{
SortedList slResult = new SortedList();
slResult.Add("1", "Error");
return JsonConvert.SerializeObject(slResult);
}
}
This might not be possible!
As best I know, once you send a response back, code does not continue any further from that line.
You may do the following-
Use same code.
Send one by one pic from the iOS device.
That way you'll be able to tell what file was stored successfully and what not.
Hope it helped!
You can't do this in one single function in Web Services
Why not trying to create the following?
Function upload to save the list of files like this
public string upload(List<byte[]> postedFile, string folderName, List<string> fileNameList)
{
//code to save here
}
Function checkUploaded that takes a list of images name as parameter and checks how many images have already been saved-
public string checkUploaded(string folderName, List<string> fileNameList)
{
//add code to check how many images of the list have already been saved
//and return a percent
}

C# - Creating a configuration file to save data used in the application

my project has been an extremely fun journey so far but I am looking to save the configuration of the Server settings that it will connect (using MySQL Net/Connector).
When the application has loaded up, by default it connects to a server named 'sqlserver05' but I want the user/admin to be able to configure the server settings in a menustrip. So I navigate to the menustrip and you can click 'Configure' where another form pops up asking for server details.
I can do this just by a global string but I have to change the settings everytime the application runs. Can I not create an XML file to read the configuration settings that I just changed?
Sorry if I am not being clear. Many thanks,
Brandon
Yes, you can. An easy way to do this is to use application settings. This is an out-of-the-box implementation of (user and program) settings that is serialized to XML.
Please take a look at the ancient, but still applicable Using Settings in C#.
Effectively what you have to do:
Add a settings file to your project. Go the the Solution Explorer, right click on your project and select Properties. Then select Settings. Follow the steps there.
Create a setting. (In the following code it has the name PropertyName)
Get and set that setting in code.
string value = Properties.Settings.PropertyName; // get
Properties.Settings.Default.PropertyName = value; // set
Save the settings when you have changed anything:
Properties.Settings.Default.Save()
I think in your case it's better to use the Settings class that came with C#, take a look at these links.
1 , 2
First of all, create a simple POCO object to handle the value you wish to set, then read / write this object through a serializer.
You could use a Javascript serializer to generate a JSON file (which is more "trendy" than XML, but if you prefer XML, the mechanism remains the same) :
class DatabaseSettings
{
// Settings file path
private const string DEFAULT_FILENAME = "settings.json";
// Server name or IP
public string Server { get; set; } = "127.0.0.1";
// Port
public int Port { get; set; } = 3306;
// Login
public string Login { get; set; } = "root";
// Password
public string Password { get; set; }
public void Save(string fileName = DEFAULT_FILENAME)
{
File.WriteAllText(
fileName,
(new JavaScriptSerializer()).Serialize(this));
}
public static DatabaseSettings Load(string fileName = DEFAULT_FILENAME)
{
var settings = new DatabaseSettings();
if (File.Exists(fileName))
settings = (new JavaScriptSerializer()).Deserialize<DatabaseSettings>(File.ReadAllText(fileName));
return settings;
}
}
Usage is then the following :
// Read
var settings = DatabaseSettings.Load(/* your path */);
// update
settings.Server = "10.10.10.2";
// save
settings.Save(/* your path */);

Getting Downloads Folder in C#? [duplicate]

This question already has answers here:
How to programmatically derive Windows Downloads folder "%USERPROFILE%/Downloads"?
(11 answers)
Closed 5 years ago.
I have made some code that will search directories and display files in a listbox.
DirectoryInfo dinfo2 = new DirectoryInfo(#"C:\Users\Hunter\Downloads");
FileInfo[] Files2 = dinfo2.GetFiles("*.sto");
foreach (FileInfo file2 in Files2)
{
listBox1.Items.Add(file2.Name);
}
However, where it says Users\Hunter - well, when people get my software, their name is not Hunter. So how can I automatically detect the user's Downloads folder?
I have tried this:
string path = Environment.SpecialFolder.UserProfile + #"\Downloads";
DirectoryInfo dinfo2 = new DirectoryInfo(Environment.SpecialFolder.UserProfile + path);
FileInfo[] Files2 = dinfo2.GetFiles("*.sto");
foreach (FileInfo file2 in Files2)
{
listBox1.Items.Add(file2.Name);
}
I get an error though.
The Downloads folder is a so called "known" folder, together with Documents, Videos, and others.
Do NOT:
combine hardcoded path segments to retrieve known folder paths
assume known folders are children of the user folder
abuse a long deprecated registry key storing outdated paths
Known folders can be redirected anywhere in their property sheets. I've gone into more detail on this several years ago in my CodeProject article.
Do:
use the WinAPI method SHGetKnownFolderPath as it is the intended and only correct method to retrieve those paths.
You can p/invoke it as follows (I've provided only a few GUIDs which cover the new user folders):
public enum KnownFolder
{
Contacts,
Downloads,
Favorites,
Links,
SavedGames,
SavedSearches
}
public static class KnownFolders
{
private static readonly Dictionary<KnownFolder, Guid> _guids = new()
{
[KnownFolder.Contacts] = new("56784854-C6CB-462B-8169-88E350ACB882"),
[KnownFolder.Downloads] = new("374DE290-123F-4565-9164-39C4925E467B"),
[KnownFolder.Favorites] = new("1777F761-68AD-4D8A-87BD-30B759FA33DD"),
[KnownFolder.Links] = new("BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968"),
[KnownFolder.SavedGames] = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"),
[KnownFolder.SavedSearches] = new("7D1D3A04-DEBB-4115-95CF-2F29DA2920DA")
};
public static string GetPath(KnownFolder knownFolder)
{
return SHGetKnownFolderPath(_guids[knownFolder], 0);
}
[DllImport("shell32",
CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = false)]
private static extern string SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags,
nint hToken = 0);
}
Here's an example of retrieving the path of the Downloads folder:
string downloadsPath = KnownFolders.GetPath(KnownFolder.Downloads);
Console.WriteLine($"Downloads folder path: {downloadsPath}");
NuGet Package
If you don't want to p/invoke yourself, have a look at my NuGet package (note that the usage is different, please check its README).
The easiest way is:
Process.Start("shell:Downloads");
If you only need to get the current user's download folder path, you can use this:
I extracted it from #PacMani 's code.
// using Microsoft.Win32;
string GetDownloadFolderPath()
{
return Registry.GetValue(#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{374DE290-123F-4565-9164-39C4925E467B}", String.Empty).ToString();
}
Note:
SHGetKnownFolderPath will return the WRONG value if you changed the download-folder.
The only thing that will ever return you the correct value is reading the shell-folders registry-key 374DE290-123F-4565-9164-39C4925E467B on Windows.
Now you can either use the "!Do not use this registry key", or you can get the wrong value.
You decide which is better for you.
Cross-Platform version:
public static string GetHomePath()
{
// Not in .NET 2.0
// System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
return System.Environment.GetEnvironmentVariable("HOME");
return System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
}
public static string GetDownloadFolderPath()
{
if (System.Environment.OSVersion.Platform == System.PlatformID.Unix)
{
string pathDownload = System.IO.Path.Combine(GetHomePath(), "Downloads");
return pathDownload;
}
return System.Convert.ToString(
Microsoft.Win32.Registry.GetValue(
#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
,"{374DE290-123F-4565-9164-39C4925E467B}"
,String.Empty
)
);
}
string download = Environment.GetEnvironmentVariable("USERPROFILE")+#"\"+"Downloads";
http://msdn.microsoft.com/en-us//library/system.environment.specialfolder.aspx
There are the variables with the path to some special folders.
typically, your software shall have a configurable variable that stores the user's download folder, which can be assigned by the user, and provide a default value when not set. You can store the value in app config file or the registry.
Then in your code read the value from where it's stored.

Categories