How to deserialize a UDPTunnel in protobuf.net - c#

I'm doing a voip client code with mumble in Unity3d (c# scripting) and now I'm able to successfully connect to any of mumble public server. But when I try to deserialize a UDP tunnel I get a lot of exceptions including 'invalid wiretype', 'number overflow', 'invalid field', 'endofstream', 'wrong group was ended' and bla bla... all of the at this particular line.
var udpTunnel = Serializer.DeserializeWithLengthPrefix<UDPTunnel> (_ssl, PrefixStyle.Fixed32BigEndian);
where _ssl is SslStream
Here is my complete method
nternal void ProcessTcpData ()
{
try {
var masg = IPAddress.NetworkToHostOrder (_reader.ReadInt16 ());
MessageType messageType = (MessageType)masg;
Debug.Log ("Received message type: " + messageType);
switch (messageType) {
case MessageType.Version:
_mc.RemoteVersion = Serializer.DeserializeWithLengthPrefix<Version> (_ssl,
PrefixStyle.Fixed32BigEndian);
break;
case MessageType.CryptSetup:
var cryptSetup = Serializer.DeserializeWithLengthPrefix<CryptSetup> (_ssl,
PrefixStyle.Fixed32BigEndian);
ProcessCryptSetup (cryptSetup);
break;
case MessageType.CodecVersion:
_mc.CodecVersion = Serializer.DeserializeWithLengthPrefix<CodecVersion> (_ssl,
PrefixStyle.Fixed32BigEndian);
break;
case MessageType.ChannelState:
_mc.ChannelState = Serializer.DeserializeWithLengthPrefix<ChannelState> (_ssl,
PrefixStyle.Fixed32BigEndian);
break;
case MessageType.PermissionQuery:
_mc.PermissionQuery = Serializer.DeserializeWithLengthPrefix<PermissionQuery> (_ssl,
PrefixStyle.Fixed32BigEndian);
break;
case MessageType.UserState:
_mc.UserState = Serializer.DeserializeWithLengthPrefix<UserState> (_ssl,
PrefixStyle.Fixed32BigEndian);
break;
case MessageType.ServerSync:
_mc.ServerSync = Serializer.DeserializeWithLengthPrefix<ServerSync> (_ssl,
PrefixStyle.Fixed32BigEndian);
_mc.ConnectionSetupFinished = true;
break;
case MessageType.ServerConfig:
_mc.ServerConfig = Serializer.DeserializeWithLengthPrefix<ServerConfig> (_ssl,
PrefixStyle.Fixed32BigEndian);
_validConnection = true; // handshake complete
break;
case MessageType.TextMessage:
var textMessage = Serializer.DeserializeWithLengthPrefix<TextMessage> (_ssl, PrefixStyle.Fixed32BigEndian);
break;
case MessageType.UDPTunnel:
if (_validConnection) {
var udpTunnel = Serializer.DeserializeWithLengthPrefix<UDPTunnel> (_ssl, PrefixStyle.Fixed32BigEndian);
}
break;
case MessageType.Ping:
var ping = Serializer.DeserializeWithLengthPrefix<MumbleProto.Ping> (_ssl, PrefixStyle.Fixed32BigEndian);
Debug.Log ("Received ping: " + ping.timestamp + ", udp: " + ping.udp_packets + ", tcp:" +
ping.tcp_packets);
break;
case MessageType.Reject:
var reject = Serializer.DeserializeWithLengthPrefix<Reject> (_ssl,
PrefixStyle.Fixed32BigEndian);
_validConnection = false;
_errorCallback ("Mumble server reject: " + reject.reason, true);
break;
default:
_errorCallback ("Message type " + messageType + " not implemented", true);
break;
}
if (_validConnection) {
Debug.Log ("Handshake Complete:\tconnection is valid");
}
} catch (Exception ex) {
Debug.LogException (ex);
}
}
_reader is a BinaryReader

