webservice method repeats itself more than once when clicking on button - web-services

i have created an android app via xamarin.android. i have a recyclerview that gets its data from an asmx webservice. the recyclerview is filled correctly. i also have a floatingActionButton that deletes rows from the recyclerview, and floatingActionButton save that saves the data that is in the recyclerview in a database table in sqlserver. this is the code:
private void Presave_Click(object sender, EventArgs e)
{
if (laborers_dt_total.Rows.Count == 0)
{
Toast.MakeText(this.Context, "select the laborers that you need!", ToastLength.Long).Show();
}
else
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
supp_status = 1;
}
}
private void Ws_get_labors_of_todayCompleted(object sender, WSattendane1.get_labors_of_todayCompletedEventArgs e)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this.Context);
List<String> repeated_laborers = new List<String>();
DataTable labors_today = new DataTable();
labors_today = e.Result;
try
{
for(int i=0;i<laborers_dt_total.Rows.Count;i++)
{
for (int j = 0; j < labors_today.Rows.Count; j++)
{
if(laborers_dt_total.Rows[i]["laborerCode"].ToString() == labors_today.Rows[j]["laborerCode"].ToString())
{
repeated_laborers.Add(laborers_dt_total.Rows[i]["laborerName"].ToString());
}
}
}
string message = "";
if (repeated_laborers.Count > 0)
{
for (int i = 0; i < repeated_laborers.Count; i++)
{
message = message + repeated_laborers[i] + ", ";
}
alert.SetTitle(Resources.GetText(Resource.String.repeated_names));
alert.SetMessage(message + Resources.GetText(Resource.String.exits_else_where));
alert.SetPositiveButton(Resources.GetText(Resource.String.ok), (senderAlert, args) =>
{
_dialog.Dismiss();
});
_dialog = alert.Create();
_dialog.Show();
}
else if (repeated_laborers.Count==0)
{
Toast.MakeText(context, "uuydsa", ToastLength.Short).Show();
ws.presave_scheduleAsync(laborers_dt_total, user.sch_code, DateTime.Now.Hour.ToString(), project_code, int.Parse(phase_order), "SCH", "SCH", "", userid, int.Parse(department_code), int.Parse(department_code), 0, supp_status, user.create_update);
ws.presave_scheduleCompleted += Ws_presave_scheduleCompleted;
presave.ClearFocus();
}
}
catch (System.Reflection.TargetInvocationException exp)
{
System.Net.WebException exception = new System.Net.WebException("can't reach server", exp.InnerException);
Toast.MakeText(this.Context, exp.InnerException.Message, ToastLength.Long).Show();
Context context = this.Context;
alert.SetTitle("Connection failed");
alert.SetMessage("Please, Check your Internet Connection!");
alert.SetPositiveButton("Retry", (senderAlert, args) =>
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
alert.Dispose();
});
_dialog = alert.Create();
_dialog.Show();
}
}
the problem is that on each click on presave, the function ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted; repeats itself "number of presave clicks" times. i removed all the code inside it and added just a toast. on each click, the toast is displayed "number of presave clicks" times. i click it for the first time, the toast appears once, then i click it again, the toast repeats itself twice, and so on. what is the problem? thanks in advance.

private void Presave_Click(object sender, EventArgs e)
{
if (laborers_dt_total.Rows.Count == 0)
{
Toast.MakeText(this.Context, "select the laborers that you need!", ToastLength.Long).Show();
}
else
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
supp_status = 1;
}
}
From your code ,we can find there is an if statement,if the first condition laborers_dt_total.Rows.Count == 0 does not satisfy the condition,then it will go to execute the following code:
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
supp_status = 1;
}
So, if the condition laborers_dt_total.Rows.Count == 0 is not always satisfied, it is nomal on each click on presave, the function ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted; repeats itself "number of presave clicks" times.
In summary, you can recheck the value of laborers_dt_total.Rows.Count .
In addition, if you don't want to execute event Presave_Clickafter your first clicking this button, you can use Xamarin.Forms ActivityIndicator to achieve this. which displays an animation to show that the application is engaged in a lengthy activity.

