Using Sqlite how to maintain mailing service in windows phone 8.1 - c#

I created a login page and registration page in windows phone 8.1 app using sqlite database. When I login through the values from database how to create a mail system similar to normal mailing services like gmail using sqlite database.
(or)
How to save particular user data with respect to the user logged in. When the user login to the mainpage his data should be displayed.
Please answer the above both questions.
I successfully created login and registration page and I can insert values to the database. After navigating to the new page what should I code in order to show the data of the logged in user
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
Register m = new Register();
m.Name = text_reg.Text;
m.Password = text_password.Password;
string r = "";
if (radio_male.IsChecked == true)
{
r = "Male";
}
else
{
r = "Female";
}
m.Gender = r;
m.State = ((ComboBoxItem)combo_box.SelectedItem).Content.ToString();
await con.InsertAsync(m);
MessageDialog md = new MessageDialog("success");
await md.ShowAsync();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
Windows.Storage.ApplicationDataContainer data = Windows.Storage.ApplicationData.Current.LocalSettings;
data.Values["check"] = text_reg.Text;
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
Register t = new Register();
string query = string.Format("select Name,Password from Register where Name='{0}' and Password='{1}'", text_user.Text, text_pass.Password);
List<Register> mylist = await con.QueryAsync<Register>(query);
if (mylist.Count == 1)
{
t = mylist[0];
}
if (t.Name == text_user.Text && t.Password == text_pass.Password)
{
this.Frame.Navigate(typeof(MainPage));
}
else
{
var messagedialog = new MessageDialog("Unsuccessful").ShowAsync();
}
}
The above code runs successfully. After navigating to next page(i.e MainPage) how to show the particular data

Ok, the mailing system part of your question I couldn't fully understand it.
as for the second part, you have many options.
Use a static property that will hold t and reuse it in every page in your app if you want.
Use a ViewModel to hold any values you want to reuse across your app.
Write whatever values you want to a Temp file within your app scope/domain
The easiest way is option 1.
just add public static Register CurrentUser { get; set; }; to your App.xaml.cs.
and you can access this variable via App.CurrentUser.Name and App.CurrentUser.Password
and don't forget to set CurrentUser before your navigation to main Page.
App.CurrentUser = t;

Related

c# Can't Connecting with firebase and why SetTaskAsync returns nulls with your current code

Just I'm Trying to insert a data From C# Windows Forms Application User control
to My firebase.
I have Install Nuget Package "FirebaseDatabase.net".
I have checked AuthSecret and BasePath is correct, but why response i null.
Im any thing missing ? Please Help Me don't Close this Question.
I'm Followed this https://www.youtube.com/watch?v=jZMwwZHJXJc
using FireSharp.Config;
using FireSharp.Response;
using FireSharp.Interfaces;
IFirebaseConfig Config = new FirebaseConfig
{
AuthSecret = "xyz",
BasePath = "https://xyz-56633a.firebaseio.com"
};
IFirebaseClient Client;
Client = new FireSharp.FirebaseClient(Config);
if (Client!= null)
{
MessageBox.Show("Connected");
}
else
{
MessageBox.Show("Error Connection");
}
private async void Button1_Click(object sender, EventArgs e)
{
var data = new Data()
{
id = textBox1.Text,
Name1 = textBox2.Text,
Name2 = textBox3.Text,
Name3 = textBox4.Text,
Name4 = textBox5.Text,
};
SetResponse response = await Client.SetTaskAsync("NewList/" + textBox1.Text,data);
Data result = response.ResultAs<Data>();
MessageBox.Show("Data Inserted" + result);
}
}
While the above Code runing
MessageBox.Show("Connected");
is Working. But
Data result= response.ResultAs<Data>();
Show Error As System.NullReferenceException: 'Object reference not set to an instance of an object.'
And the Data is not inserted. Please Help me to Fix this or If any other way available forward to me
Did not get any more answer for "why is not working?" but i solve this issue.
This above code is correct is running in window form but not working in user control.
Hence i just copy the code to form and pass the the value from user control to form.
Passing the values from user control to form
private void button4_Click(object sender, EventArgs e)
{
string[] product = {textBox1.Text,textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text };
Form1 f1 = new Form1();
f1.UsercontroleData(product);
}
Asyne in window form
Internal async void UsercontroleData( string[] Product)
{
var np = new newProduct()
{
Id = "Execute PUSH",
Category = Product[0],
SubCategory = Product[1],
Modal = Product[2],
Brand = Product[3],
Unite = Product[4],
};
PushResponse response = await client.PushTaskAsync("Product/List", np);
newProduct ff = response.ResultAs<newProduct>();
newProduct result = response.ResultAs<newProduct>();
}