I've got past this by using
var size = IPAddress.NetworkToHostOrder (_reader.ReadInt32 ());
var udpTunnel = new UDPTunnel { packet = _reader.ReadBytes(size) };
Now I don't know why Deserializewithlengthprefix was not working because as I understand, these lines are doing the same thing.

Related

api controller using AspNetCore.Reporting thows System.FormatException: 'The header contains invalid values at index 0

This api controller is used to return a pdf stream to display in an html object tag
using AspNetCore.Reporting;
using Microsoft.AspNetCore.Mvc;
[HttpGet, Route("ProcedureRangeForm")]
public IActionResult ProcedureRangeForm(string procedureRangeId, byte procedureTypeId)
{
int extension = 1;
var _reportPath = "";
switch (procedureRangeId)
{
case "1":
_reportPath = #"Reports\ProcedureRangeForm1.rdlc";
break;
case "2":
_reportPath = #"Reports\ProcedureRangeForm2.rdlc";
break;
case "3":
_reportPath = #"Reports\ProcedureRangeForm3.rdlc";
break;
default:
// code block
break;
}
//Employee employee = _context.Employees.FirstOrDefault(x => x.Id == "41")!;
ProcedureType procedureType = _context.ProcedureTypes.FirstOrDefault(x => x.Id == procedureTypeId);
//RelationDegree relationDegree = _context.RelationDegrees.FirstOrDefault(x => x.Id == 1)!;
var reportParams1 = new Dictionary<string, string>();
var reportParams2 = new Dictionary<string, string>();
var reportParams3 = new Dictionary<string, string>();
reportParams1.Add("UnitCode", "UnitCode");
reportParams1.Add("ProcedureType", procedureType!.Name!);
reportParams2.Add("ProcedureType", procedureType!.Name!);
reportParams3.Add("ProcedureType", procedureType!.Name!);
//reportParams1.Add("Attachments", "");
LocalReport localReport = new LocalReport(_reportPath);
FileContentResult fileContentResult;
MemoryStream memory = new();
try
{
ReportResult result = null!;
switch (procedureRangeId)
{
case "1":
result = localReport.Execute(RenderType.Pdf, extension, parameters: reportParams1);
break;
case "2":
result = localReport.Execute(RenderType.Pdf, extension, parameters: reportParams2);
break;
case "3":
result = localReport.Execute(RenderType.Pdf, extension, parameters: reportParams3);
break;
default:
// code block
break;
}
byte[] file = result.MainStream;
fileContentResult = new FileContentResult(file, "application/pdf");
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
return Content(HttpStatusCode.InternalServerError.ToString(), e.Message);
}
finally
{
}
return fileContentResult;
}
I want to call this api more than once with varient parameters. when i call once to display ProcedureRangeForm1.rdlc it run successfully , but when i call again to display ProcedureRangeForm2.rdlc throw this exception
System.FormatException: 'The header contains invalid values at index 0: 'An error occurred during local report processing.;The definition of the report 'Reports\ProcedureRangeForm1.rdl' is invalid. An unexpected error occurred in Report Processing. The process cannot access the file 'hdsktzjh.err' because it is being used by another process.''
After a lot of research, I found a solution to my question:
First, I used nuget package Tmds.ExecFunction by Execute a function in a separate process
as in this link
But I didn't get what I wanted
And then I replaced the library AspNetCore.Reporting by ReportViewerCore.NETCore
as in this link
the problem solved as this code
using Microsoft.Reporting.NETCore;
[Route("api/[controller]")]
[ApiController]
public class ProcedureRangeFormsController : ControllerBase
{
private readonly HousingDbContext _context;
public ProcedureRangeFormsController(HousingDbContext context)
{
_context = context;
}
// GET api/values
[HttpGet, Route("ProcedureRangeForm/{procedureRangeId}/{procedureTypeId}")]
public IActionResult ProcedureRangeForm(string procedureRangeId, string procedureTypeId)
{
var reportPath = "";
switch (procedureRangeId)
{
case "1":
reportPath = "TaxHousing.Reports.ProcedureRangeForm1.rdlc";
break;
case "2":
reportPath = "TaxHousing.Reports.ProcedureRangeForm2.rdlc";
break;
case "3":
reportPath = "TaxHousing.Reports.ProcedureRangeForm3.rdlc";
break;
default:
// code block
break;
}
using var rs = Assembly.GetExecutingAssembly().GetManifestResourceStream(reportPath);
var localReport = new Microsoft.Reporting.NETCore.LocalReport();
localReport.LoadReportDefinition(rs);
var reportParams1 = new[] {
new ReportParameter("ProcedureType", "ProcedureType1"),
new ReportParameter("UnitCode", "UnitCode1")
};
var reportParams2 = new[] {
new ReportParameter("ProcedureType", "ProcedureType2")
};
var reportParams3 = new[] {
new ReportParameter("ProcedureType", "ProcedureType3")
};
byte[] file = null;
switch (procedureRangeId)
{
case "1":
localReport.SetParameters(reportParams1);
break;
case "2":
localReport.SetParameters(reportParams2);
break;
case "3":
localReport.SetParameters(reportParams3);
break;
default:
// code block
break;
}
try
{
file = localReport.Render("PDF");
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
return Content(HttpStatusCode.InternalServerError.ToString(), e.Message);
}
return new FileContentResult(file, "application/pdf");
}
}