I would just change:
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
supp_status = 1;
}
to:
{
ws.get_labors_of_todayAsync(0, "", 3);
ws.get_labors_of_todayCompleted -= Ws_get_labors_of_todayCompleted;
ws.get_labors_of_todayCompleted += Ws_get_labors_of_todayCompleted;
supp_status = 1;
}
This will ensure your don't keep accumulating method calls.

Related

Update list in Kotlin

So here is my Data Class
data class Bestellung (var id:Int = 0, var anzahl:Int = 1, var speise:String? = null)
my List
private var bestellungList = ArrayList<Bestellung>()
Trying to update the list if "speise" equals "s" but its not working without any error..
if (bestellungList.contains(Bestellung(speise = s))) {
var i = bestellungList.indexOf(Bestellung(speise = s))
bestellungList.set(i, Bestellung(anzahl = +1))
problem is contains
pls try this if you want to check first:
if(bestellungList.any{ it.speise == "s" }) {
// do add logic
} else {
// do something else
}
The problem is your contains part. Replace it like this
val index = bestellungList.indexOfFirst {
it.speise == s
}
if (index >= 0) {
bestellungList[index] = Bestellung(anzahl = +1)
}
if (bestellungList.any{ it.speise == "s" }) {
bestellungList.addAll(Bestellung(anzahl = +1))
} else {
// handle else statement also
}

Extract pdf document with multi page

I am using Amazon's Textract service for extracting tables, Forms from pdf documnets.
The example provided at Github here is working for single page document only. But as per demo provided by AWS they are able to extract multi page pdf docs as well.
As per documentation we have to call same service for multi pages as well. But it is not working for me.
All the examples provided by them are either in python or java.
I am doing it in dotnet core.
Any help?
Here is my code.
public IActionResult FileExtract(string filename)
{
try
{
string lineText = "";
string wordText = "";
string fieldsText = "";
string fieldsText2 = "";
string tableText = "";
// Extracting file in below code.
var textractAnalysisClient = BuildTextractClient();
var document = PrepareDocument(textractAnalysisClient, "FORMS", filename);
document.Pages.ForEach(page =>
{
page.Lines.ForEach(line =>
{
lineText += "<button class='rawlabel'>" + line.Text + "</button>";
line.Words.ForEach(word =>
{
wordText += word.Text;
});
});
page.Form.Fields.ForEach(f =>
{
fieldsText += "<div><h5>" + f.Key + "</h5><p style='background-color:lightgray;width: 200px;padding: 6px;'>"
+ f.Value + "</p></div>";
});
var key = "Phone Number:";
var field = page.Form.GetFieldByKey(key);
if (field != null)
{
fieldsText2 += "Key: " + field.Key + " | Value: " + field.Value;
}
});
tableText = "<table id='customers'>";
document = PrepareDocument(textractAnalysisClient, "TABLES", filename);
document.Pages.ForEach(page =>
{
page.Tables.ForEach(table =>
{
var r = 0;
table.Rows.ForEach(row =>
{
r++;
tableText += "<tr>";
var c = 0;
row.Cells.ForEach(cell =>
{
c++;
tableText += "<td>";
tableText += cell.Text + "</td>";
});
tableText += "</tr>";
});
});
});
tableText += "</table>";
objJsonResponse.fieldsText = fieldsText;
objJsonResponse.fieldsText2 = fieldsText2;
objJsonResponse.lineText = lineText;
objJsonResponse.tableText = tableText;
objJsonResponse.wordText = wordText;
objJsonResponse.responsecode = 1;
return Json(objJsonResponse);
}
catch (Exception ex)
{
this.objJsonResponse.responsecode = -1;
this.objJsonResponse.error = "failed";
return Json(this.objJsonResponse);
}
}
static TextractTextAnalysisService BuildTextractClient()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var awsOptions = builder.GetAWSOptions();
return new TextractTextAnalysisService(awsOptions.CreateServiceClient<IAmazonTextract>());
}
static TextractDocument PrepareDocument(TextractTextAnalysisService textractAnalysisClient, string type, string FormFile)
{
var task = textractAnalysisClient.StartDocumentAnalysis(BucketName, FormFile, type);
var jobId = task.Result;
textractAnalysisClient.WaitForJobCompletion(jobId);
var results = textractAnalysisClient.GetJobResults(jobId);
return new TextractDocument(results);
}

