I'm just a junior, and I'm taking care of a support project alone, and with many doubts. I have a plugin made, which connects the dynamics with the SAP system. every occurrence created within the dynamics, automatically has to create a protocol in SAP. Most is working, but in some cases it is not integrating. We have an integration log to track, and the message it gives is "Data at the root level is invalid. Line 1, position 1." What could it be, and how could I check what's happening in real time?
I appreciate any help
SERVICE INTEGRATION SAP
public class IntegracaoSap
{
private object service;
public string XmlSapRetonro { get; private set; }
public IntegracaoSap(object provider)
{
this.service = provider;
}
public string OrganizationName { get; set; }
private static readonly Regex _tags_ = new Regex(#"<[^>]+?>", RegexOptions.Multiline | RegexOptions.Compiled);
//add characters that are should not be removed to this regex
private static readonly Regex _notOkCharacter_ = new Regex(#"[^\w;&##.:/\\?=|%!() -]", RegexOptions.Compiled);
public string EnviarProtocolo(Ocorrencia ocorrencia, VariavelAmbiente variavelAmbiente, Email email)
{
if (ocorrencia == null)
{
throw new Exception("Ocorrência não informada.");
}
var emailAssunto = "";
var response = String.Empty;
var msgRetorno = String.Empty;
var remetente = "Remetente: ";
var assunto = "Assunto: ";
var descricaoAssunto = "";
var modeAssuntoRemetente = "";
var emailCliente = string.Empty;
if (email != null)
{
if (email.De[0].Type.Equals("account", StringComparison.InvariantCultureIgnoreCase))
{
var conta = new Conta("", service).ObterPorId(email.De[0].Id);
emailCliente = conta.Email;
}
else if (email.De[0].Type.Equals("contact", StringComparison.InvariantCultureIgnoreCase))
{
var contato = new Contato("", service).ObterPor(email.De[0].Id);
emailCliente = contato.Email;
}
emailAssunto = Regex.Replace(email.Assunto, #"<[^>]*(>|$)| ||»|«", string.Empty).Trim();
modeAssuntoRemetente = remetente + email.De[0].Name + " " + " " + emailCliente + " " + " " + "\n" + assunto + " " + "\n" + emailAssunto;
}
else
{
//pegar email de Contato em Ocorrencia
if(ocorrencia.Cliente.Type.Equals("account",StringComparison.InvariantCultureIgnoreCase))
{
var conta = new Conta("", service).ObterPorId(ocorrencia.Cliente.Id);
emailCliente = conta.Email;
}
else if (ocorrencia.Cliente.Type.Equals("contact", StringComparison.InvariantCultureIgnoreCase))
{
var contato = new Contato("", service).ObterPor(ocorrencia.Cliente.Id);
emailCliente = contato.Email;
}
descricaoAssunto = Regex.Replace(ocorrencia.Descricao, #"<[^>]*(>|$)| ||»|«", string.Empty).Trim();
modeAssuntoRemetente = remetente + ocorrencia.Cliente.Name + " " + "\n" + emailCliente + " " + "\n" + descricaoAssunto;
}
modeAssuntoRemetente = GetSubstring(modeAssuntoRemetente);
string usuario = variavelAmbiente.ObterValorPor("b2bsac_usuario_sap").ToString();
string senha = variavelAmbiente.ObterValorPor("b2bsac_senha_sap").ToString();
string P_DESCRIPTION = string.Empty;
try
{
string url = variavelAmbiente.ObterValorPor("b2bsac_url_sap_ocorrencia").ToString();
string sapStatus = variavelAmbiente.ObterValorPor("b2bsac_sap_pstatus").ToString();
string processType = variavelAmbiente.ObterValorPor("b2bsac_sap_processtype").ToString();
string category = variavelAmbiente.ObterValorPor("b2bsac_sap_category").ToString();
string codeGroup = variavelAmbiente.ObterValorPor("b2bsac_sap_codegroup").ToString();
WebRequest httpWebRequest = WebRequest.Create(url);
httpWebRequest.ContentType = "application/xml";
httpWebRequest.Headers["Ocp-Apim-Subscription-Key"] = variavelAmbiente.ObterValorPor("b2bsac_value_sap").ToString();
httpWebRequest.Headers["SOAPAction"] = "http://sap.com/xi/WebService/soap1.1";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes($"{usuario}:{senha}"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
var xml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:energiasdobrasil-com-br.URA_PROTOCOLO\">" +
" <soapenv:Header/>" +
" <soapenv:Body>" +
"<urn:mt_ura_protocolo>" +
"<IV_BU_PARTNER></IV_BU_PARTNER>" +
"<IV_PROCESS_TYPE>" + processType + "</IV_PROCESS_TYPE>" +
"<IV_DIRECTION>0</IV_DIRECTION>" +
"<IV_CATEGORY>" + category + "</IV_CATEGORY>" +
"<P_STATUS>" + sapStatus +"</P_STATUS>" +
"<P_DESCRIPTION>PROTOCOLO E-MAIL</P_DESCRIPTION>" +
"<P_CODE_GROUP>" + codeGroup + "</P_CODE_GROUP>" +
"<P_CODE>PR01</P_CODE>" +
"<P_FUNC_PARC>ZP000010</P_FUNC_PARC>" +
"<P_FUNC_PARC_RESP>ZP000011</P_FUNC_PARC_RESP>" +
"<P_RESP>CRM_DYN</P_RESP>" +
"<P_DATA>" +
"<REF_GUID></REF_GUID>" +
"<REF_HANDLE></REF_HANDLE>" +
"<REF_KIND></REF_KIND>" +
"<APPT_TYPE></APPT_TYPE>" +
"<TIMESTAMP_FROM></TIMESTAMP_FROM>" +
"<TIMEZONE_FROM></TIMEZONE_FROM>" +
"<TIMESTAMP_TO></TIMESTAMP_TO>" +
"<TIMEZONE_TO></TIMEZONE_TO>" +
"<DATE_FROM>" + ocorrencia.CriadoEm.Value.ToString("yyyyMMdd") + "</DATE_FROM>" +
"<DATE_TO>" + ocorrencia.CriadoEm.Value.ToString("yyyyMMdd") + "</DATE_TO>" +
"<TIME_FROM>" + ocorrencia.CriadoEm.Value.ToString("hhmmss") + "</TIME_FROM>" +
"<TIME_TO>" + ocorrencia.CriadoEm.Value.ToString("hhmmss") + "</TIME_TO>" +
"<SHOW_LOCAL></SHOW_LOCAL>" +
"<DOMINANT></DOMINANT>" +
"<RULE_ID></RULE_ID>" +
"<RULE_NAME></RULE_NAME>" +
"<DURATION></DURATION>" +
"<TIME_UNIT></TIME_UNIT>" +
"<IS_DURATION></IS_DURATION>" +
"<MODE></MODE>" +
"</P_DATA>" +
"<P_INSTALLATION></P_INSTALLATION>" +
"<P_NOTIFICATION></P_NOTIFICATION>" +
"<P_SALESDOCUMENT></P_SALESDOCUMENT>" +
"<P_OBJECTIVE>011</P_OBJECTIVE>" +
"<P_ATIVIDADE_PREC></P_ATIVIDADE_PREC>" +
"<P_BUT0ID>" +
"<PARTNER></PARTNER>" +
"<TYPE></TYPE>" +
"<IDNUMBER></IDNUMBER>" +
"</P_BUT0ID>" +
"<P_LOCATION></P_LOCATION>" +
"<P_ATIVIDADE_EXTERNA>" + ocorrencia.NumeroOcorrencia + "</P_ATIVIDADE_EXTERNA>" +
"<P_TELEFONE_URA></P_TELEFONE_URA>" +
"<P_TEXTO>" +
"<!--Zero or more repetitions:-->" +
"<item>" +
"<REF_GUID></REF_GUID>" +
"<REF_HANDLE></REF_HANDLE>" +
"<REF_KIND></REF_KIND>" +
"<TDID>A002</TDID>" +
"<TDSPRAS></TDSPRAS>" +
"<LANGU_ISO></LANGU_ISO>" +
"<TDSTYLE></TDSTYLE>" +
"<TDFORM></TDFORM>" +
"<TDFORMAT>*</TDFORMAT>" +
"<TDLINE>" + modeAssuntoRemetente + "</TDLINE>" +
"<MODE></MODE>" +
"</item>" +
"</P_TEXTO>" +
"</urn:mt_ura_protocolo>" +
"</soapenv:Body>" +
"</soapenv:Envelope>";
streamWriter.Write(xml);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
var encoding = ASCIIEncoding.UTF8;
using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream(), encoding))
{
response = reader.ReadToEnd();
msgRetorno = response;
this.XmlSapRetonro = response;
}
}
catch (Exception ex)
{
msgRetorno = $"Ocorreu um erro no método EnviarProtocolo: {ex.Message}";
}
return msgRetorno;
}
public static String UnHtml(String html)
{
html = HttpUtility.UrlDecode(html);
html = HttpUtility.HtmlDecode(html);
html = RemoveTag(html, "<!--", "-->");
html = RemoveTag(html, "<script", "</script>");
html = RemoveTag(html, "<style", "</style>");
//replace matches of these regexes with space
html = _tags_.Replace(html, " ");
html = _notOkCharacter_.Replace(html, " ");
html = SingleSpacedTrim(html);
return html;
}
private static String RemoveTag(String html, String startTag, String endTag)
{
Boolean bAgain;
do
{
bAgain = false;
Int32 startTagPos = html.IndexOf(startTag, 0, StringComparison.CurrentCultureIgnoreCase);
if (startTagPos < 0)
continue;
Int32 endTagPos = html.IndexOf(endTag, startTagPos + 1, StringComparison.CurrentCultureIgnoreCase);
if (endTagPos <= startTagPos)
continue;
html = html.Remove(startTagPos, endTagPos - startTagPos + endTag.Length);
bAgain = true;
} while (bAgain);
return html;
}
private static String SingleSpacedTrim(String inString)
{
StringBuilder sb = new StringBuilder();
Boolean inBlanks = false;
foreach (Char c in inString)
{
switch (c)
{
case '\r':
case '\n':
case '\t':
case ' ':
if (!inBlanks)
{
inBlanks = true;
sb.Append(' ');
}
continue;
default:
inBlanks = false;
sb.Append(c);
break;
}
}
return sb.ToString().Trim();
}
public static string GetSubstring(string modeAssuntoRemetente)
{
string valorTexto = modeAssuntoRemetente;
// Pega os 132 caracteres da String
valorTexto = valorTexto.PadRight(132, ' ').Substring(0, 132);
return valorTexto;
}
}
}
OCURRENCE
public class OcorrenciaManager : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
#region Contexto e Serviços
// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
// Obtain the organization service reference which you will need for
// web service calls.
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService adminService = serviceFactory.CreateOrganizationService(null);
IOrganizationService userService = serviceFactory.CreateOrganizationService(context.UserId);
// Obtain the tracing service
ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
#endregion
adminService.SetDistribution(Distribution.Online);
Entity entidadeDoContexto = SDKorePlugin.GetContextEntity(context);
if (SDKorePlugin.Validate(context, SDKorePlugin.MessageName.Create, SDKorePlugin.Stage.PostOperation, SDKorePlugin.Mode.Asynchronous))
{
Ocorrencia ocorrencia = entidadeDoContexto.Parse<Ocorrencia>(context.OrganizationName, context.IsExecutingOffline, adminService);
Email email = new Email(context.OrganizationName, adminService).BuscarPrimeiroEmailOcorrencia(ocorrencia.Id.Value);
var logIntegracao = new LogIntegracao(context.OrganizationName, adminService);
var variavelAmbiente = new VariavelAmbiente(context.OrganizationName, adminService);
trace.Trace("Início da integração de consulta Ocorrencia");
if (entidadeDoContexto.Attributes.Contains("ticketnumber") && entidadeDoContexto.Attributes.Contains("description"))
{
trace.Trace("Início da integração de consulta Ocorrencia");
ocorrencia.CriarXMLParaSap(ocorrencia,variavelAmbiente,email);
}
}
}
}
}
MODEL
[LogicalEntity("incident")]
public class Ocorrencia : SDKoreBase
{
#region Construtores
public IOrganizationService service;
public Ocorrencia(string organization)
: base(organization)
{
RepositorioOcorrencia = new RepositoryOcorrencia<Ocorrencia>();
}
public Ocorrencia(string organization, object provider)
: base(organization, provider)
{
RepositorioOcorrencia = new RepositoryOcorrencia<Ocorrencia>();
RepositorioOcorrencia.SetOrganization(organization);
this.SetProvider(provider);
}
private void SetProvider(object provider)
{
RepositorioOcorrencia.SetProvider(provider);
this.Provider = provider;
}
#endregion
#region Atributos
private RepositoryOcorrencia<Ocorrencia> RepositorioOcorrencia { get; set; }
[LogicalAttribute("customerid")]
public Lookup Cliente { get; set; }
[LogicalAttribute("incidentid")]
public Guid? Id { get; set; }
[LogicalAttribute("ticketnumber")]
public string NumeroOcorrencia { get; set; }
[LogicalAttribute("description")]
public string Descricao { get; set; }
[LogicalAttribute("b2bsac_integracaoSAP")]
public Option Sac_Integracaosap { get; set; }
[LogicalAttribute("emailaddress")]
public string Email { get; set; }
#endregion
#region Métodos
public Ocorrencia ObterPorNumOcorrencia(string NumeroOcorrencia)
{
Ocorrencia _ocorrencia = null;
_ocorrencia = RepositorioOcorrencia.BuscarPorOcorrencia(NumeroOcorrencia);
return _ocorrencia;
}
public Ocorrencia ObterPor(Guid ocorrenciaId)
{
return RepositorioOcorrencia.Retrieve(ocorrenciaId);
}
public Guid Criar()
{
return RepositorioOcorrencia.Create(this);
}
public void Atualizar()
{
RepositorioOcorrencia.Update(this);
}
public void CriarXMLParaSap(Ocorrencia ocorrencia, VariavelAmbiente variavelAmbiente, Email email)
{
string response = string.Empty;
string MsgError = string.Empty;
try
{
var ocorrenciaAtualizar = new Ocorrencia("", this.Provider);
ocorrenciaAtualizar.Id = ocorrencia.Id;
ocorrenciaAtualizar.Sac_Integracaosap = new Option((int)Enumerator.IntegracaoSAP.EnviadoParaSap);
ocorrenciaAtualizar.Atualizar();
var integracaoSAP = new IntegracaoSap(this.Provider);
response = integracaoSAP.EnviarProtocolo(ocorrencia, variavelAmbiente, email);
var logIntegracao = new LogIntegracao("", this.Provider);
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(response);
if (xDoc.SelectSingleNode("//P_MSG_RETORNO") != null)
{
if (xDoc.GetElementsByTagName("P_MSG_RETORNO").Item(0) != null)
{
MsgError = xDoc.GetElementsByTagName("P_MSG_RETORNO").Item(0).InnerText;
}
}
if ((MsgError != "Atividade criada !"))
{
ocorrenciaAtualizar.Sac_Integracaosap = new Option((int)Enumerator.IntegracaoSAP.NaoIntegradoComSap);
ocorrenciaAtualizar.Atualizar();
logIntegracao.Mensagem = MsgError;
if (!string.IsNullOrEmpty(integracaoSAP.XmlSapRetonro))
{
if (integracaoSAP.XmlSapRetonro.Length <= 9000)
{
logIntegracao.Mensagem += integracaoSAP.XmlSapRetonro;
}
else
{
logIntegracao.Mensagem += integracaoSAP.XmlSapRetonro.Substring(0, 8999);
}
}
logIntegracao.NumeroTentativas = 1;
logIntegracao.NomeSap = "";
logIntegracao.Ocorrencia = new SDKore.DomainModel.Lookup(ocorrencia.Id.Value, "incident");
logIntegracao.Criar();
}
else
{
ocorrenciaAtualizar.Sac_Integracaosap = new Option((int)Enumerator.IntegracaoSAP.IntegradoComSap);
ocorrenciaAtualizar.Atualizar();
}
}
catch(Exception ex)
{
ocorrenciaAtualizar.Sac_Integracaosap = new Option((int)Enumerator.IntegracaoSAP.NaoIntegradoComSap);
ocorrenciaAtualizar.Atualizar();
logIntegracao.Mensagem = ex.Message;
if (!string.IsNullOrEmpty(integracaoSAP.XmlSapRetonro))
{
if (integracaoSAP.XmlSapRetonro.Length <= 9000)
{
logIntegracao.Mensagem += integracaoSAP.XmlSapRetonro;
}
else
{
logIntegracao.Mensagem += integracaoSAP.XmlSapRetonro.Substring(0, 8999);
}
}
logIntegracao.NumeroTentativas = 1;
logIntegracao.NomeSap = "";
logIntegracao.Ocorrencia = new SDKore.DomainModel.Lookup(ocorrencia.Id.Value, "incident");
logIntegracao.Criar();
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message);
}
}
#endregion
}
}
Related
I am developing an application. When I modify my data, the previous data is displayed and not the updated data. This is the ModifyActivity.java file:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ModifyCountryActivity extends Activity implements OnClickListener {
private EditText titleText, dateText, timeText;
private Button updateBtn, deleteBtn;
public Calendars calendars;
private DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Modify Record");
setContentView(R.layout.activity_modify_record);
dbHelper = new DatabaseHelper(this);
calendars = new Calendars();
titleText = (EditText) findViewById(R.id.title_edittext_modify);
timeText = (EditText) findViewById(R.id.time_edittext_modify);
dateText = (EditText) findViewById(R.id.date_edittext_modify);
updateBtn = (Button) findViewById(R.id.btn_update);
deleteBtn = (Button) findViewById(R.id.btn_delete);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String time = intent.getStringExtra("time");
String date = intent.getStringExtra("date");
titleText.setText(title);
timeText.setText(time);
dateText.setText(date);
updateBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_update:
titleText.setText(titleText.getText().toString() + " ");
timeText.setText(dateText.getText().toString() + " ");
dateText.setText(timeText.getText().toString() + " ");
calendars.set_remindertitle(titleText.getText().toString() + " ");
calendars.set_reminderdate(dateText.getText().toString() + " ");
calendars.set_remindertime(timeText.getText().toString() + " ");
dbHelper.update(calendars);
this.returnHome();
break;
case R.id.btn_delete:
dbHelper.delete(calendars);
this.returnHome();
break;
}
}
public void returnHome() {
Intent home_intent = new Intent(getApplicationContext(), CountryListActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
The database doesn't update. It shows the previous data again. This is the database class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "calendar.db";
public static final String TABLE_REMINDER = "reminder";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_REMINDER_TITLE = "_remindertitle";
public static final String COLUMN_REMINDER_DESCRIPTION = "_reminderdescription";
public static final String COLUMN_REMINDER_DATE = "_reminderdate";
public static final String COLUMN_REMINDER_TIME = "_remindertime";
public static final String COLUMN_REMINDER_REPEAT = "_reminderrepeat";
public static final String COLUMN_REMINDER_SNOOZE = "_remindersnooze";
SQLiteDatabase database;
// Database Information
Class<? extends DatabaseHelper> context = getClass();
DatabaseHelper dbHelper;
// Creating table query
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_REMINDER + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_REMINDER_DATE + " TEXT, " + COLUMN_REMINDER_TIME + " TEXT, " + COLUMN_REMINDER_TITLE + " TEXT, "
+ COLUMN_REMINDER_DESCRIPTION + " TEXT, " + COLUMN_REMINDER_REPEAT + " TEXT, " + COLUMN_REMINDER_SNOOZE + " TEXT " + ");";
Log.i("Query", query);
db.execSQL(query);
}
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REMINDER);
onCreate(db);
}
public ArrayList<Calendars> databaseToArrayList() {
ArrayList<Calendars> arrayList = new ArrayList();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_REMINDER;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("_reminderdate")) != null) {
Calendars calendars = new Calendars();
calendars.set_reminderdate(c.getString(c.getColumnIndex(COLUMN_REMINDER_DATE)));
calendars.set_remindertime(c.getString(c.getColumnIndex(COLUMN_REMINDER_TIME)));
calendars.set_remindertitle(c.getString(c.getColumnIndex(COLUMN_REMINDER_TITLE)));
calendars.set_reminderdescription(c.getString(c.getColumnIndex(COLUMN_REMINDER_DESCRIPTION)));
calendars.set_reminderrepeat(c.getString(c.getColumnIndex(COLUMN_REMINDER_REPEAT)));
calendars.set_remindersnooze(c.getString(c.getColumnIndex(COLUMN_REMINDER_SNOOZE)));
arrayList.add(calendars);
}
c.moveToNext();
}
c.close();
db.close();
return arrayList;
}
public void remove(String id) {
String string = String.valueOf(id);
SQLiteDatabase database = getReadableDatabase();
database.execSQL("DELETE FROM " + TABLE_REMINDER + " WHERE _id = '" + string + "'");
}
public void addReminder(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());
SQLiteDatabase database = getReadableDatabase();
database.insert(TABLE_REMINDER, null, contentValues);
Log.i("insData", "the data has been inseted");
database.close();
}
public Cursor fetch() {
String[] columns = new String[]{COLUMN_ID, /*COLUMN_REMINDER_DATE, COLUMN_REMINDER_TIME, COLUMN_REMINDER_TITLE,*/
COLUMN_REMINDER_DESCRIPTION, COLUMN_REMINDER_REPEAT, COLUMN_REMINDER_SNOOZE};
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.query(TABLE_REMINDER, columns, null, null, null, null, null);
if (cursor != null)
{
cursor.moveToFirst();
}
return cursor;
}
public int update(Calendars calendars) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_REMINDER_DATE, calendars.get_reminderdate());
contentValues.put(COLUMN_REMINDER_TIME, calendars.get_remindertime());
contentValues.put(COLUMN_REMINDER_TITLE, calendars.get_remindertitle());/*
contentValues.put(COLUMN_REMINDER_DESCRIPTION, calendars.get_reminderdescription());
contentValues.put(COLUMN_REMINDER_REPEAT, calendars.get_reminderrepeat());
contentValues.put(COLUMN_REMINDER_SNOOZE, calendars.get_remindersnooze());*/
SQLiteDatabase database = getReadableDatabase();
int i = database.update(TABLE_REMINDER, contentValues, COLUMN_ID + " = " + calendars.get_id(), null);
database.close();
return i;
}
public void delete(Calendars calendars) {
database = getReadableDatabase();
database.delete(TABLE_REMINDER, COLUMN_ID + "=" + calendars.get_id(), null);
}
}
I believe that the update button should be working fine. I am new to Android and don't know how to solve this problem. Any suggestions on how to solve it?
If you're update function returns an int, then in your onClick function, rather than typing:
dbHelper.update(calendars);
You need to type:
int update = dbHelper.update(calendars);
Or:
if (dbHelper.update(calendars) > 0) {
// do something here
}
I would recommend the latter of the options. See how you go.
I have 3 GridViews, each inside a separate tab. Every row in the GridView is associated with a LinkButton, and when it's clicked a MessageBox are popping up, showing the content on that particular row.
The problem is that when the MessageBox pops up the GridView disappears, and when MessageBox is closed GridView then comes back.
This problem doesn't occur if GridView is used without any tabs and is placed outside the TabControl. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
TabControl TheTabCtrl = new TabControl("InfoTabCtrl");
for (var i = 0; i < 3; i++)
{
GridView newGridView = new GridView();
//generate dynamic id
newGridView.ID = String.Concat("GridView", i);
newGridView.AutoGenerateColumns = false;
newGridView.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
//if (!this.IsPostBack)
//{
BoundField bfield = new BoundField();
bfield.HeaderText = "Id";
bfield.DataField = "Id";
newGridView.Columns.Add(bfield);
bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
newGridView.Columns.Add(bfield);
TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
newGridView.Columns.Add(tfield);
tfield = new TemplateField();
tfield.HeaderText = "View";
newGridView.Columns.Add(tfield);
//}
this.BindGrid(newGridView, i);
string myString = i.ToString();
TabPage BasicPage1 = new TabPage(myString, myString);
BasicPage1.Controls.Add(newGridView);
TheTabCtrl.Tabs.Add(BasicPage1);
}
if (!this.IsPostBack)
{
string value = Request.Form[TheTabCtrl.Id + "_SelectedTab"];
if (!string.IsNullOrEmpty(value))
{
try
{
TheTabCtrl.SelectedTab = TheTabCtrl.Tabs.IndexOf(TheTabCtrl.Tabs.Where(x => x.Id == value).First());
}
catch
{
}
}
}
form1.Controls.Add(TheTabCtrl.GetControl);
}
private void BindGrid(GridView newGridView, int id)
{
string[][,] jaggedArray = new string[3][,]
{
new string[,] { {"John Hammond", "United States"}, {"Mudassar Khan", "India"}, {"Suzanne Mathews", "France"}, {"Robert Schidner", "Russia"} },
new string[,] { {"Zoey Melwick", "New Zeeland"}, {"Bryan Robertson", "England"}, {"Beth Stewart", "Australia"}, {"Amanda Rodrigues", "Portugal"} },
new string[,] { {"Glenda Becker", "Germany"}, {"Despoina Athanasiadis", "Greece"}, {"Alexandra López", "Spain"}, {"David Bouchard", "Canada"} }
};
for (int row = 0; row < jaggedArray.Length; row++)
{
if (id != row) continue;
DataTable dt = new DataTable();
// Share the same headlines
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
for (int pair = 0; pair < jaggedArray[row].Length / 2; pair++)
{
dt.Rows.Add(pair + 1, jaggedArray[row][pair, 0], jaggedArray[row][pair, 1]);
}
string myPage = string.Concat(row, "page");
string myString = row.ToString();
newGridView.DataSource = dt;
newGridView.DataBind();
}//End for Row
}//BindGrid
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
e.Row.Cells[1].Width = 200;
e.Row.Cells[2].Controls.Add(txtCountry);
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[1].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
So how can I show a MessageBox without GridView disappearing?
I get the following log during on-device debugging
Error:
*** [Play Games Plugin DLL] ERROR: Cloud load failed with status code 7
Basically the OnStateLoaded() callback function always returns the boolean success = false and I can't figure out the reason why.
All that the plugin debugging logs mention is "Cloud load failed with status code 7".
According to the android doc, 7 is a generic "developer error", see https://developer.android.com/reference/com/google/android/gms/appstate/AppStateStatusCodes.html#STATUS_DEVELOPER_ERROR
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set
to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID
Created a new project in Unity
Added the play games plugin (Assets/Import Package.../Custom
Package)
Set the application ID (Google Play Games/Android Setup...)
Switched the platform to Android (File/Build Settings...)
Set the player settings (bundle identifier and the keystore info)
Added a new script component to the camera
Saved everything and hit build and run.
Here are the contents:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
void Start () {
slot0 = new GameData(0,"waiting for login....");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.Data =" loading....";
slot0.LoadState();
}
else {
Debug.LogWarning("Authentication failed!");
}
};
// make Play Games the default social implementation
PlayGamesPlatform.Activate();
// enable debug logs
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
protected void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,100);
Rect dataRect = new Rect( 10, 150, Screen.width,100);
Rect b1Rect = new Rect(10, 400, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth,
b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
// logged in, so show the load button and the contents of the saved data.
if(GUI.Button(b1Rect, "Load")) {
slot0.LoadState();
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
// just save a string, incrementing the number on the end.
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
slot0.SaveState();
}
GUI.Label(statusRect, slot0.State);
}
// Class to handle save/load callbacks.
public class GameData : OnStateLoadedListener {
int slot;
string data;
string state;
public GameData(int slot, string data) {
this.slot = slot;
this.data = data;
this.state = "Initialized, modified";
}
public void LoadState() {
this.state += ", loading";
((PlayGamesPlatform)Social.Active).LoadState(0, this);
}
public void SaveState() {
byte[] bytes = new byte[data.Length * sizeof(char)];
System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
this.state += ", saving";
((PlayGamesPlatform) Social.Active).UpdateState(slot, bytes, this);
}
public void OnStateLoaded(bool success, int slot, byte[] data) {
if (success) {
Debug.Log ("Save game slot : " + slot + " loaded: " + data);
if (data != null) {
char[] chars = new char[data.Length / sizeof(char)];
System.Buffer.BlockCopy(data, 0, chars, 0, data.Length);
this.data = new string(chars);
this.state = "loaded";
} else {
Debug.Log ("Saved data is null");
this.data = "";
this.state = "loaded, but empty";
}
} else {
// handle failure
Debug.LogWarning ("Save game slot : " + slot + " failed!: ");
this.data = "";
this.state = "loading failed!";
}
}
public byte[] OnStateConflict(int slot, byte[] local, byte[] server) {
// resolve conflict and return a byte[] representing the
// resolved state.
Debug.LogWarning("Conflict in saved data!");
state = "conflicted";
// merge or resolve using app specific logic, here
byte[] resolved = local.Length > server.Length ? local : server;
char[] chars = new char[resolved.Length / sizeof(char)];
System.Buffer.BlockCopy(resolved, 0, chars, 0, resolved.Length);
this.data = new string(chars);
return resolved;
}
public void OnStateSaved(bool success, int slot) {
Debug.Log ("Save game slot : " + slot + " success: " + success);
state = "saved";
}
public string Data {
get {
return data;
}
set {
data = value;
state += ", modified";
}
}
public int Slot {
get {
return slot;
}
}
public string State {
get {
return state;
}
}
}
}
The error code 7 is because the Cloud Save API has been deprecated and is only currently accessible to existing games that have used the API. The Unity plugin version 0.9.11 has been updated to use the SavedGames API.
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID Created a new
project in Unity
Added the play games plugin (Assets/Import
Package.../Custom Package)
Set the application ID (Google Play
Games/Android Setup...)
Switched the platform to Android (File/Build
Settings...)
Set the player settings (bundle identifier and the
keystore info)
Added a new script component to the camera Saved
everything and hit build and run.
Here is my script:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
using GooglePlayGames.BasicApi.SavedGame;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
bool mSaving;
private Texture2D mScreenImage;
// Use this for initialization
void Start () {
slot0 = new GameData("New game");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.State = "Click load or save";
}
else {
Debug.LogWarning("Authentication failed!");
}
};
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.EnableSavedGames()
.Build();
PlayGamesPlatform.InitializeInstance(config);
// Activate the Play Games platform. This will make it the default
// implementation of Social.Active
PlayGamesPlatform.Activate();
// enable debug logs (note: we do this because this is a sample; on your production
// app, you probably don't want this turned on by default, as it will fill the user's
// logs with debug info).
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
public void CaptureScreenshot() {
mScreenImage = new Texture2D(Screen.width, Screen.height);
mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
mScreenImage.Apply();
}
protected virtual void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,200);
Rect dataRect = new Rect( 10, 250, Screen.width,100);
Rect b1Rect = new Rect(10, 800, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth, b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
if(GUI.Button(b1Rect, "Load")) {
mSaving = false;
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
4,false,false,SavedGameSelected);
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
mSaving = true;
CaptureScreenshot();
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
4,true,true,SavedGameSelected);
}
GUI.Label(statusRect, slot0.State);
}
public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
if (status == SelectUIStatus.SavedGameSelected) {
string filename = game.Filename;
Debug.Log("opening saved game: " + game);
if(mSaving && (filename == null || filename.Length == 0)) {
filename = "save" + DateTime.Now.ToBinary();
}
if (mSaving) {
slot0.State = "Saving to " + filename;
}
else {
slot0.State = "Loading from " + filename;
}
//open the data.
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
SavedGameOpened);
} else {
Debug.LogWarning("Error selecting save game: " + status);
}
}
public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
if( mSaving) {
slot0.State = "Opened, now writing";
byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
Debug.Log("Saving to " + game);
byte[] data = slot0.ToBytes();
TimeSpan playedTime = slot0.TotalPlayingTime;
SavedGameMetadataUpdate.Builder builder = new
SavedGameMetadataUpdate.Builder()
.WithUpdatedPlayedTime(playedTime)
.WithUpdatedDescription("Saved Game at " + DateTime.Now);
if (pngData != null) {
Debug.Log("Save image of len " + pngData.Length);
builder = builder.WithUpdatedPngCoverImage(pngData);
}
else {
Debug.Log ("No image avail");
}
SavedGameMetadataUpdate updatedMetadata = builder.Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
} else {
slot0.State = "Opened, reading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
}
} else {
Debug.LogWarning("Error opening game: " + status);
}
}
public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
if (status == SavedGameRequestStatus.Success) {
Debug.Log("SaveGameLoaded, success=" + status);
slot0 = GameData.FromBytes(data);
} else {
Debug.LogWarning("Error reading game: " + status);
}
}
public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
Debug.Log ("Game " + game.Description + " written");
slot0.State = "Saved!";
} else {
Debug.LogWarning("Error saving game: " + status);
}
}
public class GameData {
private TimeSpan mPlayingTime;
private DateTime mLoadedTime;
string mData;
string mState;
static readonly string HEADER = "GDv1";
public GameData(string data) {
mData = data;
mState = "Initialized, modified";
mPlayingTime = new TimeSpan();
mLoadedTime = DateTime.Now;
}
public TimeSpan TotalPlayingTime {
get {
TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
return mPlayingTime.Add(delta);
}
}
public override string ToString () {
string s = HEADER + ":" + mData;
s += ":" + TotalPlayingTime.TotalMilliseconds;
return s;
}
public byte[] ToBytes() {
return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
}
public static GameData FromBytes (byte[] bytes) {
return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
}
public static GameData FromString (string s) {
GameData gd = new GameData("initializing from string");
string[] p = s.Split(new char[] { ':' });
if (!p[0].StartsWith(HEADER)) {
Debug.LogError("Failed to parse game data from: " + s);
return gd;
}
gd.mData = p[1];
double val = Double.Parse(p[2]);
gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
gd.mLoadedTime = DateTime.Now;
gd.mState = "Loaded successfully";
return gd;
}
public string Data {
get {
return mData;
}
set {
mData = value;
mState += ", modified";
}
}
public string State {
get {
return mState;
}
set {
mState = value;
}
}
}
}
I am using below class to enable stream management("urn:xmpp:sm:3") in our ejabberd server(we have latest version of ejabberd). But when I send the Enable packet to server it says Service Unavailable(503). But when I use "yaxim" it works perfectly. Please help me to solve this problem. Thanks.
public class XmppStreamHandler {
public static final String URN_SM_3 = "urn:xmpp:sm:3";
private static final int MAX_OUTGOING_QUEUE_SIZE = 20;
private static final int OUTGOING_FILL_RATIO = 4;
private XMPPConnection mConnection;
private boolean isSmAvailable = false;
private boolean isSmEnabled = false;
private boolean isOutgoingSmEnabled = false;
private long previousIncomingStanzaCount = -1;
private String sessionId;
private long incomingStanzaCount = 0;
private long outgoingStanzaCount = 0;
private Queue<Packet> outgoingQueue;
private int maxOutgoingQueueSize = MAX_OUTGOING_QUEUE_SIZE;
private ConnectionListener mConnectionListener;
public XmppStreamHandler(XMPPConnection connection, ConnectionListener connectionListener) {
mConnection = connection;
mConnectionListener = connectionListener;
startListening();
}
/** Perform a quick shutdown of the XMPPConnection if a resume is possible */
public void quickShutdown() {
if (isResumePossible()) {
mConnection.quickShutdown();
// We will not necessarily get any notification from a quickShutdown, so adjust our state here.
closeOnError();
} else {
mConnection.shutdown();
}
}
public void setMaxOutgoingQueueSize(int maxOutgoingQueueSize) {
this.maxOutgoingQueueSize = maxOutgoingQueueSize;
}
public boolean isResumePossible() {
return sessionId != null;
}
public boolean isResumePending() {
return isResumePossible() && !isSmEnabled;
}
public static void addExtensionProviders() {
addSimplePacketExtension("sm", URN_SM_3);
addSimplePacketExtension("r", URN_SM_3);
addSimplePacketExtension("a", URN_SM_3);
addSimplePacketExtension("enabled", URN_SM_3);
addSimplePacketExtension("resumed", URN_SM_3);
addSimplePacketExtension("failed", URN_SM_3);
}
public void notifyInitialLogin() {
if (sessionId == null && isSmAvailable)
sendEnablePacket();
}
private void sendEnablePacket() {
debug("sm send enable " + sessionId);
if (sessionId != null) {
isOutgoingSmEnabled = true;
// TODO binding
StreamHandlingPacket resumePacket = new StreamHandlingPacket("resume", URN_SM_3);
resumePacket.addAttribute("h", String.valueOf(previousIncomingStanzaCount));
resumePacket.addAttribute("previd", sessionId);
mConnection.sendPacket(resumePacket);
} else {
outgoingStanzaCount = 0;
outgoingQueue = new ConcurrentLinkedQueue<Packet>();
isOutgoingSmEnabled = true;
StreamHandlingPacket enablePacket = new StreamHandlingPacket("enable", URN_SM_3);
enablePacket.addAttribute("resume", "true");
mConnection.sendPacket(enablePacket);
}
}
private void closeOnError() {
if (isSmEnabled && sessionId != null) {
previousIncomingStanzaCount = incomingStanzaCount;
}
isSmEnabled = false;
isOutgoingSmEnabled = false;
isSmAvailable = false;
}
private void startListening() {
mConnection.forceAddConnectionListener(new ConnectionListener() {
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception e) {
}
public void reconnectingIn(int seconds) {
}
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException &&
((XMPPException)e).getStreamError() != null) {
// Non-resumable stream error
close();
} else {
// Resumable
closeOnError();
}
}
public void connectionClosed() {
previousIncomingStanzaCount = -1;
}
});
mConnection.addPacketSendingListener(new PacketListener() {
public void processPacket(Packet packet) {
// Ignore our own request for acks - they are not counted
if (!isStanza(packet)) {
trace("send " + packet.toXML());
return;
}
if (isOutgoingSmEnabled && !outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
outgoingQueue.add(packet);
trace("send " + outgoingStanzaCount + " : " + packet.toXML());
// Don't let the queue grow beyond max size. Request acks and drop old packets
// if acks are not coming.
if (outgoingQueue.size() >= maxOutgoingQueueSize / OUTGOING_FILL_RATIO) {
mConnection.sendPacket(new StreamHandlingPacket("r", URN_SM_3));
}
if (outgoingQueue.size() > maxOutgoingQueueSize) {
// Log.e(XmppConnection.TAG, "not receiving acks? outgoing queue full");
outgoingQueue.remove();
}
} else if (isOutgoingSmEnabled && outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
trace("send DUPLICATE " + outgoingStanzaCount + " : " + packet.toXML());
} else {
trace("send " + packet.toXML());
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
mConnection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
if (isSmEnabled && isStanza(packet)) {
incomingStanzaCount++;
trace("recv " + incomingStanzaCount + " : " + packet.toXML());
} else {
trace("recv " + packet.toXML());
}
if (packet instanceof StreamHandlingPacket) {
StreamHandlingPacket shPacket = (StreamHandlingPacket) packet;
String name = shPacket.getElementName();
if ("sm".equals(name)) {
debug("sm avail");
isSmAvailable = true;
if (sessionId != null)
sendEnablePacket();
} else if ("r".equals(name)) {
StreamHandlingPacket ackPacket = new StreamHandlingPacket("a", URN_SM_3);
ackPacket.addAttribute("h", String.valueOf(incomingStanzaCount));
mConnection.sendPacket(ackPacket);
} else if ("a".equals(name)) {
long ackCount = Long.valueOf(shPacket.getAttribute("h"));
removeOutgoingAcked(ackCount);
trace(outgoingQueue.size() + " in outgoing queue after ack");
} else if ("enabled".equals(name)) {
incomingStanzaCount = 0;
isSmEnabled = true;
mConnection.getRoster().setOfflineOnError(false);
String resume = shPacket.getAttribute("resume");
if ("true".equals(resume) || "1".equals(resume)) {
sessionId = shPacket.getAttribute("id");
}
debug("sm enabled " + sessionId);
} else if ("resumed".equals(name)) {
debug("sm resumed");
incomingStanzaCount = previousIncomingStanzaCount;
long resumeStanzaCount = Long.valueOf(shPacket.getAttribute("h"));
// Removed acked packets
removeOutgoingAcked(resumeStanzaCount);
trace(outgoingQueue.size() + " in outgoing queue after resume");
// Resend any unacked packets
for (Packet resendPacket : outgoingQueue) {
mConnection.sendPacket(resendPacket);
}
// Enable only after resend, so that the interceptor does not
// queue these again or increment outgoingStanzaCount.
isSmEnabled = true;
// Re-notify the listener - we are really ready for packets now
// Before this point, isSuspendPending() was true, and the listener should have
// ignored reconnectionSuccessful() from XMPPConnection.
mConnectionListener.reconnectionSuccessful();
} else if ("failed".equals(name)) {
// Failed, shutdown and the parent will retry
debug("sm failed");
mConnection.getRoster().setOfflineOnError(true);
mConnection.getRoster().setOfflinePresences();
sessionId = null;
mConnection.shutdown();
// isSmEnabled / isOutgoingSmEnabled are already false
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
}
private void removeOutgoingAcked(long ackCount) {
if (ackCount > outgoingStanzaCount) {
// Log.e(XmppConnection.TAG,
// "got ack of " + ackCount + " but only sent " + outgoingStanzaCount);
// Reset the outgoing count here in a feeble attempt to re-sync. All bets
// are off.
outgoingStanzaCount = ackCount;
}
int size = outgoingQueue.size();
while (size > outgoingStanzaCount - ackCount) {
outgoingQueue.remove();
size--;
}
}
private static void addSimplePacketExtension(final String name, final String namespace) {
ProviderManager.getInstance().addExtensionProvider(name, namespace,
new PacketExtensionProvider() {
public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
StreamHandlingPacket packet = new StreamHandlingPacket(name, namespace);
int attributeCount = parser.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
packet.addAttribute(parser.getAttributeName(i),
parser.getAttributeValue(i));
}
return packet;
}
});
}
private void debug(String message) {
System.out.println(message);
}
private void trace(String message) {
System.out.println(message);
}
public static class StreamHandlingPacket extends UnknownPacket {
private String name;
private String namespace;
Map<String, String> attributes;
StreamHandlingPacket(String name, String namespace) {
this.name = name;
this.namespace = namespace;
attributes = Collections.emptyMap();
}
public void addAttribute(String name, String value) {
if (attributes == Collections.EMPTY_MAP)
attributes = new HashMap<String, String>();
attributes.put(name, value);
}
public String getAttribute(String name) {
return attributes.get(name);
}
public String getNamespace() {
return namespace;
}
public String getElementName() {
return name;
}
public String toXML() {
StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName());
// TODO Xmlns??
if (getNamespace() != null) {
buf.append(" xmlns=\"").append(getNamespace()).append("\"");
}
for (String key : attributes.keySet()) {
buf.append(" ").append(key).append("=\"")
.append(StringUtils.escapeForXML(attributes.get(key))).append("\"");
}
buf.append("/>");
return buf.toString();
}
}
/** Returns true if the packet is a Stanza as defined in RFC-6121 - a Message, IQ or Presence packet. */
public static boolean isStanza(Packet packet) {
if (packet instanceof Message)
return true;
if (packet instanceof IQ)
return true;
if (packet instanceof Presence)
return true;
return false;
}
public void queue(Packet packet) {
if (outgoingQueue.size() >= maxOutgoingQueueSize) {
System.out.println("outgoing queue full");
return;
}
outgoingStanzaCount++;
outgoingQueue.add(packet);
}
private void close() {
isSmEnabled = false;
isOutgoingSmEnabled = false;
sessionId = null;
}
}
when I send the Enable packet to server it says Service
Unavailable(503)
Service Unavailable means that the service is unavailable on the server. Does ejabberd support XEP-198? Did you enable it?
You should also consider switching to Smack 4.1.0-alpha, which also runs on Android and comes with Stream Management support. yaxim will soon switch to from it's custom XmppStreamHandler implementation to Smack 4.1.
I had created a datagridview like this
public void gridviewsetup()
{
tbl_Aplication.Columns.Add("1", "Empid");
tbl_Aplication.Columns.Add("2", "Emp no");
tbl_Aplication.Columns.Add("3", "Emp Name");
tbl_Aplication.Columns.Add("4", "Department ");
tbl_Aplication.Columns.Add("5", "Designation");
tbl_Aplication.Columns.Add("6", "Shift");
tbl_Aplication.Columns.Add("7", "Start Time");
tbl_Aplication.Columns.Add("8", "End Time");
tbl_Aplication.Columns.Add("9", "OT");
tbl_Aplication.Columns.Add("10", "Reversed Swipe Out");
tbl_Aplication.RowTemplate.Height = 18;
}
and i had populated a data table to fill the data dgridview
public void filldatagrid()
{
if (cmb_dept.Text.Trim() != "")
{
Datatable employedata = empreg.getallemployeeshiftdetails(int.Parse(cmb_dept.SelectedValue.ToString()), Program.LOCTNPK);
tbl_Aplication.Rows.Clear();
tbl_Aplication.DataSource = null;
for (int i = 0; i < employedata.Rows.Count; i++)
{
tbl_Aplication.Rows.Add();
tbl_Aplication.Rows[i].Cells[1].Value = employedata.Rows[i][0];
tbl_Aplication.Rows[i].Cells[2].Value = employedata.Rows[i][1];
tbl_Aplication.Rows[i].Cells[3].Value = employedata.Rows[i][2];
tbl_Aplication.Rows[i].Cells[4].Value = employedata.Rows[i][3];
tbl_Aplication.Rows[i].Cells[5].Value = employedata.Rows[i][4];
tbl_Aplication.Rows[i].Cells[6].Value = employedata.Rows[i][5];
tbl_Aplication.Rows[i].Cells[7].Value = employedata.Rows[i][6];
tbl_Aplication.Rows[i].Cells[8].Value = employedata.Rows[i][7];
tbl_Aplication.Rows[i].Cells[9].Value = 0;
tbl_Aplication.Rows[i].Cells[10].Value = employedata.Rows[i][7];
}
}
}
now i want to filter data in the datagrid with the designation selected in the combobox without going back to database ,I did it like this but it shows error
private void cmb_designation_SelectedIndexChanged(object sender, EventArgs e)
{
if (desgflag != 0)
{
if (cmb_dept.SelectedValue!=null )
{
// tbl_Aplication.DataSource = employedata;
((DataTable)tbl_Aplication.DataSource).DefaultView.RowFilter = " designationnName like '%" + cmb_dept.Text.Trim() + "%' ";
}
}
}
I had done it
private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)
{
tbl_DestinationData.DataSource = dt;
}
else
{
((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";
}
}
catch (Exception )
{
throw;
}
}