I am new to Xamarin. I want to confirm if the database is created and if the data is being inserted to the SQLite database. Thank you for the help
Questions:
1. How to check if database exist/created or not?
2. How to check if the user are inserted successfully or it failed?
3. Where do these file go in my phone?
Below is my code:
App.xaml.cs
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TBSMobileApplication.Views;
using TBSMobileApplication.Data;
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace TBSMobileApplication
{
public partial class App : Application
{
static TokenDatabaseController tokenDatabase;
static UserDatabaseController userDatabase;
public App ()
{
InitializeComponent();
MainPage = new LoginPage();
}
protected override void OnStart ()
{
// Handle when your app starts
}
protected override void OnSleep ()
{
// Handle when your app sleeps
}
protected override void OnResume ()
{
// Handle when your app resumes
}
public static UserDatabaseController UserDatabase
{
get
{
if(userDatabase == null)
{
userDatabase = new UserDatabaseController();
}
return userDatabase;
}
}
public static TokenDatabaseController TokenDatabase
{
get
{
if (tokenDatabase == null)
{
tokenDatabase = new TokenDatabaseController();
}
return tokenDatabase;
}
}
}
}
LoginPage.xaml.cs (Basically this is my Code behind in my login page)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBSMobileApplication.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TBSMobileApplication.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class LoginPage : ContentPage
{
public LoginPage ()
{
InitializeComponent ();
}
void LoginProcedure(object sender, EventArgs e)
{
User user = new User(entUser.Text, entPassword.Text);
if (user.CheckInformation())
{
//DisplayAlert("Login Message", "Login Success", "Ok");
try
{
App.UserDatabase.SaveUser(user);
DisplayAlert("Database Message", "User Saved", "Ok");
}
catch(Exception ex)
{
DisplayAlert("Message", ex.Message, "Ok");
}
}
else
{
DisplayAlert("Login Message", "Login Failed", "Ok");
}
}
}
}
ISQLite.cs (This is where you get the connection to the database)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Data
{
public interface ISQLite
{
SQLiteConnection GetConnection();
}
}
User.cs (This is where the parameters of the User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TBSMobileApplication.Models
{
public class User
{
[PrimaryKey, AutoIncrement]
public int ContactID { get; set; }
[Unique]
public string UserID { get; set; }
public string UserPassword { get; set; }
public User() { }
public User(string Username, string Password)
{
this.UserID = Username;
this.UserPassword = Password;
}
public bool CheckInformation()
{
if(!this.UserID.Equals("") || !this.UserPassword.Equals(""))
{
return true;
}
else
{
return false;
}
}
}
}
SQLite_Android.cs (This is where I created the database)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using TBSMobileApplication.Data;
using TBSMobileApplication.Droid.Data;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace TBSMobileApplication.Droid.Data
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.SQLiteConnection GetConnection()
{
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, DBFileName);
var conn = new SQLite.SQLiteConnection(path);
return conn;
}
}
}
UserDatabaseController.cs (This is where I control User table like adding, deleting or getting data from User table)
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using TBSMobileApplication.Models;
using Xamarin.Forms;
namespace TBSMobileApplication.Data
{
public class UserDatabaseController
{
static object locker = new object();
SQLiteConnection database;
public UserDatabaseController()
{
database = DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<User>();
}
public User GetUser()
{
lock (locker)
{
if(database.Table<User>().Count() == 0)
{
return null;
}
else
{
return database.Table<User>().First();
}
}
}
public int SaveUser(User user)
{
lock (locker)
{
if (user.ContactID != 0)
{
database.Update(user);
return user.ContactID;
}
else
{
return database.Insert(user);
}
}
}
public int DeleteUser(int contactid)
{
lock (locker)
{
return database.Delete<User>(contactid);
}
}
}
}
Starting with part 3 of your question - where is the database file? - it's here:
var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
That equates to:
/data/data/[your.package.name]/files/backend.db3
For the first part of your question, to check whether the database has been created, just check whether the file exists:
public static bool DBExists()
{
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(DocumentPath, "backend.db3");
return File.Exists(path);
}
Accessing the file there is somewhere between difficult and impossible without a rooted device. You're not supposed to be able to access files there - only your app can access them. It's a safety measure.
Your application doesn't have any trouble accessing the database file, though, so you can implement a method in your application to copy it somewhere more accessible (e.g. the Downloads directory).
Put this in your Android project:
public static void CopyDBToDownloadsDirectory()
{
var path = System.IO.Path.Combine(
Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath,
"backend.db3");
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var safePath = Path.Combine(DocumentPath, "backend.db3");
File.Copy(safePath, path, true);
}
Call it to create a copy of the database you can readily access on the phone's built-in file browser.
So, for part 2 of the question, whether a transaction succeeded or failed, you can either run queries against your database in code to check, or open a copy of the database file in a GUI and browse the data.
Related
I have a project in c# winforms, with a file called: PublicSettings.cs (this file is within a folder called: Class) where I have a variable.
Now, I want to use that variable from another file within the same project.
PublicSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LVSetup.Class
{
class PublicSettings
{
private string _ConnStr = "Connection";
public string ConnStr
{
get
{
return this._ConnStr;
}
set
{
this._ConnStr = value;
}
}
}
}
I want to use the variable ConnStr in the file: frmLogin.cs
frmLogin.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LVSetup.Class;
namespace LVSetup
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
string a = PublicSettings.ConnStr;
}
}
}
But there is no ConnStr within PublicSettings, just (Equals and ReferenceEquals)
What could be wrong here?
You need to make this field static in order to access it without creating a class instance. Or create and instance. What suites the best depends on the logic that you want to apply for this class and how it will be used later.
Instance approach
private void btnEnter_Click(object sender, EventArgs e)
{
var settings = new PublicSettings();
string a = settings.ConnStr;
}
Static field approach
class PublicSettings
{
private static string _ConnStr = "Connection";
public static string ConnStr
{
get
{
return _ConnStr;
}
set
{
_ConnStr = value;
}
}
}
For a connection string, I would either use a Configuration file (app.config) or make the property a static read-only property (since there's often no reason to change a connection string at run-time):
class PublicSettings
{
public static string ConnStr
{
get
{
return "Connection";
}
}
}
I wanted to create a web control which has collection featured in the ASPX. I have code below which has a problem.
I seem to turn off and objects collection editor(collection stable).But I object design information Design Time at runtime what you can not get
when I turn off the project.So in a way the information will be saved during design is disappear.
When I open the project files in aspx file nor what. Designer.cs do not coincide in any record in the file.
I want to show in the picture below, this situation partially.
Based on the above, or as seen in the example in asp.net collection listing on sample collection can fix or waiting for your advice.
Here is code
//******************************************************Rol.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SANNET.ToolBox.TemelRoller
{/*
[ControlBuilder(typeof(ListItemControlBuilder))]
[ParseChildren(true, "Text")]*/
[TypeConverter(typeof(ExpandableObjectConverter))]
public class Rol
{
private string rolAdi;
private AksiyonTuru aksiyonIcinKullan;
private EfektTuru iseYapilacak;
private string hataMesaji;
private IOzelEfekt ozelEfekt;
public String RolAdi { get { return rolAdi; } set { rolAdi = value; } }
public AksiyonTuru AksiyonIcinKullan { get { return aksiyonIcinKullan; } set { aksiyonIcinKullan = value; } }
public EfektTuru IseYapilacak { get { return iseYapilacak; } set { iseYapilacak = value; } }
public String HataMesaji { get { return hataMesaji; } set { hataMesaji = value; } }
public IOzelEfekt OzelEfekt { get { return ozelEfekt; } set { ozelEfekt = value; } }
public Rol()
{
RolAdi = "Hicbiri";
}
/*
public string GetAttribute(string key)
{
return (String)ViewState[key];
}
public void SetAttribute(string key, string value)
{
ViewState[key] = value;
}*/
}
}
//******************************************************RolListesi.cs
using SANNET.ToolBox.Yardimcilar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
namespace SANNET.ToolBox.TemelRoller
{
//[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class RolListesi : CollectionBase//ICollection<Rol>
{
private Collection<Rol> roller;
private Control parent;
public RolListesi(Control parent)
{
this.parent = parent;
parent.PreRender += parent_PreRender;
parent.Load += parent_PreRender;
roller = new Collection<Rol>();
}
void parent_PreRender(object sender, EventArgs e)
{
RolIslemleri.PreRenderIsle((Control)sender, this);
}
public Control Parent { get { return this.parent; } }
public Rol rolGetir(String rolAdi)
{
foreach (Rol r in roller) {
if (r.RolAdi.Equals(rolAdi))
return r;
}
return null;
}
public bool Contains(String rolAdi)
{
return rolGetir(rolAdi) != null;
}
public Rol this[int index]
{
get { return (Rol)roller[index]; }
}
public void Add(Rol emp)
{
roller.Add(emp);
}
public void Remove(Rol emp)
{
roller.Remove(emp);
}
}
}
//******************************************************RolCollectionEditor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SANNET.ToolBox.TemelRoller
{
public class RolCollectionEditor : CollectionEditor
{
public RolCollectionEditor(Type type)
: base(type)
{
}
protected override string GetDisplayText(object value)
{
Rol item = new Rol();
item = (Rol)value;
return base.GetDisplayText(string.Format("{0}, {1}", item.RolAdi,
item.AksiyonIcinKullan));
}
}
}
//******************************************************SANButton.cs
using DevExpress.Web.ASPxEditors;
using SANNET.ToolBox.TemelRoller;
using System.ComponentModel;
using System.Web.UI;
namespace SANNET.ToolBox.Bilesenler
{
public class SANButton : ASPxButton, IRolSahibi
{
private RolListesi roller;
/* [Editor(typeof(System.ComponentModel.Design.CollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]*/
[Editor(typeof(RolCollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public RolListesi Roller { get {
if (roller == null)
{
roller = new RolListesi(this);
}
return roller; } }
}
}
The answer is
[PersistenceMode(PersistenceMode.InnerProperty)]
Here is sample usage
private Roller roller;
[Editor(typeof(RolCollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PersistenceMode(PersistenceMode.InnerProperty)]
public Roller Roller
{
get
{
if (roller == null)
{
roller = new Roller();
} return roller;
}
}
I've been going crazy over this particular problem. What I am trying to do is make an HTTPS Call to the server after a user clicks the sign up button. The server must add the new user to the database and send me back a user key. I've tested the httpClient class with a local LAMP server without HTTPS. Works fine. When I try to connect to the productions server with SSL I GET A 404 - NOT FOUND. I have double checked that the URL, CONTENT and Authorization is formatted well. As a matter of facted I codded it in a console application and it connects to the production server every time. It just does not work with the windows phone emulator or my windows phone. Been monitoring everything with fiddler. I've also used the WebClient class to no avail. PLEASE HELP!
Code below!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JailBird_ProtoType.Models
{
// CLASS USED TO FORMAT OBJECT TO JSON STRING
public class TestUser
{
public string Name { set; get; }
public string Email { get; set; }
public string Password { set; get; }
public List<string> Roles = new List<string>();
}
}
using Microsoft.Phone.Net.NetworkInformation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace JailBird_ProtoType.Services
{
public class UploadJsonService
{
private BackgroundWorker bw = new BackgroundWorker();
public BackgroundWorker GetBackGroundWorker { get { return bw; } }
private HttpClient client = new HttpClient();
private HttpClient GetClient { get { return client; } }
private HttpResponseMessage response;
public HttpResponseMessage GetResponseMessage { get { return response; } }
// SET THE UPLOAD URL
private string uploadURL;
public string SetUploadURL { set { uploadURL = value; } }
// SET THE STRING DATA UPLOAD VALUE
private string jsonValue ="";
public string SetJsonValue { set { jsonValue = value; } }
private HttpContent httpContent;
public HttpContent GetHttpContent { get { return httpContent; } set { httpContent = value; } }
// SET THE METHOD TYPE UPLOAD VALUE
private string Method = "POST";
public string SetMethod { set { Method = value; } }
// CONSRUCTOR
public UploadJsonService()
{
SetUpClass();
}
public UploadJsonService(string url, string data)
{
SetUploadURL = url;
SetJsonValue = data;
SetUpClass();
}
public UploadJsonService(string url, string method, string data)
{
SetUploadURL = url;
SetJsonValue = data;
SetMethod = method;
SetUpClass();
}
private void SetUpClass()
{
bw.DoWork += new DoWorkEventHandler(DoWork);
httpContent = new StringContent(jsonValue);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
public void StartUpload()
{
try
{
bw.RunWorkerAsync(); // RUN BACKGROUND WORKER
}
catch (Exception) { }
}
public void CancelUpload()
{
// CANCEL ALL WORKER TASKS
try
{
client.Dispose();
httpContent = null;
bw.CancelAsync();
}
catch (Exception) { }
}
public void SetHeader(string header, string value)
{
client.DefaultRequestHeaders.Add(header, value);
}
private async void DoWork(object sender, DoWorkEventArgs e)
{
if (isConnectionReady())
{
try
{
if (Method.ToLower() == "post")
{
response = await client.PostAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
}
else if (Method.ToLower() == "push")
{
response = await client.PutAsync(new Uri(uploadURL, UriKind.Absolute), httpContent);
}
// DO SOMETHING WITH THE RESPONSE HERE
}
catch (Exception)
{
//UPDATE THE UI THREAD HERE
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
MessageBox.Show("Upload did not complete successfully. Check your connection settings.", "Something Went Wrong", MessageBoxButton.OK);
}));
}
}
else
{
//UPDATE THE UI THREAD HERE
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
MessageBox.Show("Check your phone's connection settings", "No Network Connection", MessageBoxButton.OK);
}));
}
}
// METHOD USED TO CHECK FOR NETWORK CONNECTION
private bool isConnectionReady()
{
bool internet = false;
//Check if network is available
if (DeviceNetworkInformation.IsNetworkAvailable)
{
internet = true;
}
return internet;
}
}
}
// THIS METHOD IS ACTIVATED IN THE SIGNUP BUTTON EVENT HANDLER
public void SendToServer()
{
// string user = JsonConvert.SerializeObject(App.ViewModel.Users[0]); // Get User Information
TestUser me = new TestUser() { Name="testName2", Password="password",Email="mail#mail.com"};
me.Roles.Add("User");
string meString = JsonConvert.SerializeObject(me);
if (App.Settings.Contains("FirstSignUp"))
{
service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"PUT",meString);
}
else
{
service = new UploadJsonService(ConnectToServer.USER_UPLOAD_URL,"POST",meString);
}
service.SetHeader("Authorization", "Basic " + ConnectToServer.Get64BitEncoding(ConnectToServer.SERVER_ADMIN));
service.GetBackGroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(RunWorkerServiceCompleted);
service.StartUpload();
}
private void RunWorkerServiceCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// DO WORK AFTER THE BACKGROUND WORKER COMPLETES
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JailBird_ProtoType.Services
{
// THIS CLASS HOLDS ALL SERVER INFORMATION
// FOR QUICK ACCESS AND CHANGE
public static class ConnectToServer
{
public static string SERVER_ADMIN = "admin:password";
// UPLOAD USER TO DB
public static string USER_UPLOAD_URL = "https://xx.xxx.xx.xxx:443/api/users";
public static string Get64BitEncoding(string key) {
byte[] convert = System.Text.Encoding.UTF8.GetBytes(key);
return System.Convert.ToBase64String(convert);
}
}
}
omitted real server address for security reasons.
Sorry my code is not structured Right. Been changing it around to get this to work.
I'm having trouble with the copying entities between multiple databases. I can't seem to get my head around this issue and really need some help with the implementation.
My current implementation is described here:
Http module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using ISMSControl.Infrastructure.Sessions;
using NHibernate;
using NHibernate.Context;
namespace ISMSControl.Infrastructure.Modules
{
public class SessionModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OpenSession;
context.EndRequest += CloseSession;
}
private void CloseSession(object sender, EventArgs e)
{
ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.GetCurrentSession().SessionFactory);
if (session != null)
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Rollback();
else
session.Flush();
session.Close();
}
}
private void OpenSession(object sender, EventArgs e)
{
ManagedWebSessionContext.Bind(HttpContext.Current,
SessionManager.GetCurrentSession());
}
public void Dispose()
{
}
}
}
SessionManager implemenation
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using ISMSControl.Infrastructure.Mappings;
using NHibernate;
using NHibernate.Cache;
namespace ISMSControl.Infrastructure.Sessions
{
public sealed class SessionManager
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;
static SessionManager()
{
sessionFactory = CreateSessionFactory("source");
}
private static ISessionFactory CreateSessionFactory(string connectionStringName)
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(c => c.FromConnectionStringWithKey(connectionStringName)))
.CurrentSessionContext("managed_web")
.Cache(c =>
{
c.UseQueryCache();
c.ProviderClass<HashtableCacheProvider>();
})
.Diagnostics(d =>
{
d.Enable();
d.OutputToConsole();
})
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<StandardMapping>())
.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}
public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;
if (currentSession == null)
{
// No current session
return;
}
currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}
public static void CloseSessionFactory(string sessionFactoryName = null)
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}
Repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using ISMSControl.Domain;
using ISMSControl.Domain.Contracts;
using ISMSControl.Infrastructure.Sessions;
using NHibernate;
using NHibernate.Context;
namespace ISMSControl.Infrastructure.Repositories
{
public class StandardRepository : IStandardRepository
{
public void SaveOrUpdate(Standard standard)
{
var session = SessionManager.GetCurrentSession();
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(standard);
transaction.Commit();
}
}
public IEnumerable<Standard> RetrieveList()
{
return SessionManager.GetCurrentSession().CreateCriteria<Standard>().List<Standard>();
}
public void CopyTo(string database, Standard standard)
{
//how do i implement this method, so it will copy the standard entity to the other database?
}
}
}
The problem is that i'm getting all these different kind of errors like, "The session is closed.", "The entity belows to another transaction or something". "Illegal attempt to associate a collection with two open sessions".
I really hope that someone can help me out our point me in the right direction by sharing a
Tutorial
Example
etc.
CopyTo implemenation
public void CopyTo(string sessionFactoryName, Standard standard)
{
//gets a new session for the destination database from the destination sessionfactory.
using (var destinationSession = SessionFactoryContainer.Current.Get(sessionFactoryName).OpenSession())
{
//error: no persister for...
var newStandard = new Standard();
newStandard.Code = standard.Code;
newStandard.Description = standard.Description;
newStandard.Explanation = standard.Explanation;
destinationSession.Save(newStandard);
}
}
In your "CopyTo" method, you have to create a session on the second database, deep clone the second parameter of your method and then attach the cloned object to the session you opened.
I have a problem that has been driving me nuts.
I have 2 ASPX pages in which the parent use Server.Transfer() function. The parent is called Submit.aspx whereas child is called Review.aspx
In Submit.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Contacts_Submit : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Review_Click(object sender, EventArgs e)
{
Server.Transfer("Review.aspx", true);
}
/*
* Sequence of functions that will server as a Get functionality that will
* return the text inside each textbox.
* These information will be used by "Review.aspx" to validate the
* information given by the user before final submission takes place.
*/
public string GetFirstName { get { return FirstName.Text; } }
public string GetLastName { get { return LastName.Text; } }
public string GetAddress { get { return Address.Text; } }
public string GetCountry { get { return Country.SelectedValue; } }
public string GetProvince { get { return Province.SelectedValue; } }
public string GetCity { get { return City.Text; } }
public string GetZipCode { get { return ZipCode.Text; } }
public string GetWorkPhone { get { return WorkPhone.Text; } }
public string GetMobilePhone { get { return MobilePhone.Text; } }
public string GetFax { get { return Fax.Text; } }
public string GetEmail { get { return Email.Text; } }
public string GetCompany { get { return Company.Text; } }
public string GetWebsite { get { return Website.Text; } }
public string GetRelationship { get { return Relationship.SelectedValue; } }
}
Whereas on the Review.aspx.cs, I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Contacts_Review : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if(PreviousPage != null)
{
Contacts_Submit prevpage = PreviousPage as Contacts_Submit;
//FirstName.Text = PreviousPage.GetFirstName;
}
}
}
The problem is when I declare "Contacts_Submit prevpage = PreviousPage as Contacts_Submit". The system is giving me an error that says "The type or namespace name 'Contacts_Submit' could not be found (are you missing a using directive or an assembly reference?)".
I am a beginner in both ASP.NET and C#, can anyone help me with this? Thank you SOOO MUCH.
I think you just want
Contacts_Submit prevpage = PreviousPage as Contacts_Submit;
instead of
Contacts_Submit prevpage = PreviousPage as System.Data.DataSet Contacts_Submit;
Contacts_Submit is type of Page and not in any way related to Dataset, so your cast is invalid.
remove that and it should be fine