How to pass multipart file data to a web service

I wanna do something like this.
1.Uploading a file from a jsp in multipart
2.Calling a servlet
3.In dopost of that servlet i wanna call a webservice which takes all the params passed by jsp to servlet along with the multipart data.
dopost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response){
webserviceMethod(request,response);
}
I'm stuck on third point where I can set all request params to webservice method. But I don't know how to pass multipart file data to that websevice. I failed to do so. How can i do that part??
Have a look at that jquery plugin:
http://jquery.malsup.com/form/
I'm also using this in my Application together with a java servlet:
uploadImage: function (e) {
var self = this;
self.ignoreDrag(e);
if ($('#feed_imageUploader').find('input').hasClass('error')) {
return;
}
//cant put this in an model - ajaxSubmit has no done callback
$('#img_uploaded h1').text(polyglot.t('iview.loading'));
$('#feed_imageUploader').ajaxSubmit({
target: '#img_uploaded',
type: "POST",
url: path.apiPath + 'item.uploadImg/' + self.itemId + '/' + token,
dataType: "text",
async: true,
success: function () {
self.afterUploadImage();
}
});
},
afterUploadImage: function () {
var self = this;
self.changed = true;
var xFactorItemImage = 0;
var yFactorItemImage = 0;
var randomnumber = Math.floor(Math.random() * 10100000);
$('#img_uploaded').html("<img src=\"" + path.tempImage + userId + "_" + self.itemId + ".jpg?id=" + randomnumber + "\" style=\"display:none\" id=\"cropPhoto_uploaded\">");
var theImage = new Image();
var cropPhoto = $('#cropPhoto_uploaded');
theImage.src = cropPhoto.attr("src");
var widthPhoto = 0;
var heightPhoto = 0;
var NwidthPhoto = 0;
var NheightPhoto = 0;
$(theImage).load(function () {
$('#img_uploaded h1').empty();
$('#additemimage').hide();
NwidthPhoto = theImage.width;
NheightPhoto = theImage.height;
cropPhoto.css({
maxHeight: $('#img_uploaded').height() + 'px',
maxWidth: $('#img_uploaded').width() + 'px'
});
cropPhoto.show();
$('#addimage_upload').fadeIn(aSpeed.middle);
widthPhoto = cropPhoto.width();
heightPhoto = cropPhoto.height();
xFactorItemImage = NwidthPhoto / widthPhoto;
yFactorItemImage = NheightPhoto / heightPhoto;
cropPhoto.Jcrop({
setSelect: helper.getMiddleSelectionOfImage(widthPhoto, heightPhoto, widthPhoto, heightPhoto),
bgOpacity: 0.3,
onChange: showItemImageCoords,
onSelect: showItemImageCoords
});
});
function showItemImageCoords(c) {
$('#x111').val(parseInt(xFactorItemImage * c.x));
$('#y111').val(parseInt(yFactorItemImage * c.y));
$('#x222').val(parseInt(xFactorItemImage * c.w));
$('#y222').val(parseInt(yFactorItemImage * c.h));
}
},
And the servlet part:
public void UploadImage(HttpServletRequest request, String filename, String folder,String bucketname) {
File file;
PropertyReader mainconf = new PropertyReader();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items ;
mainconf.getProb("conf/MainConfig.properties");
s3 s3=new s3();
try {
items = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = items.iterator();
//Iterate through the items
String finalPath = "";
FileItem fi;
while (i.hasNext()) {
fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String your_os = System.getProperty("os.name").toLowerCase();
String workingDir = "images";
finalPath = mainconf.read("imagePath");
if (your_os.indexOf("win") >= 0) {
finalPath = finalPath + workingDir + "\\" + folder + "\\";
} else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
finalPath = finalPath + workingDir + "/" + folder + "/";
} else {
finalPath = finalPath + workingDir + "{others}" + folder + "{others}";
}
file = new File(finalPath + filename + ".jpg");
fi.write(file);
s3.writeFile(bucketname, file, filename+".jpg");
file.delete();
}
break;
}
} catch (Exception ex) {
Logger.getLogger(UploadItemImage.class.getName()).log(Level.SEVERE, null, ex);
}
}

How to sync WebService operation in silverlight?