message being consumed even if the consumer is down RabbitMQ

I am writing async communication between services so if one goes down the request can't be stopped
so I am doing this scenario
I am turning off my consumer and sending message through the producer
I get a response that the message has been sent successfully
but when I run my consumer on again no message in the queue
Note :
when I don't turn off my consumer i can get my message and consume it
this is my producer code
var factory = new ConnectionFactory() { HostName = "host.docker.internal" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "UserRequestExch", type: ExchangeType.Direct);
UserInfo userInfo = new UserInfo();
userInfo.UserID = GetCurrentUserID();
userInfo.JWT=GetCurrentUserToken();
var mess = System.Text.Json.JsonSerializer.Serialize(userInfo);
var body = Encoding.UTF8.GetBytes(mess);
string RoueKey = "";
switch (Int32.Parse(dataObject["PostponementID"].ToString()))
{
case 1:
RoueKey = "AlonePostponement";
break;
case 2:
RoueKey = "BrotherInServicePostponement";
break;
case 3:
RoueKey = "CashAllowance";
break;
case 4:
RoueKey = "CashAllowancLessThan42";
break;
case 5:
RoueKey = "FixedServiceAllowance";
break;
case 6:
RoueKey = "ObligatoryService";
break;
case 7:
RoueKey = "PostponementOfConvicts";
break;
case 8:
RoueKey = "SchoolPostponement";
break;
case 9:
RoueKey = "TravelApproval";
break;
default:
return NotFound();
}
channel.BasicPublish("UserRequestExch", RoueKey, null, body);
return Ok("The request has been received and is now being processed");
my consumer code :
factory = new ConnectionFactory() { HostName = "host.docker.internal" };
connection = factory.CreateConnection();
channel = connection.CreateModel();
channel.ExchangeDeclare(exchange: "UserRequestExch", ExchangeType.Direct);
var queName = channel.QueueDeclare().QueueName;
channel.QueueBind(queue: queName, exchange: "UserRequestExch", routingKey: "TravelApproval");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var recbody = ea.Body.ToArray();
var recmess = Encoding.UTF8.GetString(recbody);
UserInfo userInfo = JsonSerializer.Deserialize<UserInfo>(recmess);
var User = _context.TravelApprovalDb.Where(x => x.UserID == userInfo.UserID).FirstOrDefault();
if (User == null)
{
int ReqStatuesID = InsertRequestToDB(userInfo.UserID);
SendToExternalAPI(userInfo.JWT, ReqStatuesID);
}
else
{
if (User.DateOfEnd.DateTime > DateTime.Now)
{
int ReqStatuesID = InsertRequestToDB(userInfo.UserID);
SendToExternalAPI(userInfo.JWT, ReqStatuesID);
}
}
channel.BasicAck(deliveryTag:ea.DeliveryTag,multiple:true);
};
channel.BasicConsume(queue: queName, consumer: consumer);
System.Console.Read();
I have applied persistent volume to the rappitMQ in docker-compose
volumes:
- rabbitmq:/var/lib/rabbitmq
or
- ~/.docker-conf/rabbitmq/data/:/var/lib/rabbitmq/
- ~/.docker-conf/rabbitmq/log/:/var/log/rabbitmq
I removed auto ack and put
channel.BasicAck(deliveryTag:ea.DeliveryTag,multiple:true);
but nothing happened