How can I use progress bar while fetching data from server database located in web in c# winforms?

After login process I want to load form1 with mdi.
In the Pageload event of the Form1 load database table data from web using JSon and saved to the local database.
Form1 pageload take lots of time.
When I execute my application the mdi form load first and after some time form1 is loaded.
I want to resolve this issue. This is my pageload event code.
Here get data from web and saved to the local database.
Then set the data to the controls in form1.
private void Form1_Load(object sender, EventArgs e)
{
string strUrlService = "http://.............................";
string strUrlBranch = "http://......................";
string strUrlOrigin = "http://.....";
string strUrlEmployee = "http://.......";
.............................
GetServiceType(strUrlService);
GetBranch(strUrlBranch);
GetOrigin(strUrlOrigin);
GetEmployee(strUrlEmployee);
.............................
SetServiceType();
SetBranch();
SetOrigin();
SetEmployee();
......................
}
GetServiceType method definition. Using Json object get value from web. And saved this data to the local database.
//---------Get ServiceType from web database-------------
private void GetServiceType(string strUrl)
{
ServiceType obj = new ServiceType();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(strUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(strUrl).Result;
if (response.IsSuccessStatusCode)
{
var JsonResult = response.Content.ReadAsStringAsync().Result;
System.Web.Script.Serialization.JavaScriptSerializer tmp = new System.Web.Script.Serialization.JavaScriptSerializer();
obj = (ServiceType)tmp.Deserialize(JsonResult, typeof(ServiceType));
}
if (obj != null)
{
int count = obj.products.Count;
int[] TxtID = new int[count];
..............................
for (int i = 0; i < count; i++)
{
TxtID[i] = Convert.ToInt32(obj.products[i].id.ToString());
...............................
}
FunSaveServiceType(TxtID, txtService, txtCode, intDays);
}
}
In SetServiceType() method retrieve data(which is fetched from web and saved to local database) from local database. And this data is set to the combo box in the form1.
//--------------set service type to Form1 combobox control-----------------
private void SetServiceType()
{
DataTable dtService = new DataTable();
dtService = GetServiceTypeFromDB();
DataRow dr = dtService.NewRow();
dr["ServiceType"] = "";
dtService.Rows.InsertAt(dr, 0);
cbServiceType.DataSource = dtService;
}
These are the process done before the form1 pageload event. These codes are working properly.
I am tried to set a progressbar and background worker in my mdi form. But it is not working properly.
If you are using .Net 4.5 you won't longer need a background-worker. You can use the new TPL (Task Parallel Library). What you need at first is a progressbar which you can show in a different form. You could also use your mainform for showing progress, but you should use the Form1.Shown Event than. This is fired if your form is up and running and your gui-components are loaded properly.
You can implement the progress logic in the Shown-Event as following:
private async void Form1_Shown(object sender, EventArgs e)
{
var progressHandler = new Progress<string>(value =>
{
//What to do if a Progress is reported?
//For example set progressbar and labeltext
progressBar.Step();
label1.Text = value; //Value stores the string you send via Report (see at bottom method)
});
await InitializeServicesAsync(progressHandler as IProgress<string>);
}
private async Task InitializeServicesAsync(IProgress<string> progress)
{
await Task.Run(() =>
{
string strUrlService = "http://.............................";
string strUrlBranch = "http://......................";
string strUrlOrigin = "http://.....";
string strUrlEmployee = "http://.......";
GetServiceType(strUrlService);
progress.Report("Getting Servicetypes done");
GetBranch(strUrlBranch);
progress.Report("Getting Branch done");
GetOrigin(strUrlOrigin);
progress.Report("Getting Origin done");
GetEmployee(strUrlEmployee);
progress.Report("Getting Employee done");
SetServiceType();
progress.Report("Setting ServiceType done");
SetBranch();
//Report further progress as often as you need
SetOrigin();
SetEmployee();
});
}
Check out this blogpost to learn more.

when i restart my emulator i cannot retrieve database values in sqlite windows phone 8.1

I designed a login and registration page using Sqlite database in windows phone 8.1. With the following code I can successfully insert and retrieve the values from sqlite database. But it happens only once. When I restart my emualator I cannot retrieve the values from database.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
Register m = new Register();
m.Name = text_reg.Text;
m.Password = text_password.Password;
string rd = "";
if (radio_male.IsChecked == true)
{
rd = "Male";
}
else
{
rd = "Female";
}
m.Gender = rd;
m.State = ((ComboBoxItem)combo_box.SelectedItem).Content.ToString();
await con.InsertAsync(m);
MessageDialog md = new MessageDialog("success");
await md.ShowAsync();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
Register t = new Register();
string query = string.Format("select Name,Password from Register where Name='{0}' and Password='{1}'", text_user.Text, text_pass.Password);
List<Register> mylist = await con.QueryAsync<Register>(query);
if (mylist.Count == 1)
{
t = mylist[0];
}
if (t.Name == text_user.Text && t.Password == text_pass.Password)
{
this.Frame.Navigate(typeof(MainPage));
}
else
{
var messagedialog = new MessageDialog("Unsuccessful").ShowAsync();
}
}
}
This is the expected behavior. State isn't persisted in the Windows Phone emulator. When you restart it, it loses all the data you previously stored (settings, installed applications, and whatever you wrote on the storage).
This won't occur on an actual, physical device.

About Application data(local settings) and Sqlite database in windows phone 8.1

I have a small doubt about using SQLite database and local settings. I have an idea about how to use local settings for an app. When we use Application data(local settings) in our application we can restore the previous state of the application. Can we use sqlite local database to store and retrieve the values while we use local settings.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (data.Values["check"] != null)
{
this.Frame.Navigate(typeof(BlankPage1));
}
if (data.Values["add"] != null)
{
list_view.Items.Add(data.Values["add"].ToString());
}
if (data.Values["remove"] != null)
{
list_view.Items.Remove(data.Values["remove"]);
}
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<list>();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(!mypop.IsOpen)
{
mypop.IsOpen = true;
}
}
public async void Button_Click_1(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
list l = new list();
data.Values["add"] = l.list1;
l.list1 = text_input.Text.ToString();
await con.InsertAsync(l);
await con.UpdateAllAsync(l.list1);
data.Values["add"] = l.list1;
list_view.Items.Add(data.Values["add"].ToString());
mypop.IsOpen = false;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
if(mypop.IsOpen)
{
mypop.IsOpen = false;
}
}
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
list l = new list();
data.Values["remove"] = l.list1;
l.list1 = list_view.SelectedItem.ToString();
list_view.Items.Remove(list_view.SelectedItem);
List<list> mylist = await con.QueryAsync<list>("delete from list where list1='" + list_view.SelectedItem + "'");
mylist.Remove(l);
Please check and verify the code. I can only store single value to local settings. When I restart my application only one value will be shown. It wont show the values inserted in the listview. Please also check delete query. It is not working.. please help me...

WP8 - Facebook Login Issue

I am trying to authenticate a user on Facebook using the Facebook C# SDK on Windows Phone 8. To do so I am following the code here: FacebookLoginPage.xaml.cs
But the problem I am facing is that, whenever I input my username and password into the dialog that opens to authenticate the user, I just get the following page:
After this, my program does not redirect to the Landing page which is a separate view. The other solutions I have seen that suggest hiding the WebView are not applicable since the authentication is abstracted into a single LoginAsync function call.
Any suggestions on what to do?
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control.
What the C# SDK does, is generate the login page as "http://www.facebook.com....". When you open this URL on the webbrowser control, it gets redirected to "http://m.facebook.com..." which displays the mobile version of the FB login page.
This previously has no issue, but recently, when FB does the redirection, it also strips the parameter "display=page" from the URL. What happens then is that when a successful FB login is made, the "login_success.html" page is opened without this parameter. Without the "display=page" parameter passed in, it defaults to "display=touch". This URL unfortunately, does not append the token string in the URL, hence the page shown in the very first thread is displayed.
The solution to this is, instead of using the below code to generate the login URL, ammend it to
original:
Browser.Navigate(_fb.GetLoginUrl(parameters));
ammended:
var URI = _fb.GetLoginUrl(parameters).toString().replace("www.facebook.com","m.facebook.com");
Browser.Navigate(new Uri(URI));
In my project I just listened for the WebView's navigated event. If it happens, it means that user did something on the login page (i.e. pressed login button).
Then I parsed the uri of the page you mentioned which should contain OAuth callback url, if it is correct and the result is success I redirect manually to the correct page:
//somewhere in the app
private readonly FacebookClient _fb = new FacebookClient();
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
//you have an access token, you can proceed further
FBLoginSucceded(accessToken);
}
else
{
// errors when logging in
MessageBox.Show(oauthResult.ErrorDescription);
}
}
If you abstract logging in an async function, you expect it to behave asynchronously, so events are ok.
Sorry for my English.
The code for the full page:
public partial class LoginPageFacebook : PhoneApplicationPage
{
private readonly string AppId = Constants.FacebookAppId;
private const string ExtendedPermissions = "user_birthday,email,user_photos";
private readonly FacebookClient _fb = new FacebookClient();
private Dictionary<string, object> facebookData = new Dictionary<string, object>();
UserIdentity userIdentity = App.Current.Resources["userIdentity"] as UserIdentity;
public LoginPageFacebook()
{
InitializeComponent();
}
private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
{
var loginUrl = GetFacebookLoginUrl(AppId, ExtendedPermissions);
webBrowser1.Navigate(loginUrl);
}
private Uri GetFacebookLoginUrl(string appId, string extendedPermissions)
{
var parameters = new Dictionary<string, object>();
parameters["client_id"] = appId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
// add the 'scope' only if we have extendedPermissions.
if (!string.IsNullOrEmpty(extendedPermissions))
{
// A comma-delimited list of permissions
parameters["scope"] = extendedPermissions;
}
return _fb.GetLoginUrl(parameters);
}
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (waitPanel.Visibility == Visibility.Visible)
{
waitPanel.Visibility = Visibility.Collapsed;
webBrowser1.Visibility = Visibility.Visible;
}
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
FBLoginSucceded(accessToken);
}
else
{
// user cancelled
MessageBox.Show(oauthResult.ErrorDescription);
}
}
private void FBLoginSucceded(string accessToken)
{
var fb = new FacebookClient(accessToken);
fb.GetCompleted += (o, e) =>
{
if (e.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
return;
}
var result = (IDictionary<string, object>)e.GetResultData();
var id = (string)result["id"];
userIdentity.FBAccessToken = accessToken;
userIdentity.FBID = id;
facebookData["Name"] = result["first_name"];
facebookData["Surname"] = result["last_name"];
facebookData["Email"] = result["email"];
facebookData["Birthday"] = DateTime.Parse((string)result["birthday"]);
facebookData["Country"] = result["locale"];
Dispatcher.BeginInvoke(() =>
{
BitmapImage profilePicture = new BitmapImage(new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", id, "square", accessToken)));
facebookData["ProfilePicture"] = profilePicture;
userIdentity.FBData = facebookData;
userIdentity.ProfilePicture = profilePicture;
ARLoginOrRegister();
});
};
fb.GetAsync("me");
}
private void ARLoginOrRegister()
{
WebService.ARServiceClient client = new WebService.ARServiceClient();
client.GetUserCompleted += client_GetUserCompleted;
client.GetUserAsync((string)facebookData["Email"]);
client.CloseAsync();
}
void client_GetUserCompleted(object sender, WebService.GetUserCompletedEventArgs e)
{
if (e.Result == null)
NavigationService.Navigate(new Uri("/RegisterPageFacebook.xaml", UriKind.RelativeOrAbsolute));
else if (e.Result.AccountType != (int)AccountType.Facebook)
{
MessageBox.Show("This account is not registered with facebook!");
NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.RelativeOrAbsolute));
}
else
{
userIdentity.Authenticated += userIdentity_Authenticated;
userIdentity.FetchARSocialData((string)facebookData["Email"]);
}
}
void userIdentity_Authenticated(bool success)
{
NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.RelativeOrAbsolute));
}
}
Before trying to do all the proposed changes,
please check that your Facebook App is not on Sandbox mode. This will eventually resolve your issue.
If your facebook app is in sandbox mode, only the developer can login, using his email address. Any other fb user will get the white page.

Categories