C# SessionState custom. Session never expires - session

I have a problem with an MVC3 application and MySQL persistent DB session.
The problem is that session never expires.
ResetItemTimeout method is callign before GetItemExclusive
GetItemExclusive method checks if expire field is less than now.
This never occurs due to this method update the expire date adding the minutes specified on the web.config.
My web.config is:
For Session state:
<sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom" customProvider="MySqlSessionProvider" timeout="20">
<providers>
<add name="MySqlSessionProvider" type="Zasy.SQLSessionState.Session.MySqlSessionStateStore" connectionStringName="MySqlConnection" writeExceptionsToEventLog="true"/>
</providers>
For form authorization:
<authentication mode="Forms">
<forms loginUrl="~/Home/?error=authentication" timeout="20" />
The problem is that session never expires. I'm using the following code (with the only modiffication that I'm using a MySql conecction) from the following page (http://msdn.microsoft.com/en-us/library/ms178589%28v=vs.80%29.aspx)
using System;
using System.Web;
using System.Web.Configuration;
using System.Configuration;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Web.SessionState;
using System.Data;
using System.Data.Odbc;
using System.Diagnostics;
using System.IO;
/*
This session state store provider supports the following schema:
CREATE TABLE Sessions
(
SessionId Text(80) NOT NULL,
ApplicationName Text(255) NOT NULL,
Created DateTime NOT NULL,
Expires DateTime NOT NULL,
LockDate DateTime NOT NULL,
LockId Integer NOT NULL,
Timeout Integer NOT NULL,
Locked YesNo NOT NULL,
SessionItems Memo,
Flags Integer NOT NULL,
CONSTRAINT PKSessions PRIMARY KEY (SessionId, ApplicationName)
)
This session state store provider does not automatically clean up
expired session item data. It is recommended
that you periodically delete expired session information from the
data store with the following code (where 'conn' is the OdbcConnection
for the session state store provider):
string commandString = "DELETE FROM Sessions WHERE Expires < ?";
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand(commandString, conn);
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value = DateTime.Now;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
*/
namespace Samples.AspNet.Session
{
public sealed class OdbcSessionStateStore : SessionStateStoreProviderBase
{
private SessionStateSection pConfig = null;
private string connectionString;
private ConnectionStringSettings pConnectionStringSettings;
private string eventSource = "OdbcSessionStateStore";
private string eventLog = "Application";
private string exceptionMessage =
"An exception occurred. Please contact your administrator.";
private string pApplicationName;
//
// If false, exceptions are thrown to the caller. If true,
// exceptions are written to the event log.
//
private bool pWriteExceptionsToEventLog = false;
public bool WriteExceptionsToEventLog
{
get { return pWriteExceptionsToEventLog; }
set { pWriteExceptionsToEventLog = value; }
}
//
// The ApplicationName property is used to differentiate sessions
// in the data source by application.
//
public string ApplicationName
{
get { return pApplicationName; }
}
public override void Initialize(string name, NameValueCollection config)
{
//
// Initialize values from web.config.
//
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "OdbcSessionStateStore";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "Sample ODBC Session State Store provider");
}
// Initialize the abstract base class.
base.Initialize(name, config);
//
// Initialize the ApplicationName property.
//
pApplicationName =
System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
//
// Get <sessionState> configuration element.
//
Configuration cfg =
WebConfigurationManager.OpenWebConfiguration(ApplicationName);
pConfig =
(SessionStateSection)cfg.GetSection("system.web/sessionState");
//
// Initialize connection string.
//
pConnectionStringSettings =
ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
if (pConnectionStringSettings == null ||
pConnectionStringSettings.ConnectionString.Trim() == "")
{
throw new ProviderException("Connection string cannot be blank.");
}
connectionString = pConnectionStringSettings.ConnectionString;
//
// Initialize WriteExceptionsToEventLog
//
pWriteExceptionsToEventLog = false;
if (config["writeExceptionsToEventLog"] != null)
{
if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
pWriteExceptionsToEventLog = true;
}
}
//
// SessionStateStoreProviderBase members
//
public override void Dispose()
{
}
//
// SessionStateProviderBase.SetItemExpireCallback
//
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
return false;
}
//
// SessionStateProviderBase.SetAndReleaseItemExclusive
//
public override void SetAndReleaseItemExclusive(HttpContext context,
string id,
SessionStateStoreData item,
object lockId,
bool newItem)
{
// Serialize the SessionStateItemCollection as a string.
string sessItems = Serialize((SessionStateItemCollection)item.Items);
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd;
OdbcCommand deleteCmd = null;
if (newItem)
{
// OdbcCommand to clear an existing expired session if it exists.
deleteCmd = new OdbcCommand("DELETE FROM Sessions " +
"WHERE SessionId = ? AND ApplicationName = ? AND Expires < ?", conn);
deleteCmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
deleteCmd.Parameters.Add
("#ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
deleteCmd.Parameters.Add
("#Expires", OdbcType.DateTime).Value = DateTime.Now;
// OdbcCommand to insert the new session item.
cmd = new OdbcCommand("INSERT INTO Sessions " +
" (SessionId, ApplicationName, Created, Expires, " +
" LockDate, LockId, Timeout, Locked, SessionItems, Flags) " +
" Values(?, ?, ?, ?, ?, ? , ?, ?, ?, ?)", conn);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add
("#ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
cmd.Parameters.Add
("#Created", OdbcType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add
("#Expires", OdbcType.DateTime).Value = DateTime.Now.AddMinutes((Double)item.Timeout);
cmd.Parameters.Add
("#LockDate", OdbcType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = 0;
cmd.Parameters.Add
("#Timeout", OdbcType.Int).Value = item.Timeout;
cmd.Parameters.Add("#Locked", OdbcType.Bit).Value = false;
cmd.Parameters.Add
("#SessionItems", OdbcType.VarChar, sessItems.Length).Value = sessItems;
cmd.Parameters.Add("#Flags", OdbcType.Int).Value = 0;
}
else
{
// OdbcCommand to update the existing session item.
cmd = new OdbcCommand(
"UPDATE Sessions SET Expires = ?, SessionItems = ?, Locked = ? " +
" WHERE SessionId = ? AND ApplicationName = ? AND LockId = ?", conn);
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value =
DateTime.Now.AddMinutes((Double)item.Timeout);
cmd.Parameters.Add("#SessionItems",
OdbcType.VarChar, sessItems.Length).Value = sessItems;
cmd.Parameters.Add("#Locked", OdbcType.Bit).Value = false;
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = lockId;
}
try
{
conn.Open();
if (deleteCmd != null)
deleteCmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "SetAndReleaseItemExclusive");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
//
// SessionStateProviderBase.GetItem
//
public override SessionStateStoreData GetItem(HttpContext context,
string id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags)
{
return GetSessionStoreItem(false, context, id, out locked,
out lockAge, out lockId, out actionFlags);
}
//
// SessionStateProviderBase.GetItemExclusive
//
public override SessionStateStoreData GetItemExclusive(HttpContext context,
string id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags)
{
return GetSessionStoreItem(true, context, id, out locked,
out lockAge, out lockId, out actionFlags);
}
//
// GetSessionStoreItem is called by both the GetItem and
// GetItemExclusive methods. GetSessionStoreItem retrieves the
// session data from the data source. If the lockRecord parameter
// is true (in the case of GetItemExclusive), then GetSessionStoreItem
// locks the record and sets a new LockId and LockDate.
//
private SessionStateStoreData GetSessionStoreItem(bool lockRecord,
HttpContext context,
string id,
out bool locked,
out TimeSpan lockAge,
out object lockId,
out SessionStateActions actionFlags)
{
// Initial values for return value and out parameters.
SessionStateStoreData item = null;
lockAge = TimeSpan.Zero;
lockId = null;
locked = false;
actionFlags = 0;
// ODBC database connection.
OdbcConnection conn = new OdbcConnection(connectionString);
// OdbcCommand for database commands.
OdbcCommand cmd = null;
// DataReader to read database record.
OdbcDataReader reader = null;
// DateTime to check if current session item is expired.
DateTime expires;
// String to hold serialized SessionStateItemCollection.
string serializedItems = "";
// True if a record is found in the database.
bool foundRecord = false;
// True if the returned session item is expired and needs to be deleted.
bool deleteData = false;
// Timeout value from the data store.
int timeout = 0;
try
{
conn.Open();
// lockRecord is true when called from GetItemExclusive and
// false when called from GetItem.
// Obtain a lock if possible. Ignore the record if it is expired.
if (lockRecord)
{
cmd = new OdbcCommand(
"UPDATE Sessions SET" +
" Locked = ?, LockDate = ? " +
" WHERE SessionId = ? AND ApplicationName = ? AND Locked = ? AND Expires > ?", conn);
cmd.Parameters.Add("#Locked", OdbcType.Bit).Value = true;
cmd.Parameters.Add("#LockDate", OdbcType.DateTime).Value
= DateTime.Now;
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.Parameters.Add("#Locked", OdbcType.Int).Value = false;
cmd.Parameters.Add
("#Expires", OdbcType.DateTime).Value = DateTime.Now;
if (cmd.ExecuteNonQuery() == 0)
// No record was updated because the record was locked or not found.
locked = true;
else
// The record was updated.
locked = false;
}
// Retrieve the current session item information.
cmd = new OdbcCommand(
"SELECT Expires, SessionItems, LockId, LockDate, Flags, Timeout " +
" FROM Sessions " +
" WHERE SessionId = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
// Retrieve session item data from the data source.
reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (reader.Read())
{
expires = reader.GetDateTime(0);
/* ####################################################################################################
* ResetItemTimeout has already update the expires date to the new expires date, so expires never will be less than DateTime.now
* #####################################################################################################
*/
if (expires < DateTime.Now)
{
// The record was expired. Mark it as not locked.
locked = false;
// The session was expired. Mark the data for deletion.
deleteData = true;
}
else
foundRecord = true;
serializedItems = reader.GetString(1);
lockId = reader.GetInt32(2);
lockAge = DateTime.Now.Subtract(reader.GetDateTime(3));
actionFlags = (SessionStateActions)reader.GetInt32(4);
timeout = reader.GetInt32(5);
}
reader.Close();
// If the returned session item is expired,
// delete the record from the data source.
if (deleteData)
{
cmd = new OdbcCommand("DELETE FROM Sessions " +
"WHERE SessionId = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.ExecuteNonQuery();
}
// The record was not found. Ensure that locked is false.
if (!foundRecord)
locked = false;
// If the record was found and you obtained a lock, then set
// the lockId, clear the actionFlags,
// and create the SessionStateStoreItem to return.
if (foundRecord && !locked)
{
lockId = (int)lockId + 1;
cmd = new OdbcCommand("UPDATE Sessions SET" +
" LockId = ?, Flags = 0 " +
" WHERE SessionId = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = lockId;
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;
cmd.ExecuteNonQuery();
// If the actionFlags parameter is not InitializeItem,
// deserialize the stored SessionStateItemCollection.
if (actionFlags == SessionStateActions.InitializeItem)
item = CreateNewStoreData(context, pConfig.Timeout.Minutes);
else
item = Deserialize(context, serializedItems, timeout);
}
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "GetSessionStoreItem");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
if (reader != null) { reader.Close(); }
conn.Close();
}
return item;
}
//
// Serialize is called by the SetAndReleaseItemExclusive method to
// convert the SessionStateItemCollection into a Base64 string to
// be stored in an Access Memo field.
//
private string Serialize(SessionStateItemCollection items)
{
MemoryStream ms = new MemoryStream();
BinaryWriter writer = new BinaryWriter(ms);
if (items != null)
items.Serialize(writer);
writer.Close();
return Convert.ToBase64String(ms.ToArray());
}
//
// DeSerialize is called by the GetSessionStoreItem method to
// convert the Base64 string stored in the Access Memo field to a
// SessionStateItemCollection.
//
private SessionStateStoreData Deserialize(HttpContext context,
string serializedItems, int timeout)
{
MemoryStream ms =
new MemoryStream(Convert.FromBase64String(serializedItems));
SessionStateItemCollection sessionItems =
new SessionStateItemCollection();
if (ms.Length > 0)
{
BinaryReader reader = new BinaryReader(ms);
sessionItems = SessionStateItemCollection.Deserialize(reader);
}
return new SessionStateStoreData(sessionItems,
SessionStateUtility.GetSessionStaticObjects(context),
timeout);
}
//
// SessionStateProviderBase.ReleaseItemExclusive
//
public override void ReleaseItemExclusive(HttpContext context,
string id,
object lockId)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd =
new OdbcCommand("UPDATE Sessions SET Locked = 0, Expires = ? " +
"WHERE SessionId = ? AND ApplicationName = ? AND LockId = ?", conn);
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value =
DateTime.Now.AddMinutes(pConfig.Timeout.Minutes);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = lockId;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "ReleaseItemExclusive");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
//
// SessionStateProviderBase.RemoveItem
//
public override void RemoveItem(HttpContext context,
string id,
object lockId,
SessionStateStoreData item)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("DELETE * FROM Sessions " +
"WHERE SessionId = ? AND ApplicationName = ? AND LockId = ?", conn);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = lockId;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "RemoveItem");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
//
// SessionStateProviderBase.CreateUninitializedItem
//
public override void CreateUninitializedItem(HttpContext context,
string id,
int timeout)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd = new OdbcCommand("INSERT INTO Sessions " +
" (SessionId, ApplicationName, Created, Expires, " +
" LockDate, LockId, Timeout, Locked, SessionItems, Flags) " +
" Values(?, ?, ?, ?, ?, ? , ?, ?, ?, ?)", conn);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
cmd.Parameters.Add("#Created", OdbcType.DateTime).Value
= DateTime.Now;
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value
= DateTime.Now.AddMinutes((Double)timeout);
cmd.Parameters.Add("#LockDate", OdbcType.DateTime).Value
= DateTime.Now;
cmd.Parameters.Add("#LockId", OdbcType.Int).Value = 0;
cmd.Parameters.Add("#Timeout", OdbcType.Int).Value = timeout;
cmd.Parameters.Add("#Locked", OdbcType.Bit).Value = false;
cmd.Parameters.Add("#SessionItems", OdbcType.VarChar, 0).Value = "";
cmd.Parameters.Add("#Flags", OdbcType.Int).Value = 1;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "CreateUninitializedItem");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
//
// SessionStateProviderBase.CreateNewStoreData
//
public override SessionStateStoreData CreateNewStoreData(
HttpContext context,
int timeout)
{
return new SessionStateStoreData(new SessionStateItemCollection(),
SessionStateUtility.GetSessionStaticObjects(context),
timeout);
}
//
// SessionStateProviderBase.ResetItemTimeout
//
/* ####################################################################################################
* ResetItemTimeout is callign before GetItemExclusive
* GetItemExclusive checks if expire field is less than now.
* This never occurs due to this method update the expire date adding the minutes specified on the web.config.
* #####################################################################################################
*/
public override void ResetItemTimeout(HttpContext context,
string id)
{
OdbcConnection conn = new OdbcConnection(connectionString);
OdbcCommand cmd =
new OdbcCommand("UPDATE Sessions SET Expires = ? " +
"WHERE SessionId = ? AND ApplicationName = ?", conn);
cmd.Parameters.Add("#Expires", OdbcType.DateTime).Value
= DateTime.Now.AddMinutes(pConfig.Timeout.Minutes);
cmd.Parameters.Add("#SessionId", OdbcType.VarChar, 80).Value = id;
cmd.Parameters.Add("#ApplicationName", OdbcType.VarChar,
255).Value = ApplicationName;
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (OdbcException e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "ResetItemTimeout");
throw new ProviderException(exceptionMessage);
}
else
throw e;
}
finally
{
conn.Close();
}
}
//
// SessionStateProviderBase.InitializeRequest
//
public override void InitializeRequest(HttpContext context)
{
}
//
// SessionStateProviderBase.EndRequest
//
public override void EndRequest(HttpContext context)
{
}
//
// WriteToEventLog
// This is a helper function that writes exception detail to the
// event log. Exceptions are written to the event log as a security
// measure to ensure private database details are not returned to
// browser. If a method does not return a status or Boolean
// indicating the action succeeded or failed, the caller also
// throws a generic exception.
//
private void WriteToEventLog(Exception e, string action)
{
EventLog log = new EventLog();
log.Source = eventSource;
log.Log = eventLog;
string message =
"An exception occurred communicating with the data source.\n\n";
message += "Action: " + action + "\n\n";
message += "Exception: " + e.ToString();
log.WriteEntry(message);
}
}
}
Can someone help me?.
Thank you very much indeed for your answers.
Juan

On SQL SERVER you must have SQL Server agent runnig.
When you install ASPState the job "ASPState_Job_DeleteExpiredSessions" is installed, but if the Agent is dead the sessions wil be there forever.
If "OdbcSessionStateStore" is in the context of a webpage the session will be always refreshed before your code get on to Delete action.
So you are running on mysql must have some kind of agent to run this process.
Quartz is a good sheduler and you can implement quartz easy with a windows service and get the job done.
http://quartz-scheduler.org/

Related

how to set javafx Togglebutton in javafx Tableview to correct image based on boolean from sqlite database(JDBC)

I am working on a program that is going to allow users to select/add sounds as favorites
via a toggle button with an image in a javafx tableview tablecell and set the status of the sound in the database(the updating of the favorite status in the database works) however the updating of the image only partially works.
when pressing the toggle button the image updates correctly as does the database
initial loading
first 10 records before any favorite selection
after button is pressed
database
but the problem comes when I stop and restart the program because I wind up with none of the buttons selected (sound id 5 should be)
here is the code for the database data loading
public void getSounds() {
soundFilelist.removeAll(soundFilelist);
try {
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
// add where userId = VerifiedUserId or something simular//
String sql = "SELECT * FROM Sounds Where userId = ? ";
PreparedStatement ps;
ResultSet rs;
ps = conn.prepareStatement(sql);
ps.setInt(1 , User.getUserId());
rs = ps.executeQuery();
while (rs.next()) {
int favoriteStatus;
soundFilelist.add(new Sound(
rs.getInt("SoundId") ,
rs.getString("SoundName") ,
rs.getString("soundPath") ,
rs.getLong("soundDurration") ,
favoriteStatus = rs.getInt("Favorite")));
System.out.println(favoriteStatus);
if(favoriteStatus == 0){
setFavoritesTableButton(0);
}else if(favoriteStatus == 1){
setFavoritesTableButton(1);
}
}
soundBrowser.setItems(soundFilelist);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
the addButtoncell code
(favorite column 2) modified from https://riptutorial.com/javafx/example/27946/add-button-to-tableview
private void addButtonToTable() {
Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>> cellFactory = new Callback<TableColumn<Sound, Void>, TableCell<Sound, Void>>() {
#Override
public TableCell<Sound, Void> call(final TableColumn<Sound, Void> param) {
favoritecell = new TableCell<>() {
private final ToggleButton btn = new ToggleButton();
private Image favoritesImage = new Image("SoundSphere/RegularSizeFavoritesImage.png");
private Image favoriteslPressedImage = new Image("SoundSphere/RegularSizeFavoriteslPressedImage.png");
private ImageView tableViewFavorites = new ImageView();
{
tableViewFavorites.setFitWidth(20);
tableViewFavorites.setFitHeight(20);
btn.setAlignment(Pos.CENTER);
// favoritecell.setAlignment(Pos.CENTER);
btn.setGraphic(tableViewFavorites);
btn.setOnAction((new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
if ((btn.isSelected())) {
Sound sound = getTableView().getItems().get(getIndex());
sound.setSoundId(soundIdColumn.getCellData(sound));
System.out.println("selected SID: "+ sound.getSoundId());
int selectedSoundId2 = sound.getSoundId();
tableViewFavorites.setImage(favoriteslPressedImage);
tableviewFavoriteButtonIsPressed = false;
//addFavorite();
System.out.println("buttonselectedId"+ selectedSoundId);
addFavorite2(selectedSoundId2);
}else{
Sound sound = getTableView().getItems().get(getIndex());
sound.setSoundId(soundIdColumn.getCellData(sound));
int selectedSoundId2 = sound.getSoundId();
tableViewFavorites.setImage(favoritesImage);
tableviewFavoriteButtonIsPressed = true;
removeFavorite2(selectedSoundId2);
}
}
private void removeFavorite2(int selectedSoundId2) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
String sql = "UPDATE Sounds " +
"SET Favorite = ?"+
// "soundName = ?"+
"Where soundId = ? AND userId = ?";
PreparedStatement ps;
ps = conn.prepareStatement(sql);
ps.setInt(1,0);
ps.setInt(2 , selectedSoundId2);
ps.setInt(3 , User.getUserId());
ps.executeUpdate();
System.out.println("Data has been removed");
}catch(Exception e){
System.out.println("we have a problem with add favorite 2");
e.printStackTrace();
}
}
}));
}
private void addFavorite2(int favoriteSoundId) {
try{
Connection conn = DriverManager.getConnection("jdbc:sqlite:Sphere.db");
String sql = "UPDATE Sounds " +
"SET Favorite = ?"+
// "soundName = ?"+
"Where soundId = ? AND userId = ?";
PreparedStatement ps;
ps = conn.prepareStatement(sql);
ps.setInt(1,1);
ps.setInt(2 , favoriteSoundId);
System.out.println(favoriteSoundId);
ps.setInt(3 , User.getUserId());
ps.executeUpdate();
System.out.println("Data has been inserted");
}catch(Exception e){
System.out.println("we have a problem with add favorite 2");
e.printStackTrace();
}
}
#Override
public void updateItem(Void item , boolean empty) {
super.updateItem(item , empty);
if (btn.isSelected() || dbFavorite) {
tableViewFavorites.setImage(tableFavoriteslPressedImage);
setGraphic(btn);
} if (!btn.isSelected() || !dbFavorite) {
tableViewFavorites.setImage(favoritesImage);
setGraphic(btn);
}
}
};
return favoritecell;
}
};
favoritesColumn2.setCellFactory(cellFactory);
soundBrowser.getColumns().add(favoritesColumn2);
}
public boolean setFavoritesTableButton(int favoriteStatus){
if(favoriteStatus == 1) {
dbFavorite = true;
}else if(favoriteStatus == 0){
dbFavorite = false;
}
return dbFavorite;
}
relevant Intializable code
soundNameColumn.setCellValueFactory(new PropertyValueFactory<>("soundName"));
soundPathColumn.setCellValueFactory(new PropertyValueFactory<>("soundPath"));
soundDurationColumn.setCellValueFactory(new PropertyValueFactory<>("soundDurration"));
favoritesColumn.setCellValueFactory(new PropertyValueFactory<>("Favorite"));
addButtonToTable();
getSounds();
I have tried setting the state of the toggle button in the get sounds method and various Booleans but none of my attempts have worked.
thank you for your time and any help
Thomas Gustafson

Getting error while consuming Web API in Xamarin forms cross platform

Getting below error while consuming web API in Xamarin forms "Cannot convert from Login to System.Net.Http.HttpCompletionOption"
I'm new to mobile development ,please help me in completing the above code for consuming the API's in Xamarin cross platform.
Below is the code for WEB API
public class DBLoginController : ApiController
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_test"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpGet]
[ActionName("getCustomerInfo")]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_admin";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_admin";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
[HttpPost]
public int Login([System.Web.Http.FromBody] Login lgn)
{
int ret = 0;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from tbl_admin where username='"+lgn.username+"'username and password='"+ lgn.password + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
ret = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch
{
}
return ret;
}
}
Below is the code for consuming API in xamarin form
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://********.com/api/DBLogin/getCustomer");
Login lgn = new Login { username = txtUsername.Text.ToString(), password = txtPassword.Text.ToString() };
var response = client.GetAsync("api/Login/Login").Result;
var a = response.Content.ReadAsStringAsync();
if (a.Result.ToString().Trim() == "0")
{
messageLabel.Text = "Invalid login credentials.";
}
else
{
await Navigation.PushModalAsync(new Page2());
}
}
}
}
please help
Thanks in advance

SqlException was unhandled(incorrect syntax error)

When I try to enter login, the program is sending me throw section & writing something about incorrect synxtax error '='.
public bool personelEntryControl(string password, int UserId)
{
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ID=#Id and PAROLA=#password", con);
cmd.Parameters.Add("#Id", SqlDbType.VarChar).Value = UserId;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = Convert.ToBoolean(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
throw;
}
return result;
}
public void personelGetbyInformation(ComboBox cb)
{
cb.Items.Clear();
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ", con);
if (con.State == ConnectionState.Closed) ;
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cPersoneller p = new cPersoneller();
p._PersonelId = Convert.ToInt32(dr["ID"]);
p._PersonelGorevId = Convert.ToInt32(dr["GOREVID"]);
p._PersonelAd = Convert.ToString(dr["AD"]);
p._PersonelSoyad = Convert.ToString(dr["SOYAD"]);
p._PersonelParola = Convert.ToString(dr["PAROLA"]);
p._PersonelKullanıcıAdı = Convert.ToString(dr["KULLANICIADI"]);
p._PersonelDurum = Convert.ToBoolean(dr["DURUM"]);
cb.Items.Add(p);
}
dr.Close();
con.Close();
}
You appear to be trying to filter with your cmd SQLCommand. However, you left out the keyword WHERE, hence the incorrect syntax error. It should be something like:
SqlCommand cmd = new SqlCommand("Select * from Personeller WHERE ID=#Id and PAROLA=#password", con)