I am now on a project regarding controlling devices by using silverlight and web service(asmx page). The project flows like below:
pressing the button on the silverlight UI, it will send out a package by using socket to the middlewire. Then middlewire will accept the package and deconstructe it and return back another package to silverlight UI. I am using below code to load the button state, which will trigger database query:
private ButtonStateModel _buttonStateModel = new ButtonStateModel() { BtnOneImage = "Skins/images/flag/QU.png", BtnOneVisible = Visibility.Visible, BtnTwoVisible = Visibility.Collapsed };
public ButtonStateModel ButtonStateModel
{
get
{
ButtonStateModel btnState = null;
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
});
return btnState;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
Now the problem is, whenever I load the silverlight app, the button on the UI can't load its state correctly. I know the reason is because that the GetPR function is from webservice(asmx), it's very oddly that I can't do sync operation by using AutoResetEvent in silverlight generated client code:
public void GetPR(string rtuID, string devID, Action<List<BusControlPR>> action)
{
ServiceSoapClient proxy = new ServiceSoapClient();
proxy.GetPRAsync(rtuID, devID);
proxy.GetPRCompleted += (sender, args) =>
{
//I cannt do Sync Operation Here by using AutoResetEvent.
if (action != null)
action(args.Result.ToList());
};
}
I am using webservice (asmx page) instead of WCF ria service.
Above problem is what i meet, Anyone can give me some light?
The "GetPR" method is still running asynchronously, so the "ButtonStateModel" getter will return null immediately (the "completed" action will then have no effect). And, you do not want to use any kind of blocking inside your getters, as that will block the UI. Instead, you should put the "GetPR" in the initialization, and use the to set the "ButtonStateModel" property to the appropriate value:
public class TheViewModel
{
public ButtonStateModel ButtonStateModel
{
get
{
return _buttonStateModel;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
public TheViewModel()
{
Initialize();
}
private void Initialize()
{
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
ButtonStateModel btnState = null;
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
ButtonStateModel = btnState;
});
}
}

How to Retrieve News Feed using Facebook Graph API.?

I am working on WPF application and I want to retrieve News Feed using facebook Graph API so how I can access it also convert into serialize.!
Thank you.
You're gonna use Facebook.dll u can download it using Package Manager in Visual studio if u are using C# for example
NuGet Package here..
and code may look like this
public List<string> Facebook(string query)
{
// Facebook.FacebookAPI api = new FacebookAPI();
List<string> list = new List<string>();
string[] arr = new string[5];
string result = null;
FacebookAPI api = new FacebookAPI(token);
// query is ur search criteria
JSONObject q = api.Get("https://graph.facebook.com/search?q="+query+"&type=post");
foreach (JSONObject item in q.Dictionary["data"].Array)
{
if (item.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> jso in item.Dictionary)
{
if (jso.Key == "message"/* || jso.Key == "name" || jso.Key == "description" || jso.Key == "link"*/)
{
for (int i = 0; i < 5; i++)
{
arr[i] = jso.Value.String;
}
list.Add (jso.Value.String);
}
else if (jso.Key == "likes")
{
foreach (JSONObject like in jso.Value.Dictionary["data"].Array)
{
foreach (KeyValuePair<String, JSONObject> lik in like.Dictionary)
{
if (lik.Key == "name")
{
result += lik.Value.String;
}
else if (lik.Key == "id")
{
result += lik.Value.String;
}
}
}
foreach (KeyValuePair<String, JSONObject> count in jso.Value.Dictionary)
{
if (count.Key == "count")
{
result += count.Value.String;
}
}
}
else if (jso.Key == "from")
{
foreach (KeyValuePair<String, JSONObject> froms in jso.Value.Dictionary)
{
if (froms.Key == "name")
{
result += froms.Value.String;
}
}
}
}
}
/*
else if (item.IsArray)
{
foreach (JSONObject j in item.Dictionary["data"].Array)
{
if (j.IsDictionary)
{
foreach (KeyValuePair<String,JSONObject> x in j.Dictionary)
{
result += (x.Key + " --- "+x.Value.String);
}
}
}
}
*/
}
return list;
}
you can of course change post and query to whatever you want to search in Facebook Graph API
and there is another way to do that using FQL and its really easy
hope that will be helpful.