Error while reading metadatafile using activityInfo.LoadXmlMetaData() - xamarin.forms

Implementing weakfulIntentService in xamarin.android .
Problem while reading metadatafile.
eturn null while reading metadatafile xml file in BroadCastReceiver.
** XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);**
BroadcastReceiver
namespace Squarelabs.Droid
{
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private static string WAKEFUL_META_DATA = "squrelabs.inspection";
public override void OnReceive(Context context, Intent intent)
{
WakefulIntentService.IAlarmListener alarmListener =
GetListener(context);
if (alarmListener != null)
{
if (intent.Action == null)
{
alarmListener.SendWakefulWork(context);
}
else
{
WakefulIntentService.ScheduleAlarms(alarmListener, context, true);
}
}
}
private WakefulIntentService.IAlarmListener GetListener(Context context)
{
PackageManager packageManager = context.PackageManager;
ComponentName componentName = new ComponentName(context, Class);
try
{
ActivityInfo activityInfo = packageManager.GetReceiverInfo(componentName, PackageInfoFlags.MetaData);
XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);
while (reader!=null)
{
if (reader.IsStartElement())
{
if (reader.Name == "WakefulIntentService")
{
string className = reader.Value;
Class cls = Java.Lang.Class.ForName(className);
return ((WakefulIntentService.IAlarmListener)cls.NewInstance());
}
}
reader.MoveToNextAttribute();
}
} catch (NameNotFoundException e) {
throw new RuntimeException("Cannot find own info???", e);
} catch (XmlPullParserException e) {
throw new RuntimeException("Malformed metadata resource XML", e);
} catch (IOException e) {
//throw new RuntimeException("Could not read resource XML", e);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Listener class not found", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Listener is not public or lacks public constructor", e);
} catch (InstantiationException e) {
throw new RuntimeException("Could not create instance of listener", e);
}
return (null);
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="2" android:versionName="1.9.5" package="squrelabs.inspection">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="Squarelabs" android:icon="#drawable/icon">
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<meta-data android:name="squrelabs.inspection" android:resource="#xml/wakeful" />
</receiver>
</application>
xml in resource
<WakefulIntentService
listener="squrelabs.inspection.Droid.AppListener"
/>
Kindly help me to solve this issue.

Problem while reading metadatafile. eturn null while reading metadatafile xml file in BroadCastReceiver.
You can add attribute MetaData on your AlarmReceiver, and change android:resource="#xml/wakeful" code to load resource directly from string. For example:
[MetaData("mTag", Value = "#string/WakefulIntentService")]
string resource is like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MetaDataDemo</string>
<string name="WakefulIntentService">squrelabs.inspection.Droid.AppListener </string>
</resources>
Then your final purpose is to get the ((WakefulIntentService.IAlarmListener)cls.NewInstance()), you can replace the code:
ActivityInfo activityInfo = packageManager.GetReceiverInfo(componentName, PackageInfoFlags.MetaData);
XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);
while (reader!=null)
{
if (reader.IsStartElement())
{
if (reader.Name == "WakefulIntentService")
{
string className = reader.Value;
Class cls = Java.Lang.Class.ForName(className);
return ((WakefulIntentService.IAlarmListener)cls.NewInstance());
}
}
reader.MoveToNextAttribute();
}
With:
ComponentName cn = new ComponentName(context, Class);
ActivityInfo info = context.PackageManager.GetReceiverInfo(cn, PackageInfoFlags.MetaData);
System.String mTag = info.MetaData.GetString("mTag");
Class cls = Java.Lang.Class.ForName(mTag);
return cls.NewInstance();
Update:
try to replace this code with var listener = ReflectionHelper.CreateInstance<WakefulIntentService.IAlarmListener>("Demo.AppListener", Assembly.GetExecutingAssembly().FullName); and then change the string WakefulIntentService like this:
<string name="WakefulIntentService">yournamespace.AppListener</string>
The ReflectionHelper is like this:
public static class ReflectionHelper
{
public static T CreateInstance<T>(string fullName, string assemblyName)
{
string path = fullName + "," + assemblyName;
Type o = Type.GetType(path);
object obj = Activator.CreateInstance(o, true);
return (T)obj;
}
public static T CreateInstance<T>(string assemblyName, string nameSpace, string className)
{
try
{
string fullName = nameSpace + "." + className;
object ect = Assembly.Load(assemblyName).CreateInstance(fullName);
return (T)ect;
}
catch
{
return default(T);
}
}
}

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

Spring MVC returns 405 for api call made from my android client