EDITTEXT add data to a table from a previously loaded from a stored procedure in C#

I need add to a edittext data previously loaded from stored procedure. But only add the first row of the column of name "Respuestas" the id of "Preguntas" is id cod_pregunta. But I need that the other "respuestas" too add to next edittext this is the code.
public void mostrarDatos(int posicion)
{
CotiBenev = tablaVerificacionAnexosV.Rows[posicion]["Usuario"].ToString();
Batchid = tablaVerificacionAnexosV.Rows[posicion]["iBatchId"].ToString();
primerApellido = tablaVerificacionAnexosV.Rows[posicion]["Primer apellido"].ToString();
segundoApellido = tablaVerificacionAnexosV.Rows[posicion]["Segundo apellido"].ToString();
primerNombre = tablaVerificacionAnexosV.Rows[posicion]["Primer Nombre"].ToString();
segundoNombre = tablaVerificacionAnexosV.Rows[posicion]["Segundo Nombre"].ToString();
cons_pregunta = tablaVerificacionAnexosV.Rows[posicion]["consecutivo pregunta"].ToString();
cod_pregunta = tablaVerificacionAnexosV.Rows[posicion]["Codigo pregunta"].ToString();
cod_aportante = tablaVerificacionAnexosV.Rows[posicion]["Codigo aportante"].ToString();
Respuesta = tablaVerificacionAnexosV.Rows[posicion]["Respuesta"].ToString();
rutaTapa = tablaVerificacionAnexosV.Rows[posicion]["Ruta Tapa"].ToString();
rutaAnexo = tablaVerificacionAnexosV.Rows[posicion]["Ruta Anexo"].ToString();
try
{
imagenTapa = new Bitmap(rutaTapa);
}
catch (Exception e)
{
botonSiguiente();
}
try
{
imagenAnexo = new Bitmap(rutaAnexo);
}
catch (Exception e)
{
botonSiguiente();
}
// textBoxCantidadRegistrosV.Text = cantidadRegistros;
//textBoxNumeroRegistroV.Text = (posicion + 1) + "";
textBoxCotiBene.Text = CotiBenev;
// activarCamposValidacionAnexos();
pictureBoxTapa.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBoxAnexo.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBoxTapa.Image = (Image)imagenTapa;
pictureBoxAnexo.Image = (Image)imagenAnexo;
// textBoxValorTapaV.Focus();
textBoxCotiBene.Text = CotiBenev + ": " + primerApellido + segundoApellido + primerNombre + segundoNombre;
string caseSwitch = cod_pregunta;
switch (caseSwitch)
{
case "1.1":
textBoxPreg_1_1.Text = Respuesta;
break;
case "1.2":
textBoxPreg_1_2.Text = Respuesta;
break;
case "1.3":
textBoxPreg_1_3.Text = Respuesta;
break;
case "1.4":
textBoxPreg_1_4.Text = Respuesta;
break;
case "1.5":
textBoxPreg_1_5.Text = Respuesta;
break;
case "1.6":
textBoxPreg_1_6.Text = Respuesta;
break;
case "1.7":
textBoxPreg_1_7.Text = Respuesta;
break;
case "1.8":
textBoxPreg_1_8.Text = Respuesta;
break;
case "2.1":
textBoxPreg_2_1.Text = Respuesta;
break;
case "2.2":
textBoxPreg_2_2.Text = Respuesta;
break;
case "2.3":
textBoxPreg_2_3.Text = Respuesta;
break;
case "2.4":
textBoxPreg_2_4.Text = Respuesta;
break;
case "2.5":
textBoxPreg_2_5.Text = Respuesta;
break;
case "2.6":
textBoxPreg_2_6.Text = Respuesta;
break;
case "2.7":
textBoxPreg_2_7.Text = Respuesta;
break;
case "2.8":
textBoxPreg_2_8.Text = Respuesta;
break;
case "2.9":
textBoxPreg_2_9.Text = Respuesta;
break;
case "2.10":
textBoxPreg_2_10.Text = Respuesta;
break;
case "2.11":
textBoxPreg_2_11.Text = Respuesta;
break;
case "2.12":
textBoxPreg_2_12.Text = Respuesta;
break;
case "2.13":
textBoxPreg_2_13.Text = Respuesta;
break;
case "2.14":
textBoxPreg_2_14.Text = Respuesta;
break;
case "2.15":
textBoxPreg_2_15.Text = Respuesta;
break;
case "2.16":
textBoxPreg_2_16.Text = Respuesta;
break;
case "2.17":
textBoxPreg_2_17.Text = Respuesta;
break;
case "2.18":
textBoxPreg_2_18.Text = Respuesta;
break;
case "2.19":
textBoxPreg_2_19.Text = Respuesta;
break;
case "2.20":
textBoxPreg_2_20.Text = Respuesta;
break;
case "3.1":
textBoxPreg_3_1.Text = Respuesta;
break;
case "3.2":
textBoxPreg_3_2.Text = Respuesta;
break;
case "3.3":
textBoxPreg_3_3.Text = Respuesta;
break;
case "3.4":
textBoxPreg_3_4.Text = Respuesta;
break;
case "3.5":
textBoxPreg_3_5.Text = Respuesta;
break;
case "4.1":
textBoxPreg_4.Text = Respuesta;
break;
default:
Console.WriteLine("No existe esa pregunta");
break;
}
}

Remove some parts in FastReport using C#

I am using FastReport in ASP.net MVC. I wrote some code for removing the report title when exporting to Excel. It works properly. But sometimes the report is shown and after that export method is called; in this case when I push the Next Page button in FastReport's toolbar, I see that the report title was removed. I wrote this:
FastReport.Utils.Config.WebMode = true;
ExportBase export = null;
var webReportExport = new WebReport();
//keep werreport object in tempdata in first loading of report for using it to export later
webReportExport.Report = TempData["WebReport"] as FastReport.Report;
webReportExport.Report.FindObject("PageHeader1").Delete();
webReportExport.Report.FindObject("PageFooter1").Delete();
TempData.Keep("WebReport");
ViewBag.WebReport = TempData["WebReport"] as FastReport.Report;
if (webReportExport.Report.Prepare())
{
switch (exportType)
{
case "pdf": export = new FastReport.Export.Pdf.PDFExport(); break;
case "excel": export = new FastReport.Export.OoXML.Excel2007Export() ; break;
case "word": export = new FastReport.Export.OoXML.Word2007Export(); break;
case "rtf": export = new FastReport.Export.RichText.RTFExport(); break;
default:
break;
}
export.ShowProgress = false;
MemoryStream strm = new MemoryStream();
webReportExport.Report.Export(export, strm);
webReportExport.Dispose();
export.Dispose();
strm.Position = 0;
var currentDate = PersianDate.Parse(PersianDateConverter.ToPersianDate(DateTime.Now).ToString()).ToString("swt");
var reportName = TempData["reportName"] + currentDate;
switch (exportType)
{
case "pdf": return File(strm, "application/pdf", reportName+".pdf"); break;
case "excel": return File(strm, "application/ms-excel", reportName+".xlsx"); break;
case "word": return File(strm, "application/vnd.openxmlformats-officedocument.wordprocessingml.document",reportName+ ".docx"); break;
case "rtf": return File(strm, "application/rtf", reportName+".rtf"); break;
default:
break;
}
}
return null;

