Display message in a toastr after controller method finish - javascript

i have controller method that upload image file, not using jQuery AJAX, from <input> type "file", the method returns:
Return Redirect(Request.UrlReferrer.PathAndQuery)
Because i want to stay in the same view after the submit click.
I want to show after the success image upload, toastr.success.
How i can do it?

In your http post action method, after successful upload, set an entry to TempData dictionary and read it in the next view which is loaded by the Redirect method and display the toastr message.
TempData["Msg"] = "Uploaded successfully";
return Redirect(Request.UrlReferrer.PathAndQuery);
in your view
<script>
$(function(){
var msg = "#(TempData["Msg"] as string)";
if (msg !== "") {
toastr.success(msg);
}
});
</script>

There is another way.
Create a Toastr model that includes Message, Title, Type, SessionID and Date.
public class Toastr
{
public string Title { get; set; }
public string Message { get; set; }
public ToastrType Type { get; set; }
public string SessionId { get; set; }
public DateTime Date { get; set; }
public Toastr(string message, string title = "Information" , ToastrType type = ToastrType.Info)
{
this.Message = message;
this.Title = title;
this.Type = type;
this.Date = DateTime.Now;
}
}
public enum ToastrType
{
Info = 0,
Success = 1,
Warning = 2,
Error = 3
}
Create a Service or Manager where you define your basic functions (add, remove toasts)
private static List<Toastr> _toasts = new List<Toastr>();
private static string GetSession()
{
return HttpContext.Current.Session.SessionID;
}
public static void AddToUserQueue(Toastr toastr)
{
toastr.SessionId = GetSession();
_toasts.Add(toastr);
}
public static void AddToUserQueue(string message, string title, ToastrType type)
{
var toast = new Toastr(message, title, type);
toast.SessionId = GetSession();
AddToUserQueue(toast);
}
public static bool HasQueue()
{
return _toasts.Any(t => t.SessionId == GetSession());
}
public static void RemoveUserQueue()
{
_toasts.RemoveAll(t => t.SessionId == GetSession());
}
public static void ClearAll()
{
_toasts.Clear();
}
public static List<Toastr> GetUserQueue()
{
if (HasQueue())
return _toasts.Where(t => t.SessionId == GetSession())
.OrderByDescending(x=>x.Date)
.ToList();
return null;
}
public static List<Toastr> GetAndRemoveUserQueue()
{
var list = GetUserQueue();
RemoveUserQueue();
return list;
}
In your layout / page make use of the functions by creating some helpers.
#helper ProcessToasts()
{
List<Toastr> toasts = ToastrManager.GetAndRemoveUserQueue();
if (toasts != null && toasts.Count > 0)
{
foreach (var item in toasts)
{
#ShowToastr(item);
}
}
}
#helper ShowToastr(Toastr item)
{
switch (item.Type)
{
case ToastrType.Info:
#ToastrInfo(item.Message, item.Title)
break;
case ToastrType.Success:
#ToastrSuccess(item.Message, item.Title)
break;
case ToastrType.Warning:
#ToastrWarning(item.Message, item.Title)
break;
case ToastrType.Error:
#ToastrError(item.Message, item.Title);
break;
}
}
#helper ToastrInfo(string message, string title)
{
<script>
toastr.info("#message","#title")
</script>
}
#helper ToastrSuccess(string message, string title)
{
<script>
toastr.success("#message","#title")
</script>
}
#helper ToastrWarning(string message, string title)
{
<script>
toastr.warning("#message","#title")
</script>
}
#helper ToastrError(string message, string title)
{
<script>
toastr.error("#message","#title")
</script>
}
Since the helpers are below closing HTML tag, you need just to add the #ProcessToasts() right before the body closing tag.

Related

How fix to SMS Retriever API