I have an android app which is making api requests to my server running Spring MVC. The RestController works fine when I make a request from the browser but it responds with 404 when I am making requests from android. Not sure why
Here is code snippet from Android app making requests
public class AsyncFetch extends AsyncTask<Pair<String, String>, String, String> {
public ProgressDialog pdLoading;
private HttpURLConnection conn;
private String urlStr;
private String requestMethod = "GET";
public AsyncFetch(String endpoint, Context ctx)
{
pdLoading = new ProgressDialog(ctx);
Properties reader = PropertiesReader.getInstance().getProperties(ctx, "app.properties");
String host = reader.getProperty("host", "10.0.2.2");
String port = reader.getProperty("port", "8080");
String protocol = reader.getProperty("protocol", "http");
String context = reader.getProperty("context", "");
this.urlStr = protocol+"://"+host+":"+port+context+endpoint;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(Pair<String, String>... params) {
URL url;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made`enter code here`
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
Spring MVC Controller
#RestController
public class ApiController {
#RequestMapping(value = "homefeed", method=RequestMethod.GET)
public String homefeed(#RequestParam(value="userId", required = false) Integer id, #RequestParam(value="search", required = false) String search, #RequestParam(value="page", required = false, defaultValue = "0") Integer page) { ... }
}
localhost:8080/api/homefeed -- works
127.0.0.1:8080/api/homefeed -- works
My Public IP:8080/api/homefeed -- does not works
10.0.2.2:8080/api/homefeed -- android emulator to localhost -- does not work
10.0.2.2:8080/Some resource other than the api endpoint -- works
Any help is highly appreciable, have wasted quiet some time in debugging.

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

Upload file to Secured FTP in ASP.NET

I want to upload files to FTPS and SFTP. My code is currently using FtpWebRequest object to upload to FTP. What changes or class should I use to upload to FTP, FTPS and SFTP servers?
SFTP is not a built-in protocol for .NET, you'll have to use a third-party library, like SharpSSH; however, FTP and FTPS are. There are a number of third-party libraries both commercial and OpenSource (SSH Factory for .NET , Rebex SFTP for .NET/.NET CF, SharpSSH - A Secure Shell (SSH) library for .NET, Compare SFTP (SSH File Transfer Protocol) components for .NET (C#, VB.NET) - SecureBlackbox®) and you'll need to do some research to determine which one will best suit your needs.
Here's a sample console app I wrote that does FTP and FTPS using the .NET Framework's FtpWebRequest:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace FtpSslTest
{
class Program
{
static void Main(string[] args)
{
string server = null;
do
{
Console.Write("Enter the server to connect to: ");
server = Console.ReadLine();
} while (IsServerValid(server) == false);
UriBuilder ftpUrl = new UriBuilder("ftp", server);
bool useSsl = GetYesNo("Use SSL?");
bool allowInvalidCertificate = false;
if (useSsl)
{
allowInvalidCertificate = GetYesNo("Allow invalid SSL certificate?");
}
bool useActiveFtp = GetYesNo("Use Active FTP?");
string path = null;
do
{
Console.Write("Enter the path: ");
path = Console.ReadLine();
} while (IsValidPath(path) == false);
ftpUrl.Path = path;
Console.Write("Enter the user name: ");
string userName = Console.ReadLine();
string password = GetPasswordFromUser();
Console.WriteLine();
Console.WriteLine();
List<string> directoryContents = null;
try
{
directoryContents = DisplayDirectoryContents(ftpUrl.ToString(), userName, password, useSsl, allowInvalidCertificate, useActiveFtp, false);
}
catch (WebException ex)
{
Console.WriteLine("The request failed with status {0}. {1}", ex.Status, ex.Message);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
if (directoryContents != null && directoryContents.Count == 1)
{
bool saveFile = GetYesNo(string.Format("Download the file {0} from {1}? ", directoryContents[0], server));
if (saveFile)
{
string savePath = null;
do
{
Console.Write("Enter a local path to save the file: ");
savePath = Console.ReadLine();
} while (!IsValidPath(savePath));
try
{
DownloadFileFromServer(ftpUrl.ToString(), userName, password, useSsl, allowInvalidCertificate, useActiveFtp, savePath);
}
catch (WebException ex)
{
Console.WriteLine("The request failed with status {0}. {1}", ex.Status, ex.Message);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
}
}
private static bool GetYesNo(string message)
{
Console.Write("{0} (Y/N) ", message);
string input = null;
do
{
input = new string(Console.ReadKey(true).KeyChar, 1);
} while (!input.Equals("Y", StringComparison.CurrentCultureIgnoreCase) && !input.Equals("N", StringComparison.CurrentCultureIgnoreCase));
Console.WriteLine(input);
return input.Equals("Y", StringComparison.CurrentCultureIgnoreCase);
}
private static bool IsValidPath(string path)
{
bool validPath = false;
validPath = path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0;
if (validPath == false)
{
Console.WriteLine("You must enter a valid path.");
}
return validPath;
}
private static bool IsServerValid(string server)
{
bool serverValid = false;
if (!string.IsNullOrEmpty(server))
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(server);
serverValid = (addresses != null && addresses.Length > 0);
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine("You must provide a valid host name or IP address.");
}
return serverValid;
}
private static string GetPasswordFromUser()
{
Console.Write("Enter the password: ");
StringBuilder password = new StringBuilder();
char readChar = '\x00';
while (readChar != '\r')
{
readChar = Console.ReadKey(true).KeyChar;
if (readChar == '\b')
{
if (password.Length > 0)
{
password.Length--;
Console.Write("\b \b");
}
}
else if (readChar != '\r')
{
Console.Write('*');
password.Append(readChar);
}
}
return password.ToString();
}
public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool allowCertificate = true;
if (sslPolicyErrors != SslPolicyErrors.None)
{
Console.WriteLine("Accepting the certificate with errors:");
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
{
Console.WriteLine("\tThe certificate subject {0} does not match.", certificate.Subject);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)
{
Console.WriteLine("\tThe certificate chain has the following errors:");
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Console.WriteLine("\t\t{0}", chainStatus.StatusInformation);
if (chainStatus.Status == X509ChainStatusFlags.Revoked)
{
allowCertificate = false;
}
}
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable)
{
Console.WriteLine("No certificate available.");
allowCertificate = false;
}
Console.WriteLine();
}
return allowCertificate;
}
private static FtpWebRequest CreateFtpWebRequest(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(userName, password);
if (useSsl)
{
request.EnableSsl = true;
if (allowInvalidCertificate)
{
ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
}
else
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
}
request.UsePassive = !useActiveFtp;
return request;
}
private static List<string> DisplayDirectoryContents(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, bool detailed)
{
List<string> directoryContents = new List<string>();
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
if (detailed)
{
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
}
else
{
request.Method = WebRequestMethods.Ftp.ListDirectory;
}
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseStreamReader = new StreamReader(responseStream))
{
while (!responseStreamReader.EndOfStream)
{
string directoryEntry = responseStreamReader.ReadLine();
Console.WriteLine(directoryEntry);
directoryContents.Add(directoryEntry);
}
}
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes received in {1} seconds.", bytesReceived, stopwatch.ElapsedMilliseconds / 1000.0);
return directoryContents;
}
private static List<string> ListDirectoryContents(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, bool detailed)
{
List<string> directoryContents = new List<string>();
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
if (detailed)
{
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
}
else
{
request.Method = WebRequestMethods.Ftp.ListDirectory;
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseStreamReader = new StreamReader(responseStream))
{
while (!responseStreamReader.EndOfStream)
{
string directoryEntry = responseStreamReader.ReadLine();
directoryContents.Add(directoryEntry);
}
}
}
return directoryContents;
}
private static void DownloadFileFromServer(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, string savePath)
{
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
using (FileStream saveFileStream = File.OpenWrite(savePath))
{
// Note that this method call requires .NET 4.0 or higher. If using an earlier version it will need to be replaced.
responseStream.CopyTo(saveFileStream);
}
bytesReceived = response.ContentLength;
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes received in {1} seconds.", bytesReceived, stopwatch.ElapsedMilliseconds / 1000.0);
}
private static void UploadFileToServer(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, string filePath)
{
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
request.Method = WebRequestMethods.Ftp.UploadFile;
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
long bytesSent = 0;
using (Stream requestStream = request.GetRequestStream())
using (FileStream uploadFileStream = File.OpenRead(filePath))
{
// Note that this method call requires .NET 4.0 or higher. If using an earlier version it will need to be replaced.
uploadFileStream.CopyTo(requestStream);
bytesSent = uploadFileStream.Position;
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
bytesReceived = response.ContentLength;
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes sent in {1} seconds.", bytesSent, stopwatch.ElapsedMilliseconds / 1000.0);
}
}
}
You can also get detailed tracing for debugging purposes by using the following config file with the sample application:
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
<source name="System.Net.Sockets" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="System.Net.trace.log" traceOutputOptions="DateTime"/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose"/>
<!--<add name="System.Net.Sockets" value="Verbose"/>-->
</switches>
<trace autoflush="true" />
</system.diagnostics>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
I use this library to download and upload files over sftp. Should be samples of how to use the library if you download the source. http://sshnet.codeplex.com

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources