How to get path of isolated storage in silverlight? - silverlight

I read a similar post here... I tried implementing it but getting an exception saying
Attempt by method 'get_path_isolated.Page.button1_Click(System.Object, System.Windows.RoutedEventArgs)' to access field 'System.IO.IsolatedStorage.IsolatedStorageFileStream.m_FullPath' failed.
I have this code
public void button1_Click(object sender, RoutedEventArgs e)
{
isoStore = IsolatedStorageFile.GetUserStoreForApplication();
isoStore.CreateDirectory("root_dir");
IsolatedStorageFileStream iostream = new IsolatedStorageFileStream("sampleFile.txt", FileMode.Create, isoStore);
StreamWriter writer = new StreamWriter(iostream);
writer.Write("jaimokar");
try
{
FieldInfo pi = iostream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic);
string path = pi.GetValue(iostream).ToString();
}
catch (Exception ex)
{
textBox1.Text += ex.Message;
}
where I'm going wrong? Please help me..

For those that have Elevated Permissions (especially in browser) I have come up with a semi-functional solution to determine the path. Unfortunately, if you switch from dev to live you will see a different folder path, so you have to include it here, also you should add a check for which version you are running (dev or live) via a passed in page parameter or the host url or so
private string GetProfilePath() {
var fullname = string.Empty;
try
{
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
var profilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
profilePath = Path.GetDirectoryName(profilePath);
profilePath = Path.Combine(profilePath, #"LocalLow\Microsoft\Silverlight\is");
//profilePath = Path.Combine(profilePath, IsoPathStaging + "\\");
var directoryInfo = new DirectoryInfo(profilePath); // C:\Users\<username>\AppData\LocalLow\Microsoft\Silverlight\is --constant
var dirs = directoryInfo.EnumerateDirectories();
// ReSharper disable PossibleMultipleEnumeration
fullname = "1: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \ir5ffeej.4of --random
fullname = "2: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \lfab1wva.xmb --random
fullname = "3: " + dirs.First().FullName;
dirs = dirs.First().EnumerateDirectories(); // \1 --constant
fullname = "4: " + dirs.First().FullName;
dirs = dirs.Where(d => d.Name == "s"); // \s --constant
fullname = "5: " + dirs.First().FullName;
var dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "sbudlbc2oqx0eo0odi5nzpo2qppp3zmxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<dev dir> --constant-ish
if (!dirs2.Any())
{
dirs2 = dirs.First().EnumerateDirectories()
.Where(d => d.Name == "2gbsxl5no1wzqebnzbj2wglhi33za1rxxxxxxxxxxxxxxxxxxxxxxxxx").ToList(); // \<live dir> --constant-ish
}
if (!dirs2.Any())
{
throw new Exception("Unable to locate silverlight storage");
}
fullname = "6: " + dirs2.First().FullName;
dirs = dirs2.First().EnumerateDirectories().Where(d => d.Name == "f"); // \f --constant
fullname = "7: " + dirs.First().FullName;
var dir = dirs.First(); // final
fullname = dir.FullName;
// ReSharper restore CommentTypo
// ReSharper restore PossibleMultipleEnumeration
return fullname;
// ReSharper restore IdentifierTypo
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
return string.Empty;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullname
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
return string.Empty;
}
}
Again, you must have elevated rights for this to work, later I would use this path to locate a file for some other use:
var fullPath = Path.Combine(GetProfilePath(), FileName);
Run(fullPath.Replace("\\\\", "\\"));
private static void Run(string fullPath)
{
try
{
CheckElevatedPermissions();
var shell = AutomationFactory.CreateObject("WScript.Shell");
shell.Run("\"" + fullPath + "\"");
}
catch (NotSupportedException ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run (Not Supported):"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
CheckElevatedPermissions();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show(
"Failed to run:"
+ Environment.NewLine + fullPath
+ Environment.NewLine + ex.Message,
messageBoxTitle,
MessageBoxButton.OK);
}
}

Related

How to use SSIS to read from ActiveMQ Queue?

I'm a newbie to SSIS, my current workplace requires that we use SSIS to read from ActiveMQ (hosted service by Amazon) and populate certain SQLServer DB tables.
I've used NiFi to some extent in the past but not SSIS and SSIS 2016 doesn't have an ActiveMQ connectior
After googling around, learnt SSIS-ActiveMQ connection can be achieved using Script component of SSIS.
I can do bit of .net / C# scripting if need be, please advise if theres a template project out there or a how-to-guide to write the Script using NMS .net libraries. Many thanks
After few hours of reading through AMQ documentation, I could do this myself. Below is the complete code which currently works but obviously needs bit of TLC, all suggestions welcome.
using System;
using System.Text;
using System.Data.SqlClient;
using Apache.NMS;
using Serilog;
namespace AMQ_ConsoleApp
{
class Program
{
private const string AMQ_URI = "activemq:ssl://abc.net";
private const string AMQ_Queue = "test";
private const string AMQ_User = "userId";
private const string AMQ_Pwd = "password";
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
)
.WriteTo.File("AMQ_SSIS_Connector.log"
, rollingInterval: RollingInterval.Day
, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
, retainedFileCountLimit:30
)
.CreateLogger();
try
{ Log.Information("#### BEGIN #####");
IConnectionFactory factory = new NMSConnectionFactory(new Uri(AMQ_URI));
IConnection Q_connection = factory.CreateConnection(AMQ_User, AMQ_Pwd);
ISession Q_session = Q_connection.CreateSession();
Log.Debug("Attempting to connect to Queue {Queue}", AMQ_Queue);
Q_connection.Start();
IDestination destination = Q_session.GetQueue(AMQ_Queue);
IMessageConsumer consumer = Q_session.CreateConsumer(destination);
IMessage message;
while (true)
{
Log.Information("______________________________");
Log.Information("Awaiting new message...");
message = consumer.Receive();
if (message != null)
{
ITextMessage textMessage = message as ITextMessage;
if (!string.IsNullOrEmpty(textMessage.Text))
{
Log.Information("Reading message with ID : " + textMessage.NMSMessageId);
WriteToDB(textMessage);
}
}
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
throw;
}
//ShutDown(Q_session, Q_connection);
}
public static void WriteToDB(ITextMessage msg)
{
try
{
const string SQL_Datasource = "(localdb)\\LocalDBv14";
const string SQL_InitialCatalog = "Customer";
const string SQL_User = "";
const string SQL_User_Pwd = "";
const string SQL_TargetTable = "TableA";
const string SQL_Schema = "dbo";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = SQL_Datasource;
builder.InitialCatalog = SQL_InitialCatalog;
builder.IntegratedSecurity = true; // Disable for Named SQLServer A/c
StringBuilder sb_SQL = new StringBuilder();
sb_SQL.Append("INSERT INTO ");
sb_SQL.Append("[");
sb_SQL.Append(SQL_Schema);//
sb_SQL.Append("].[");
sb_SQL.Append(SQL_TargetTable);//
sb_SQL.Append("] (");
sb_SQL.Append("[" + "MessageID" + "]");//Fields
sb_SQL.Append(",[" + "Message" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_URI" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Queue" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Type" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Timestamp" + "]");//Fields
sb_SQL.Append(",[" + "RECORD_INSERTED_AT" + "]");//Fields
sb_SQL.Append(",[" + "RECORD_INSERTED_BY" + "]");//Fields
sb_SQL.Append(") VALUES (");
sb_SQL.Append("'" + msg.NMSMessageId + "'");//Data
sb_SQL.Append(",'" + msg.Text + "'");//Data
sb_SQL.Append(",'" + AMQ_URI + "'");//Data
sb_SQL.Append(",'" + msg.NMSDestination.ToString() + "'");//Data
sb_SQL.Append(",'" + msg.NMSType + "'");//Data
sb_SQL.Append("," + msg.NMSTimestamp );//Data
sb_SQL.Append("," + "getdate()" + "");//Data
sb_SQL.Append(",'" + "SSIS_User" + "'");//Data
sb_SQL.Append(")");
// Connect to SQL
Log.Information("Connecting to SQL Server...{Server}", SQL_Datasource);
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
int ret_rows = 0;
Log.Information("Opening DB Connection...{Connection}", SQL_Datasource+"."+SQL_InitialCatalog+"."+SQL_Schema);
connection.Open();
Log.Information("Inserting data into...{Table}", SQL_TargetTable);
using (SqlCommand command = new SqlCommand(sb_SQL.ToString(), connection))
ret_rows = command.ExecuteNonQuery();
if (ret_rows > 0)
{
Log.Information("Data committed to DB successfully, Inserted {records} records." , ret_rows);
//DequeueMessage(msg);
}
else {
Log.Fatal("Data commit to DB Failed.");
}
Log.Information("Closing DB connection...");
connection.Close();
Log.Information("DB Connection closed.");
}
}
catch (SqlException e)
{
Log.Error(e.ToString());
}
}
private static void DequeueMessage(IMessage message)
{
try
{
message.Acknowledge();
Log.Information("Message with ID {msg} de-queued from AMQ.", message.NMSMessageId);
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
private static void ShutDown(ISession session, IConnection connection)
{
Log.Information("Ending AMQ Session");
session.Close();
Log.Information("Closing AMQ Connection");
connection.Close();
}
}
}

use viewmodel property in model and notify the same property changed in model to viewmodel to bind to view

SingleMessage.xaml has viewmodel as SingleMessageViewModel.cs and this viewmodel uses LogAcitvity class as property and the property defined in the viewmodel is bind to the SingleMessage.xaml.
Now I want to use this(viewmodel) property in SocketClient.cs(Model) and want to notify the property change in the viewmodel to update the view.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
LogActivity class whose property is used in the viewmodel
public class LogActivity : ViewModelBase
{
private string messageLog;
public string MessageLog
{
get { return messageLog; }
set
{
if (value != messageLog)
{
messageLog = value;
NotifyPropertyChanged("MessageLog");
}
}
}
}
This is my viewmodel class
public class SingleMessageViewModel : ViewModelBase
{
private LogActivity messagelog;
public SingleMessageViewModel()
{
messagelog = new LogActivity();
}
public LogActivity MessageLog
{
get { return messagelog; }
set
{
if (value != messagelog)
{
messagelog = value;
NotifyPropertyChanged("MessageLog");
}
}
}
}
this is my view
<TextBox x:Name="TxtLog" Text="{Binding MessageLog.MessageLog, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Visible" />
Now I want to use this MessageLog property in the viewmodel in my SocketClient.cs model class and want to notify its change to viewmodel.
So that update happens to view. And also this propety is changed in the asynchorous method call so I want to use the this syntaxt to update the viewmodel property :
public class SocketClient : INotifyPropertyChanged
{
App.Current.Dispatcher.BeginInvoke((Action)delegate
{
MessageLog.MessageLog += messageTimeStamp + " : <- " + szData.Replace("\n\0", "") + "\n";
});
}
So, how to use the viewmodel propety this in the model and notify it to the viewmodel
public LogActivity MessageLog
{
get { return messagelog; }
set
{
if (value != messagelog)
{
messagelog = value;
NotifyPropertyChanged("MessageLog");
}
}
}
My model looks like this..
namespace PCSTESTGUI.Models
{
public class SocketClient : INotifyPropertyChanged
{
// Receive buffer.
byte[] dataBuffer = new byte[256];
IAsyncResult result;
public AsyncCallback pfnCallBack;
public Socket clientSocket;
private LogActivity messagelog;
//private SingleMessageViewModel SingleMVM;
int portNo;
string ipAddress;
string filePathName;
string receivedResponse;
string message = string.Empty;
string connstring = ConfigurationManager.AppSettings["XmlConfigurationSetting"].ToString();
string fileName = ConfigurationManager.AppSettings["XmlConfiguratonSettingFileName"].ToString();
string messageTimeStamp = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString();
public SocketClient()
{
messagelog = new LogActivity();
SingleMessageViewModel SingleMVM = new SingleMessageViewModel(this);
//get the IPAddress and PortNo from save configuration setting
filePathName = connstring + "\\" + fileName;
try
{
if (File.Exists(filePathName))
{
XDocument xdoc = XDocument.Load(filePathName);
var configsetting = from cs in xdoc.Descendants("ConfigurationSetting")
select cs;
foreach (var config in configsetting)
{
ipAddress = config.Element("IPAddress").Value;
portNo = Convert.ToInt16(config.Element("PortNo").Value);
}
// check ipaddress and port no exists
if (ipAddress == "" || portNo == 0)
{
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n", "Socket Connection : Missing", MessageBoxButton.OK, MessageBoxImage.Error);
FileLogger.Handle("Missing IP Address / Port Number in the configuration settings file");
MessageLog.MessageLog += messageTimeStamp + " : Missing IP Address / Port Number in the configuration settings file\n";
return;
}
//connect to the server
ConnectServer();
}
}
catch (Exception ex)
{
FileLogger.Handle(ex.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + ex.Message + "\n";
}
}
public SingleMessageViewModel SingleMVM
{
get;
set;
}
public LogActivity MessageLog
{
get
{
return messagelog;
}
set
{
messagelog = value;
this.SingleMVM.MessageLog = value;
NotifyPropertyChanged("MessageLog");
}
}
public void ConnectServer()
{
try
{
// Get the remote IP address
IPAddress ip = IPAddress.Parse(ipAddress);
int iPortNo = portNo;
// Create the socket instance
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
FileLogger.Handle("StartConnect - Trying socket connection to PCS server '" + ip.ToString() + "' on Port " + iPortNo.ToString());
MessageLog.MessageLog += messageTimeStamp + " : StartConnect - Trying socket connection to PCS server '" + ip.ToString() + "' on Port " + iPortNo.ToString() + "\n";
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// Connect to the remote host
clientSocket.Connect(ipEnd);
if (clientSocket.Connected)
{
FileLogger.Handle("ProcessConnect - Client socket connected to PCS server '" + ip.ToString() + "' on Port " + iPortNo.ToString());
MessageLog.MessageLog += messageTimeStamp + " : ProcessConnect - Client socket connected to PCS server '" + ip.ToString() + "' on Port " + iPortNo.ToString() + "\n";
//Wait for data asynchronously
WaitForData();
}
else
{
ConnectServer();
}
}
catch (SocketException ex)
{
FileLogger.Handle(ex.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + ex.Message + "\n";
}
}
public void SendMessage(string message)
{
try
{
if (!clientSocket.Connected)
ConnectServer();
if (message != "")
{
this.message = message + "\r\n";
byte[] byteMessage = Encoding.ASCII.GetBytes(this.message);
//NetworkStream networkStream = new NetworkStream(clientSocket);
//StreamWriter streamWriter = new StreamWriter(networkStream);
//streamWriter.WriteLine(byteMessage);
//streamWriter.Flush();
if (clientSocket != null && clientSocket.Connected)
{
FileLogger.Handle("Pseudo Command message processing tasks started");
FileLogger.Handle(" -> " + message.ToUpper());
MessageLog.MessageLog += messageTimeStamp + " : Pseudo Command message processing tasks started\n";
MessageLog.MessageLog += messageTimeStamp + " : -> " + message.ToUpper() + "\n";
clientSocket.Send(byteMessage);
}
else
{
ConnectServer();
if (clientSocket.Connected)
{
FileLogger.Handle("Pseudo Command message processing tasks started");
FileLogger.Handle(" -> " + message.ToUpper());
MessageLog.MessageLog += messageTimeStamp + " : Pseudo Command message processing tasks started\n";
MessageLog.MessageLog += messageTimeStamp + " : -> " + message.ToUpper() + "\n";
clientSocket.Send(byteMessage);
}
}
}
}
catch (Exception ex)
{
FileLogger.Handle(ex.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + ex.Message + "\n";
}
}
public void DissconnectServer()
{
clientSocket.Close();
clientSocket = null;
FileLogger.Handle("CloseConnection - Closed socket connection to PCS server '" + ipAddress + "' on Port " + portNo.ToString());
MessageLog.MessageLog += messageTimeStamp + " : ProcessConnect - Client socket connected to PCS server '" + ipAddress + "' on Port " + portNo.ToString() + "\n";
}
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
public void WaitForData()
{
try
{
if (pfnCallBack == null)
{
pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.thisSocket = clientSocket;
// Start listening to the data asynchronously
result = clientSocket.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length,
SocketFlags.None, pfnCallBack, theSocPkt);
if (result.IsCompleted == false)
{
Console.Write(".");
}
}
catch (SocketException se)
{
FileLogger.Handle(se.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + se.Message + "\n";
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
receivedResponse = receivedResponse + szData + "\n";
if (szData.ToString() != "\0" || szData.ToString() != "")
{
FileLogger.Handle(" <- " + szData.Replace("\n\0", ""));
App.Current.Dispatcher.BeginInvoke((Action)delegate
{
MessageLog.MessageLog += messageTimeStamp + " : <- " + szData.Replace("\n\0", "") + "\n";
if (SingleMVM == null)
SingleMVM = new SingleMessageViewModel(this);
//this.SingleMVM.MessageLog.MessageLog += this.MessageLog.MessageLog;
this.SingleMVM.updateMesssage(szData.Replace("\n\0", ""));
});
}
WaitForData();
}
catch (ObjectDisposedException ex)
{
FileLogger.Handle(ex.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + ex.Message + "\n";
}
catch (SocketException se)
{
FileLogger.Handle(se.Message);
MessageLog.MessageLog += messageTimeStamp + " : " + se.Message + "\n";
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
In the OnDataReceived funtion the data is received from the server and that need to be updated to view via viewmodel property MessageLog.
The INofication is not raising the event as PropertyChanged is null.
But I am asingning the value to the value.
In the viewmodel reading this value like this and it is also notify the propert call, but property changed is null so the event isnot raised.
public void updateMesssage(string message)
{
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new Action(() =>
{
this.MessageLog.MessageLog += messageTimeStamp + " : <- " + message + "\n";
}));
}

android database sqlite rawquery, no content

I have an Activity called Wartung. In this Activity are textfields which should be auto filled by database content. Writing to the DB table works but reading from it doesn't.
I didn't get any errors or warnings in LogCat.
In the method Wartung.getWartungsDaten(String serienNr) I call the method of the helper class DBController.getLetzterWartungsDaten(String serienNr). The last one does a rawquery to the DB.
To test which parts of the code are executed, ich make a toast("1") which is showed, also toast("2") , but toast("3") isn't. The problem must be in the line "Cursor wartungsCursor = this.dbHelper.getLetzteWartungsDaten(serienNr);" or in the helper class respectively in the method getLetzteWartungsDaten().
Here is my class Wartung:
public class Wartung extends Activity {
private DBController dbHelper;
private SQLiteDatabase db;
private EditText serienNr;
private EditText datum;
private EditText zeit;
private EditText benutzer;
private EditText beschreibung;
private EditText statusAktuell;
private Spinner statusNeu;
private Button buttonAendern;
private LinearLayout layoutStatusAktuell;
private LinearLayout layoutStatusNeu;
private String sSerienNr;
private String sArtikelId;
private String sDatum;
private String sZeit;
private String sBenutzer;
private String sStatus;
private String sBeschreibung;
private List<String> statusListe;
private List<String> listeWartungSerienNr;
private List<String> listeWartungDatum;
private List<String> listeWartungZeit;
private List<String> listeWartungBenutzer;
private List<String> listeWartungStatus;
private List<String> listeWartungBeschreibung;
private boolean editModus = false;
private boolean gespeichert = false;
private int statusPosition = -1;
/**
* Initialisierung aller Objekte
*
*/
private void initObjekte() {
this.serienNr = (EditText) this.findViewById(R.id.editText_wartung_content_serienNr);
this.datum = (EditText) this.findViewById(R.id.editText_wartung_content_datum);
this.zeit = (EditText) this.findViewById(R.id.editText_wartung_content_zeit);
this.benutzer = (EditText) this.findViewById(R.id.editText_wartung_content_benutzer);
this.statusAktuell = (EditText) this.findViewById(R.id.editText_wartung_content_aktueller_status);
this.statusNeu = (Spinner) this.findViewById(R.id.spinner_wartung_content_neuer_status);
this.layoutStatusAktuell = (LinearLayout) this.findViewById(R.id.linearLayoutStatusAktuell);
this.layoutStatusNeu = (LinearLayout) this.findViewById(R.id.linearLayoutStatusNeu);
this.listeWartungSerienNr = new ArrayList<String>();
this.listeWartungDatum = new ArrayList<String>();
this.listeWartungZeit = new ArrayList<String>();
this.listeWartungBenutzer = new ArrayList<String>();
this.listeWartungStatus = new ArrayList<String>();
this.listeWartungBeschreibung = new ArrayList<String>();
this.sArtikelId = new String();
this.sDatum = new String();
this.sZeit = new String();
this.sBenutzer = new String();
this.sStatus = new String();
this.sBeschreibung = new String();
this.statusListe = new ArrayList<String>();
setStatusInSpinner();
this.beschreibung = (EditText) this.findViewById(R.id.editTextMultiLine_wartung_content_aenderung);
}
public void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
/**
*
* #param serienNr
*/
private void getWartungsDaten(String serienNr) {
this.dbHelper = new DBController(this);
this.db = this.dbHelper.getReadableDatabase();
toast("1");
// Cursor auswerten
try {
toast("2");
Cursor wartungsCursor = dbHelper.getLetzteWartungsDaten(serienNr);
toast("3");
// Daten zerlegen
if (wartungsCursor != null) {
if (wartungsCursor.moveToFirst()) {
do {
this.listeWartungDatum.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_DATUM)));
this.listeWartungZeit.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_ZEIT)));
} while (wartungsCursor.moveToNext());
}
}
// String result = "result: " + this.sSerienNr + " " + this.sDatum + " " + this.sZeit + " " + this.sBenutzer + " " + this.sStatus + " " + this.sBeschreibung;
String result = "result: " + this.listeWartungDatum.get(0).toString() + " " + this.listeWartungZeit.get(0).toString();
toast("Erhaltene Daten: " + result);
} catch (Exception e) {
;
} finally {
this.db.close();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_wartung);
this.setupActionBar();
initObjekte();
setObjekteReadable();
// Zu Testzwecken wird immer der erste Artikel aus der Datenbank ausgewählt
getWartungsDaten("SerienNr 0000");
}
}
And here is my Helper class DBController:
public Cursor getLetzteWartungsDaten(String serienNr) {
this.db = this.getReadableDatabase();
// Filter-String um die anhängenden Daten über die SerienNr zu bekommen
String serienNrFilter = "SELECT " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_DATUM + ", " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_ZEIT + ", " +
"FROM " + DBController.TABLE_WARTUNG
"ORDER BY " + DBController.KEY_DATUM + " DESC," + DBController.KEY_ZEIT + " DESC" + ")";
return db.rawQuery(serienNrFilter, /*new String[] { serienNr }*/null);
}
I have some other methods with reading methods but only this one doesn't work and I don't know why.
I hope you can help me.
Thanks!
You have an unnecessary comma:
DBController.KEY_ZEIT + ", " +
"FROM "
i.e. syntax error.

RowLeave Event - Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function

I have DataGridView Control in windows application.
I load data and bind it to grid using above code.
private void LoadData()
{
clsData objData = new clsData();
DataTable dtTemp = new System.Data.DataTable();
dtTemp = objData.GetDatatable(" SELECT [ID],[CustomerName],[OrderQty],[Price],[POStatus],[Remarks],[EstdShipDate],[ActualShipDate],[IsShipped] FROM [tblPO] ");
dgPO.DataSource = null;
dgPO.DataSource = dtTemp;
}
where dgPO is DataGrdiView(DGV).
Now i want to update records in DGV when user leaves the row.
for it i have used RowLeave event of DGV.code is here
private void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
int POId = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[0].Value) == "" ? 0 : Convert.ToInt32(dgPO.Rows[e.RowIndex].Cells[0].Value);
string CustName = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[1].Value);
int Qty = Convert.ToInt32(dgPO.Rows[e.RowIndex].Cells[2].Value);
decimal Price = Convert.ToDecimal(dgPO.Rows[e.RowIndex].Cells[3].Value);
string Status = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[4].Value);
string Remarks = Convert.ToString(dgPO.Rows[e.RowIndex].Cells[5].Value);
string dtEsdt = Convert.ToDateTime(dgPO.Rows[e.RowIndex].Cells[6].Value).ToString("yyyy-MM-dd");
string dtActl = Convert.ToDateTime(dgPO.Rows[e.RowIndex].Cells[7].Value).ToString("yyyy-MM-dd");
bool Shipped = dgPO.Rows[e.RowIndex].Cells[8].Value == DBNull.Value ? false : Convert.ToBoolean(dgPO.Rows[e.RowIndex].Cells[8].Value);
string strQry = "";
if (POId > 0)
{
strQry = " UPDATE [tblPO] SET [CustomerName] = '" + PreString(CustName) + "',[OrderQty] = " + Qty + ",[Price] = " + Price + ",[POStatus] = '" + Status + "'";
strQry = strQry + ",[Remarks] = '" + PreString(Remarks) + "',[EstdShipDate] = '" + dtEsdt + "',[ActualShipDate] = '" + dtActl + "',[IsShipped] = '" + Shipped + "'";
strQry = strQry + " WHERE ID =" + POId;
}
else
{
strQry = " INSERT INTO [tblPO] ([CustomerName],[OrderQty],[Price],[POStatus],[Remarks],[EstdShipDate],[ActualShipDate],[IsShipped]) ";
strQry += " VALUES('" + PreString(CustName) + "'," + Qty + "," + Price + ",'" + PreString(Status) + "','" + PreString(Remarks) + "'";
strQry += " ,'" + PreString(dtEsdt) + "','" + PreString(dtActl) + "','" + Shipped + "')";
}
clsData objData = new clsData();
if (objData.ExecuteQuery(strQry))
{
LoadData();
}
}
When data is updated in DB, I refresh the DGV by calling LoadData method.
At this point, i get an error message like this.
"Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function"
I tried for available solution on SO and MSDN blogs,but they don't work for me
like these
1) http://social.msdn.microsoft.com/Forums/en/winformsdatacontrols/thread/f824fbbf-9d08-4191-98d6-14903801acfc
2) Click on any other cell while a cell of same row of datagridvew is in edit mode causes Operation is not valid reentrant call
3) InvalidOperationException - When ending editing a cell & moving to another cell
Help needed.
Thanks in advance !!
Answer:
private void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.EndEdit();
//You code below
}
Suggestion: The alternative way
Did you try to use .RowValidating Event and .IsCurrentRowDirty Method?
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
//Your code here
}
}
use the following check before applying your edit in the "RowLeave" or "EndEdit" method:
public void dgPO_RowLeave(object sender, DataGridViewCellEventArgs e)
{
if (!dgPO.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected)
return;
//...rest of your code to apply edit below...
}
This should work with any cell being edited.(the edit-code is not applied when losing focus; Typing Enter would suffice to apply the edit)

Special symbols in subject of emails

We are currently working on a defect to allow special symbols also to be seen in email subject. The email is text/html mime type.
Currently, if the subject should have a heart symbol it is shown as "&heart" but in the email body a "heart" symbol is shown.
Can someone help us with the solution to have special symbols also part of subject?
Here is the code snippet.
public boolean send(String to, String from, String subject, String templatePath, Map map) {
// create a mime message using the mail sender implementation
MimeMessage mimeMessage = mailSender.createMimeMessage();
// create the message using the specified template
MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setFrom(from);
String text = VelocityEngineUtils.mergeTemplateIntoString(engine, templatePath, map);
helper.setText(text, true);
send(mimeMessage);
log.debug("in send at start" + this.getClass().getName()
+ ":SUCCESS: Sendig mail to" + to + " from " + from + " subject "
+ subject);
} catch (MessagingException e)
{
throw new MailPreparationException("unable to create the mime message helper", e);
} catch (Exception e)
{
log.debug("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ to + " from " + from + " subject " + subject);
// throw new
// MailPreparationException("unable to create the mime message helper",
// e);
}
return false;
}
public boolean send(MimeMessage mimeMessage) throws Exception {
try
{
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
multipart.addBodyPart(bodyPart);
bodyPart.setContent(mimeMessage.getContent(), "text/html");
mimeMessage.setContent(multipart);
mailSender.send(mimeMessage);
} catch (Exception e)
{
log.error("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ e.getMessage());
// e.printStackTrace();
throw e;
// return false;
}
return true;
}
public static String HTMLDecode(String encodedHTML) {
return encodedHTML.replaceAll("¡", "\u00A1")
.replaceAll("¢", "\u00A2")
.replaceAll("£", "\u00A3")
.replaceAll("¤", "\u00A4")
.replaceAll("¥", "\u00A5")
.replaceAll("¦", "\u00A6")
.replaceAll("§", "\u00A7")
.replaceAll("¨", "\u00A8")
........
You can send as Unicode / UTF-8.

Resources