Android - Display sim and phone contacts

I trying to get sim and phone contacts. I succeed with phone contacts (phone contacts & synced contacts) but with sim contacts I fail...
I tried a lot of URI but no one work so I thought that you guys can help me.
private void Click (object sender , EventArgs eventArgs)
{
Intent intent = new Intent (Intent.ActionPick , Android.Net.Uri.Parse ("content://contacts"));
intent.SetType (ContactsContract.Contacts.ContentType);
StartActivityForResult (intent , SMS_Send.PICK_NUMAR);
}
protected override void OnActivityResult (int requestCode, Result resultCode, Intent data)
{
if ((requestCode == SMS_Send.PICK_NUMAR) && (resultCode == Result.Ok) && (data != null)) {
Android.Net.Uri uriContact = data.Data;
ICursor cursor = ManagedQuery (uriContact,null,null,null,null);
if (cursor.MoveToFirst ()) {
string NUME_CONTACT = cursor.GetString (cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
string NUMAR_TELEFON = getPhoneNumber (NUME_CONTACT);
ISharedPreferences NumeNumar = GetPreferences (FileCreationMode.Private);
ISharedPreferencesEditor Editor = NumeNumar.Edit ();
Editor.PutString ("NUMAR_TELEFON" , NUMAR_TELEFON);
Editor.PutString ("NUME_CONTACT" , NUME_CONTACT);
Editor.Apply ();
}
}
}
public string getPhoneNumber(string name)
{
string ret = null;
string selection = ContactsContract.Contacts.InterfaceConsts.DisplayName +" like '%" + name +"%'";
string[] projection = new string[] { ContactsContract.CommonDataKinds.Phone.Number };
ICursor c = ManagedQuery (ContactsContract.CommonDataKinds.Phone.ContentUri,projection,selection,null,null);
if (c.MoveToFirst ()) {
ret = c.GetString (0);
}
return ret;
}
Thank you in advance!
This work for me !
public class MyContacts {
public static String getContacts(Context context){
StringBuffer outBuffer = new StringBuffer();
outBuffer.append("");
String strOrder = ContactsContract.Contacts.DISPLAY_NAME + " ASC";
ContentResolver cr = context.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, strOrder);
outBuffer.append("<contacts>");
if (cur.getCount() > 0 ) {
while (cur.moveToNext() ) {
outBuffer.append("<contact>").
append("<fullname>").
append(ServerData.getStartcdataxml() + cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ServerData.getEndcdataxml()).
append("</fullname>").
append("<id>").
append(cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID))).
append("</id>").
append("</contact>");
}
cur.close();
}
outBuffer.append("</contacts>");
return outBuffer.toString();
}
public static String getContactByID(Context context,String contact_id){
StringBuffer outBuffer = new StringBuffer();
outBuffer.append("");
//Long inizioLettura = System.currentTimeMillis();
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
Uri AdressCONTENT_URI = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI;
String AdressCONTACT_ID = ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID;
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToNext();
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
outBuffer.append("<contact>");
if (hasPhoneNumber > 0) {
outBuffer.append("<phonenumbers>");
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
if(phoneCursor != null)
while (phoneCursor.moveToNext()) {
outBuffer.append("<phonenumber>").
append("<number>").
append(phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER))).
append("</number>");
if(phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)) != null){
switch (Integer.valueOf(phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)))) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:outBuffer.append("<type>").append("home").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:outBuffer.append("<type>").append("mobile").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:outBuffer.append("<type>").append("work").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK:outBuffer.append("<type>").append("work fax").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME:outBuffer.append("<type>").append("home fax").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_PAGER:outBuffer.append("<type>").append("pager").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:outBuffer.append("<type>").append("other").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM:outBuffer.append("<type>").append("custom").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK:outBuffer.append("<type>").append("callback").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_CAR:outBuffer.append("<type>").append("car").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN:outBuffer.append("<type>").append("company main").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ISDN:outBuffer.append("<type>").append("ISDN").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MAIN:outBuffer.append("<type>").append("main").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT:outBuffer.append("<type>").append("assistant").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MMS:outBuffer.append("<type>").append("mms").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX:outBuffer.append("<type>").append("other fax").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_RADIO:outBuffer.append("<type>").append("radio").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_TTY_TDD:outBuffer.append("<type>").append("TTY TDD").append("</type>"); break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER:outBuffer.append("<type>").append("workpager").append("</type>"); break;
}
outBuffer.append("</phonenumber>");
}
}
outBuffer.append("</phonenumbers>");
phoneCursor.close();
}
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
outBuffer.append("<emails>");
if(emailCursor != null)
while (emailCursor.moveToNext()) {
outBuffer.append("<infoemail>").
append("<email>").
append(ServerData.getStartcdataxml() + emailCursor.getString(emailCursor.getColumnIndex(DATA)) + ServerData.getEndcdataxml()).
append("</email>");
if(emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE))!= null){
switch (Integer.valueOf(emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)))) {
case ContactsContract.CommonDataKinds.Email.TYPE_HOME:outBuffer.append("<type>").append("home").append("</type>"); break;
case ContactsContract.CommonDataKinds.Email.TYPE_MOBILE:outBuffer.append("<type>").append("mobile").append("</type>"); break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK:outBuffer.append("<type>").append("work").append("</type>"); break;
case ContactsContract.CommonDataKinds.Email.TYPE_OTHER:outBuffer.append("<type>").append("other").append("</type>"); break;
case ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM:outBuffer.append("<type>").append("custom").append("</type>"); break;
}
}
outBuffer.append("</infoemail>");
}
outBuffer.append("</emails>");
emailCursor.close();
Cursor adressCursor = contentResolver.query(AdressCONTENT_URI, null, AdressCONTACT_ID+ " = ?", new String[] { contact_id }, null);
outBuffer.append("<addresses>");
if(adressCursor!=null)
while (adressCursor.moveToNext()) {
outBuffer.append("<address>").
append("<street>").
append(ServerData.getStartcdataxml() + adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)) + ServerData.getEndcdataxml()).
append("</street>").
append("<city>").
append(ServerData.getStartcdataxml() + adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)) + ServerData.getEndcdataxml()).
append("</city>").
append("<country>").
append(ServerData.getStartcdataxml() + adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY)) + ServerData.getEndcdataxml()).
append("</country>").
append("<postalcode>").
append(ServerData.getStartcdataxml() + adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)) + ServerData.getEndcdataxml()).
append("</postalcode>").
append("<neighborhood>").
append(ServerData.getStartcdataxml() + adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD)) + ServerData.getEndcdataxml()).
append("</neighborhood>");
if(adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE)) != null){
switch (Integer.valueOf(adressCursor.getString(adressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE)))) {
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME:outBuffer.append("<type>").append("home").append("</type>"); break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK:outBuffer.append("<type>").append("work").append("</type>"); break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER:outBuffer.append("<type>").append("other").append("</type>"); break;
case ContactsContract.CommonDataKinds.StructuredPostal.TYPE_CUSTOM:outBuffer.append("<type>").append("custom").append("</type>"); break;
}
}
outBuffer.append("</address>");
}
outBuffer.append("</addresses>");
Cursor orgCursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?",new String[]{contact_id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}, null);
if(orgCursor!=null)
while (orgCursor.moveToNext()) {
outBuffer.append("<organization>").
append("<company>").
append(ServerData.getStartcdataxml() + orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY)) + ServerData.getEndcdataxml()).
append("</company>").
append("<title>").
append(ServerData.getStartcdataxml() + orgCursor.getString(orgCursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE)) + ServerData.getEndcdataxml()).
append("</title>").
append("</organization>");
}
orgCursor.close();
outBuffer.append("</contact>");
adressCursor.close();
}
return outBuffer.toString();
}
}
Finally I found the problem .. I had to overwrite the intent type with:
intent.SetType (ContactsContract.CommonDataKinds.Phone.ContentType);

Categories