The specified string is not in the form required for an e-mail address.i am getting Emails from Database

this is method
#region StuDetailsMail
public List StuDetailsMail(string Stu_Name, string Stu_Email, string Stu_Mobile)
{
List data = new List();
SqlParameter[] sqlprm = new SqlParameter[3];
SqlDataReader dr = null;
try {
sqlprm[0] = new SqlParameter(DBProcedures.sqlparam_Name, Stu_Name);
sqlprm[1] = new SqlParameter(DBProcedures.sqlpram_Email, Stu_Email);
sqlprm[2] = new SqlParameter(DBProcedures.sqlpram_Mobile_Num, Stu_Mobile);
dr = objDAL.ExecuteReader(DBProcedures.Usp_StuEmail, ref sqlprm, false);
while (dr.Read())
{
InstEmails list1 = new InstEmails()
{
Emaillist = dr["email"].ToString(),
};
data.Add(list1);
};
foreach (var emailId in data)
{
string MessageBody = "studentname" + Stu_Name + " is Intersted" + "studentmail is" + Stu_Email;
string MailSubject = "this is from Traininghubs";
obj.SendEmailToInstitute(emailId.ToString(), MessageBody, MailSubject);
}
}
catch(Exception e)
{
}
return data;
}
#endregion

Adding reminder to event fails in Android

I have a method which adds an reminder to an event, but it fails:
FATAL EXCEPTION: main
android.database.sqlite.SQLiteException
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:184)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
at android.content.ContentResolver.insert(ContentResolver.java:864)
at de.appwege.droid.medwege.navigationdrawer.TerminFragment.insertReminder(TerminFragment.java:848)
The method in question:
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
What I am missing here? both eventID and minutes are defined...
Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Resources