I wrote code for example "SMS Retreiver API" https://developers.google.com/identity/sms-retriever/request
but I don`t result which I wont
This code past to MainActivity.
SmsRetrieverClient client = SmsRetriever.getClient(this);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
This code past to MySMSBroadcastReceiver.
public class MySMSBroadcastReceiver extends BroadcastReceiver {
String message;
Status status;
private static MessageListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch(status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
// Get SMS message contents
message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
// Extract one-time code from the message and complete verification
// by sending the code back to your server.
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
// Handle the error ...
break;
}
mListener.MySMSBroadcastReceiver(message);
}
}
public static void bindListener(MessageListener listener){
mListener = listener;
}
}
In my Manifest
<receiver android:name="ru.project.MBank.MySMSBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
But result get nothing.
Help what do I do wrong?
I had same problem. First you need to generate a unique key (App Signature) that will identify message and your device. Once you generate key, your broadcaster will be able to detect message.
public class AppSignature extends ContextWrapper {
public static final String TAG = AppSignature.class.getSimpleName();
private static final String HASH_TYPE = "SHA-256";
public static final int NUM_HASHED_BYTES = 9;
public static final int NUM_BASE64_CHAR = 11;
public AppSignature(Context context) {
super(context);
}
/**
* Get all the app signatures for the current package
* #return
*/
public ArrayList<String> getAppSignatures() {
ArrayList<String> appCodes = new ArrayList<>();
try {
// Get all package signatures for the current package
String packageName = getPackageName();
PackageManager packageManager = getPackageManager();
Signature[] signatures = packageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES).signatures;
// For each signature create a compatible hash
for (Signature signature : signatures) {
String hash = hash(packageName, signature.toCharsString());
if (hash != null) {
appCodes.add(String.format("%s", hash));
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable to find package to obtain hash.", e);
}
return appCodes;
}
private static String hash(String packageName, String signature) {
String appInfo = packageName + " " + signature;
try {
MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE);
messageDigest.update(appInfo.getBytes(StandardCharsets.UTF_8));
byte[] hashSignature = messageDigest.digest();
// truncated into NUM_HASHED_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
// encode into Base64
String base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP);
base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR);
return base64Hash;
} catch (NoSuchAlgorithmException e) {
}
return null;
}
}
After this initiate this class in your firs activity.
Hope this will help you.

Added columns to SQLiteDatabase, can no longer read from it

My SQLiteDatabase was working fine with just 3 entries, the UUID, Title and Date, but ever since I added some more columns I am getting this error.
Not sure what it can be, I have read that 0,-1 means that the column cannot be read, but I have made sure to spell all my column names correctly.
CrimeCursorWrapper.java
public List<Crime> getCrimes() {
List<Crime> crimes = new ArrayList<>();
CrimeCursorWrapper cursor = queryCrimes(null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
crimes.add(cursor.getCrime());
cursor.moveToNext();
}
} finally{
cursor.close();
}
return crimes;
}
CrimeLab.java:
public Crime getCrime(UUID id) {
CrimeCursorWrapper cursor = queryCrimes(
CrimeTable.Cols.UUID + " = ?",
new String[] { id.toString() }
);
try {
if (cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getCrime();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Crime crime) {
ContentValues values = new ContentValues();
values.put(CrimeTable.Cols.UUID, crime.getId().toString());
values.put(CrimeTable.Cols.TITLE, crime.getTitle());
values.put(CrimeTable.Cols.DATE, crime.getDate().getTime());
values.put(CrimeTable.Cols.ACTTYPE, crime.getActType().toString());
values.put(CrimeTable.Cols.PLACE, crime.getPlace().toString());
values.put(CrimeTable.Cols.DURATION, crime.getDuration().toString());
values.put(CrimeTable.Cols.COMMENT, crime.getComment().toString());
return values;
}
private CrimeCursorWrapper queryCrimes(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(
CrimeTable.NAME,
null, // Columns - null selects all columns
whereClause,
whereArgs,
null, // groupBy
null, // having
null // orderBy
);
return new CrimeCursorWrapper(cursor);
}
CrimeCursorWrapper.java:
public class CrimeCursorWrapper extends CursorWrapper{
public CrimeCursorWrapper(Cursor cursor) {
super(cursor);
}
public Crime getCrime() {
String uuidString = getString(getColumnIndex(CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeTable.Cols.DATE));
String actType = getString(getColumnIndex(CrimeTable.Cols.ACTTYPE));
String place = getString(getColumnIndex(CrimeTable.Cols.PLACE));
String duration = getString(getColumnIndex(CrimeTable.Cols.DURATION));
String comment = getString(getColumnIndex(CrimeTable.Cols.COMMENT));
Crime crime = new Crime(UUID.fromString(uuidString));
crime.setTitle(title);
crime.setDate(new Date(date));
crime.setActType(actType);
crime.setPlace(place);
crime.setDuration(duration);
crime.setComment(comment);
return crime;
}
}
Crime.java:
public class Crime {
private UUID mId;
private String mTitle;
private Date mDate;
private String mActType;
private String mPlace;
private String mDuration;
private String mComment;
public Crime() {
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public String getPhotoFilename() {
return "IMG_" + getId().toString() + ".jpg";
}
public String getActType() {
return mActType;
}
public void setActType(String actType) {
mActType = actType;
}
public String getPlace() {
return mPlace;
}
public void setPlace(String place) {
mPlace = place;
}
public String getDuration() {
return mDuration;
}
public void setDuration(String duration) {
mDuration = duration;
}
public String getComment() {
return mComment;
}
public void setComment(String comment) {
mComment = comment;
}
}
It "CAN" be the reason: If you use your physical mobile device for debugging, after you change your database tables inside the code, delete your application's data from the mobile device and reinstall your apk (or press debug or run buttons). Database files are not updating automatically by Android Studio.
Did you change version of your database after adding more columns? It is mandatory.

p:commandButton execution order of events

I am using PrimeFaces 6.0 components:
<p:commandButton type="submit" value="Create Customer"
icon="ui-icon-check"
actionListener="#{newCustomerBean.saveNewCustomer}"
update = "#form"
oncomplete="ajaxUploadFile();"/>
<p:inputText id="saveCustomerId" value ="#{newCustomerBean.savedKundeId}"/>
and I want to execute the following sequence of actions with them:
1.) Execute the actionListener method on the backing bean to save a customer;
2.) Update the form field saveCustomerId with the id of the customer that is saved on step (1). The actionListener method generates a customer Id after the successful save and stores is as a bean property;
3.) Execute the Java Script method ajaxUploadFile()
According to the link
Execution order of events when pressing PrimeFaces p:commandButton
this sequence shall be as I have imagined.
However, in reality, the method
ajaxUploadFile()
is called BEFORE the input field with id saveCustomerId is updated.
Could you help me get the right sequence?
Here is the backing bean:
#ManagedBean
#ViewScoped
public class NewCustomerBean implements Serializable {
public enum KundeTyp {
TYP_NATPERS("Nat. Person"), TYP_FIRMA("Firma");
private String value;
private KundeTyp(String value) {
this.value = value;
}
#Override
public String toString() {
return value;
}
}
private KundeTyp custmerType;
private Map<String, KundeTyp> custmerTypes;
private long savedKundeId;
#Inject
private KundeDBService kundeService;
private String vorname;
private String addresse;
private String steuerNummer;
private String kundeTyp = Integer.MIN_VALUE + "";
#PostConstruct
public void init() {
custmerTypes = new HashMap<String, KundeTyp>();
custmerTypes.put(KundeTyp.TYP_NATPERS.value, KundeTyp.TYP_NATPERS);
custmerTypes.put(KundeTyp.TYP_FIRMA.value, KundeTyp.TYP_FIRMA);
}
public KundeTyp getCustmerType() {
return custmerType;
}
public void setCustmerType(KundeTyp custmerType) {
this.custmerType = custmerType;
}
public Map<String, KundeTyp> getCustmerTypes() {
return custmerTypes;
}
public void setCustmerTypes(Map<String, KundeTyp> custmerTypes) {
this.custmerTypes = custmerTypes;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getAddresse() {
return addresse;
}
public void setAddresse(String addresse) {
this.addresse = addresse;
}
public String getSteuerNummer() {
return steuerNummer;
}
public void setSteuerNummer(String steuerNummer) {
this.steuerNummer = steuerNummer;
}
public String getKundeTyp() {
return kundeTyp;
}
public void setKundeTyp(String kundenTyp) {
this.kundeTyp = kundenTyp;
}
public String saveNewCustomer(ActionEvent e) {
Kunde neuerKunde = null;
switch (this.custmerType) {
case TYP_NATPERS: {
neuerKunde = new NatuerlichePerson();
break;
}
case TYP_FIRMA: {
neuerKunde = new Firma();
((Firma) neuerKunde).setSteuerNummer("123456");
break;
}
}
neuerKunde.setVorname(vorname);
neuerKunde.setAdresse(this.addresse);
try {
savedKundeId = kundeService.saveKunde(neuerKunde);
} catch (ServiceException se) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
"Unable to save the new customer: " + se.getMessage()));
}
return null;
}
public long getSavedKundeId() {
return savedKundeId;
}
public void setSavedKundeId(long savedKundeId) {
this.savedKundeId = savedKundeId;
}
}
I would propose a work-around here, since I was not able to find a solution.
Instead of updating the customerId on the front-end, we put it as a session attribute in the HttpSession.
Then, in the UploadServlet, which handles the file upload, we read this attribute and save the image under this customerId.

Getting Value from DropDownList to partial view using Ajax

I'm a novice in javascript, and a junior developper in OOP.
After many attempts and many google search I dind't make it to solve it.
I have a DropDownList and a Partial View. I want to give the selected value to the partial view controller. It works when I write the value directly in, but it doesn't if i try to catch the DropDownList value. For the moment the value returned is always empty.
Model
public partial class Clients
{
public int ClientID { get; set; }
public string Code { get; set; }
public string Nom { get; set; }
public string Adresse1 { get; set; }
public string Adresse2 { get; set; }
public string CP { get; set; }
public string Ville { get; set; }
public Nullable<System.DateTime> DateCreation { get; set; }
public Nullable<System.DateTime> DateModification { get; set; }
}
View
#Html.DropDownList("id", (IEnumerable<SelectListItem>)ViewData["oas"], new { #id = "ClientID" })
<div id="result"></div>
<script>
$(function () {
$('#ClientID').change(function () {
//var pid = $("#id").val();//$(this).data('id');
$('#result').load('#Url.Action("filter")',
{ id: $("#id").val() } //replacing $("#id").val() by "3" makes it work, but i of course don't a constant value here
);
});
});
Controller
public class OnePageController : Controller
{
Entities db = new Entities();
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var clts = (
from c in db.Clients
select c).ToArray();
for (int i = 0; i < clts.Length; i++)
{
list.Add(new SelectListItem
{
Text = clts[i].Nom,
Value = clts[i].ClientID.ToString(),
Selected = (clts[i].ClientID == 1)
});
}
ViewData["oas"] = list;
return View(/*db.Clients.ToList()*/);
}
[HttpPost]
public ActionResult Filter(string id)
{
var contact = from c in db.Contacts
where c.ClientID.ToString() == id
select c;
return PartialView(contact);
}
}
Any idea would be greatly appreciated, also i don't know how to debug javasript, i use the developper tools in my when browser to try to catch the values, but i don't really track the changes..
You should change a bit your script:
$(function () {
// You select the element with id = ClientID
var clientEle = $('#ClientID');
// You register an event handler for the change of the selected value
clientEle.change(function () {
// clientEle.val() would return the selected value
$('#result').load('#Url.Action("filter")',{ id: clientEle.val() });
});
});
Regarding how you should debug JavaScript I would suggest to write the following keyword a few lines before you want to start the debugging:
debugger;
Then open developer tools and refresh your page. When JavaScript engine hits the debugger would stop it's execution and from this moment you could examine you code line by line.
For a thorough understanding in how you could debug JavaScript, you could start by checking the following links
https://developers.google.com/web/tools/chrome-devtools/javascript/
https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript
https://www.w3schools.com/js/js_debugging.asp

How to make php more secure in unity

I wish to update a table in a database using php. I'm developing a game in unity using php to retrieve and update data. Each user logs in with their FB details (the correct way by using the FB API), but for now the username is a unique int ID and a sc column that needs to be updated.
Here is a link example: http://www.mydomain.co.za/php/myphp2.php?id=1&sc="1,2"
PHP code (myphp2.php):
<?php
require_once('/home/########/public_html/php/mysqli_connect.php');
$id = $_GET['id'];
$selected_cards = $_GET['sc'];
$query = "UPDATE PlayerCards SET SelectedCards=$selected_cards WHERE ID=$id";
$response = #mysqli_query($dbc, $query);
if($response){
echo 'Updated the sc of the selected id';
} else {
echo 'could not execute database query 2';
}
?>
This way I can update any user's sc value using a browser. (BIG PROBLEM)
Here is my C# scripts for Unity that retrieves the facebook user's login ID that I will use in my database to store values:
FB_manager.cs: (script that contains data)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
public class FB_manager : MonoBehaviour {
private static FB_manager _instance;
public static FB_manager Instance
{
get {
if(_instance == null){
GameObject fbm = new GameObject("FBManager");
fbm.AddComponent<FB_manager>();
}
return _instance;
}
}
public bool IsLoggedIn {get; set;}
public string ProfileName {get; set;}
public Sprite ProfilePic {get; set;}
public string ProfileEmail {get; set;}
void Awake()
{
DontDestroyOnLoad(this.gameObject);
_instance = this;
}
public void InitFB(){
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init(InitCallback, OnHideUnity);
} else {
IsLoggedIn = FB.IsLoggedIn;
}
}
private void InitCallback()
{
if (FB.IsInitialized) {
Debug.Log("FB is logged in");
GetProfile();
FB.ActivateApp();
} else {
Debug.Log("FB not logged in");
}
IsLoggedIn = FB.IsLoggedIn;
}
private void OnHideUnity(bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
public void GetProfile(){
FB.API("/me?fields=first_name",HttpMethod.GET, DisplayUserName);
FB.API("/me/picture?type=square&height=128&&widht=128",HttpMethod.GET, DisplayProfilePic);
FB.API("/me?fields=email",HttpMethod.GET, DisplayUserEmail);
}
void DisplayUserName(IResult result){
if(result.Error == null){
ProfileName = "" + result.ResultDictionary["first_name"];
} else {
Debug.Log(result.Error);
}
}
void DisplayUserEmail(IResult result){
if(result.Error == null){
Debug.Log(result);
ProfileEmail = "" + result.ResultDictionary["id"];
} else {
Debug.Log(result.Error);
}
}
void DisplayProfilePic(IGraphResult result){
if(result.Texture != null){
ProfilePic = Sprite.Create(result.Texture, new Rect(0,0,128,128), new Vector2());
} else {
Debug.Log(result.Error);
}
}
}
FB_script.cs: (script that contains data)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using Facebook.Unity;
public class FB_script : MonoBehaviour {
public GameObject DialogLoggedIn;
public GameObject DialogLoggedOut;
public GameObject logInStatusLabel;
public GameObject Name;
public GameObject ProfilePic;
void Awake()
{
FB_manager.Instance.InitFB();
HandleMenu(FB.IsLoggedIn);
}
public void FBLogin() {
var perms = new List<string>() { "public_profile", "email", "user_friends", "publish_actions"};
FB.LogInWithReadPermissions(perms, AuthCallback);
}
private void AuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn) {
HandleMenu(FB.IsLoggedIn);
Debug.Log("User logged in");
FB_manager.Instance.IsLoggedIn = true;
FB_manager.Instance.GetProfile();
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log(perm);
}
} else{
Debug.Log("User cancelled login");
}
HandleMenu(FB.IsLoggedIn);
}
void HandleMenu(bool isLoggedIn) {
if (isLoggedIn) {
DialogLoggedIn.SetActive(true);
DialogLoggedOut.SetActive(false);
logInStatusLabel.GetComponent<Text>().text = "Logged in as: ";
if(FB_manager.Instance.ProfileName!=null){
Text userName = Name.GetComponent<Text>();
userName.text = "" + FB_manager.Instance.ProfileName;
} else {
StartCoroutine("WaitForProfileName");
}
if(FB_manager.Instance.ProfilePic!=null){
Image image = ProfilePic.GetComponent<Image>();
image.sprite = FB_manager.Instance.ProfilePic;
} else {
StartCoroutine("WaitForProfilePic");
}
if(FB_manager.Instance.ProfileEmail!=null){
Text userName = Name.GetComponent<Text>();
userName.text = "" + FB_manager.Instance.ProfileEmail;
} else {
StartCoroutine("WaitForProfileEmail");
}
} else {
DialogLoggedIn.SetActive(false);
DialogLoggedOut.SetActive(true);
logInStatusLabel.GetComponent<Text>().text = "Not logged in";
}
}
IEnumerator WaitForProfileName(){
while(FB_manager.Instance.ProfileName==null){
yield return null;
}
HandleMenu(FB.IsLoggedIn);
}
IEnumerator WaitForProfilePic(){
while(FB_manager.Instance.ProfilePic==null){
yield return null;
}
HandleMenu(FB.IsLoggedIn);
}
IEnumerator WaitForProfileEmail(){
while(FB_manager.Instance.ProfileEmail==null){
yield return null;
}
HandleMenu(FB.IsLoggedIn);
}
}
I can connect to the database within Unity so that it access the database in order to update the table. Giving only update privileges when connecting within unity. The id and sc can then be enclosed by a script (embedding php into the script) to update the table. Will users be able to change the id inside the script? When deploying the game will user be able to edit scripts?
When a user logs in with Facebook credentials, then set their id in a session variable. Use the session variable in your sql query so that only the user can update their cards.

Categories