Download image error android.os.NetworkOnMainThreadException - android-imageview

I have that function with how I download images on my application, but I don't know why I've received that network on main thread exception.
Here it's my class with function:
public class Tail {
String story, description, title, location;
int imageID;
URL url;
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public Tail(int imageID, String location, String description, String title, String story) {
this.imageID = imageID;
this.location = location;
this.title = title;
this.description = description;
this.story = story;
}
public Tail(String url, String location, String description, String title, String story) {
try {
this.url = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.location = location;
this.title = title;
this.description = description;
this.story = story;
}
public String getStory() {
return story;
}
public void setStory(String story) {
this.story = story;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImageID() {
return imageID;
}
public void setImageID(int imageID) {
this.imageID = imageID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public static Bitmap getImageBitmapFromUrl(URL url) {
Bitmap bm = null;
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
return bm;
}
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
try {
bm = BitmapFactory.decodeStream(bis);
} catch (OutOfMemoryError ex) {
bm = null;
}
bis.close();
is.close();
} catch (Exception e) {
}
return bm;
}
Know anyone how can solve that problem?

This exception is thrown when an application attempts to perform a networking operation on its main thread.
you need to perform HTTP connection in asynctask.
have a look how to use assynctask http://developer.android.com/reference/android/os/AsyncTask.html

Related

How to return different types of responses from WCF service application method?

I have a WCF service application with a method
public PersonResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
I have 2 different responses possible for that method
[DataContract]
public class PersonResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
and
[DataContract]
public class ErrorResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
Is it possible to write a method that could return either of those responses but not both at the same time?
I Could do something like
[DataContract]
public class Response
{
PersonResponse personResponse;
ErrorResponse errorResponse;
[DataMember]
public bool PersonResponse
{
get { return personResponse; }
set { personResponse= value; }
}
[DataMember]
public string ErrorResponse
{
get { return errorResponse; }
set { errorResponse= value; }
}
}
public Response(PersonRequest request)
{
return new Response{ PersonResponse = New PersonResponse { Id = 1, Name = "Mark" }, ErrorResponse = new ErrorResponse { ErrorCode = null, ErrorText = null } };
}
But I only need 1 type of the response to be returned, not both.
I've tried
public PersonResponse(PersonRequest request)
{
throw new WebFaultException<ErrorResponse>(new ErrorResponse { ErrorCode = 103 ErrorText = "Try again later" }, HttpStatusCode.Conflict);
}
But it seems that this way it only returns the exception and not the ErrorResponse.
I've also tried adding and interface layer to the response like so and then returning that interface as a response
public interface IResponse {}
[DataContract]
public class PersonResponse : IResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
[DataContract]
public class ErrorResponse : IResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
public IResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
But when I add this service as a reference to another project id doesn't generate any of the response type (Iresponse, ErrorResonse or PersonResponse) and throws an error when I try to call the method (Exception message https://ibb.co/Zdsbr9p)
I think you can try to use FaultContractAttribute. Fault contracts allow you to specify alternate responses that will be returned in a SOAP fault.
Example interface:
[ServiceContract]
interface IService
{
[OperationContract]
[FaultContract(typeof(ErrorResponse))]
PersonResponse GetResponse();
}
Service:
class Service : IService
{
public PersonResponse GetResponse()
{
if (success)
{
return new PersonResponse();
}
else
{
throw new FaultException<ErrorResponse>(new ErrorResponse()
{
ErrorMessage = "Something Happened"
})
}
}
}
The client can then handle the fault by catching FaultException<ErrorResponse>:
var serviceProxy = new ServiceProxy();
try
{
var dataObj = serviceProxy.GetResponse();
}
catch (FaultException<ErrorResponse> error)
{
ErrorResponse detail = error.Detail;
Console.WriteLine(detail.ErrorMessage);
}
source:How best should a Wcf service return different objects for the same method
resemblance:Return different Object (List or error class) from WCF service

custom file validation for .net core 2.0

I am trying to make a custom file validation for my project which is based on .net core 2.
I want to validate file size and also file extension in order to prevent users from uploading large files and for example .png files.
I have searched a lot but I could not find anything that works.
Here is my file validation class :
public class FileTypeAttribute : ValidationAttribute, IClientModelValidator
{
private const int MaxSize = 1048576;
private const string _DefaultErrorMessage = "Only the following file types are allowed: {0}";
private IEnumerable<string> _ValidTypes { get; set; }
public string ValidTypes { get; set; }
public string ErrorMessageExtension { get; set; }
public string ErrorMessageSize { get; set; }
public FileTypeAttribute(string errorExtension, string errorSize, string vt)
{
ErrorMessageExtension = errorExtension;
ErrorMessageSize = errorSize;
_ValidTypes = vt.Split(',');
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IFormFile file = value as IFormFile;
if (file != null)
{
if (!_ValidTypes.Any(e => file.FileName.EndsWith(e)))
{
return new ValidationResult(ErrorMessageExtension);
}
if (file.Length > MaxSize)
{
return new ValidationResult(ErrorMessageSize);
}
}
return ValidationResult.Success;
}
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-fileextensions", ErrorMessageExtension);
MergeAttribute(context.Attributes, "data-val-maxfilesize", ErrorMessageSize);
}
private bool MergeAttribute(
IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
and here is the javascript code in my view:
$.validator.addMethod("FileType",
function (value, element, param) {
for (var i = 0; i < element.files.length; i++) {
var extension = getFileExtension(element.files[0].name);
if ($.inArray(extension, param.validtypes) === -1) {
return false;
}
}
return true;
});
$.validator.unobtrusive.adapters.add('FileType', ['validtypes'], function (options) {
console.log("value:");
options.rules.cannotbered = {};
options.messages["FileType"] = options.message;
});
function getFileExtension(fileName) {
if (/[.]/.exec(fileName)) {
return /[^.]+$/.exec(fileName)[0].toLowerCase();
}
return null;
}
and here is the entity class code in my project:
public class MyEntityClass
{
public int MyEntityClassId { get; set; }
[FileType("invalid format", "invalid size", "jpg,png,gif")]
public IFormFile Photo { get; set; }
}
Can anyone help me to know where the problem is?
Thanks in advance.

Returning Custom Class from WCF Method?

There are so many question about that but there is no solution for my problem. I want to return a custom class which has datacontract key and it's members have datamember key. I am getting this error while I testing it;
When I call it from my windows phone application, it returns "The remote server not found"
It returns not found but it runs methods that return types are void, bool, list.
[OperationContract]
BaseModel Login(string userName, string password);
[DataContract]
public class UserModel
{
private int userID;
[DataMember]
public int UserID
{
get { return userID; }
set { userID = value; }
}
private string userName;
[DataMember]
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string password;
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
private string email;
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
private int securityQuestionID;
[DataMember]
public int SecurityQuestionID
{
get { return securityQuestionID; }
set { securityQuestionID = value; }
}
private string securityQuestionAnswer;
[DataMember]
public string SecurityQuestionAnswer
{
get { return securityQuestionAnswer; }
set { securityQuestionAnswer = value; }
}
private string sex;
[DataMember]
public string Sex
{
get { return sex; }
set { sex = value; }
}
private string gsmNo;
[DataMember]
public string GSMNo
{
get { return gsmNo; }
set { gsmNo = value; }
}
private DateTime birthDate;
[DataMember]
public DateTime BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
private string registeredDeviceUniqueID;
[DataMember]
public string RegisteredDeviceUniqueID
{
get { return registeredDeviceUniqueID; }
set { registeredDeviceUniqueID = value; }
}
private string registrationType;
[DataMember]
public string RegistrationType
{
get { return registrationType; }
set { registrationType = value; }
}
private string registeredDeviceType;
[DataMember]
public string RegisteredDeviceType
{
get { return registeredDeviceType; }
set { registeredDeviceType = value; }
}
private string registeredApplication;
[DataMember]
public string RegisteredApplication
{
get { return registeredApplication; }
set { registeredApplication = value; }
}
private DateTime registeredDate;
[DataMember]
public DateTime RegisteredDate
{
get { return registeredDate; }
set { registeredDate = value; }
}
private string registeredGSM;
[DataMember]
public string RegisteredGSM
{
get { return registeredGSM; }
set { registeredGSM = value; }
}
private string profilePictureURL;
[DataMember]
public string ProfilePictureURL
{
get { return profilePictureURL; }
set { profilePictureURL = value; }
}
}
[DataContract]
public class BaseModel
{
private string errorMessage;
[DataMember]
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
private string informationMessage;
[DataMember]
public string InformationMessage
{
get { return informationMessage; }
set { informationMessage = value; }
}
private string warningMessage;
[DataMember]
public string WarningMessage
{
get { return warningMessage; }
set { warningMessage = value; }
}
private string succeedMessage;
[DataMember]
public string SucceedMessage
{
get { return succeedMessage; }
set { succeedMessage = value; }
}
private object returnObject;
[DataMember]
public object ReturnObject
{
get { return returnObject; }
set { returnObject = value; }
}
private bool isSucceed;
[DataMember]
public bool IsSucceed
{
get { return isSucceed; }
set { isSucceed = value; }
}
}
And the method is;
public BaseModel Login(string userName, string password)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM UserBaseInformations WITH (NOLOCK) Where UserName=#userName", connection))
{
command.Parameters.Add(new SqlParameter("#userName", userName));
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable dt = new DataTable();
adapter.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
connection.Close();
if (dt.Rows.Count == 0)
return new BaseModel() { IsSucceed = false, ErrorMessage = "Geçersiz bir kullanıcı adı girdiniz." };
else if (!dt.Rows[0]["Password"].ToString().Equals(password))
return new BaseModel() { IsSucceed = false, ErrorMessage = "Şifrenizi yanlış girdiniz." };
else
return new BaseModel()
{
IsSucceed = true,
ReturnObject = new UserModel()
{
Email = dt.Rows[0]["Email"].ToString(),
Password = dt.Rows[0]["Password"].ToString(),
UserID = (int)dt.Rows[0]["UserID"],
UserName = dt.Rows[0]["UserName"].ToString(),
SecurityQuestionID = (int)dt.Rows[0]["SecurityQuestionID"],
SecurityQuestionAnswer = dt.Rows[0]["SecurityQuestionAnswer"].ToString()
}
};
}
}
}
I have found solution.
Returning an object type can be problem in WCF so I changed it to a base class for returning my classes and added KnownType attribute to BaseModel.

How to display the bean value inside the struts text box

Hi I want to display the bean value inside the text box using struts2 , But its not working ,Please help.
Even I tried to set and get the value from the bean but still not working.
I have attached the output .
Customer.java
package com.java.bean;
public class Customer {
private int id;
private String customerName;
private String cifNumber;
private int idNumber;
private String idCountry;
private String idType;
private int master_id;
private String rmCode;
private String customerCountry;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCifNumber() {
return cifNumber;
}
public void setCifNumber(String cifNumber) {
this.cifNumber = cifNumber;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getIdCountry() {
return idCountry;
}
public void setIdCountry(String idCountry) {
this.idCountry = idCountry;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public int getMaster_id() {
return master_id;
}
public void setMaster_id(int master_id) {
this.master_id = master_id;
}
public String getRmCode() {
return rmCode;
}
public void setRmCode(String rmCode) {
this.rmCode = rmCode;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
}
CustomerSearchActionForam.java
package com.vaannila;
public class CustomerSearchActionForm extends org.apache.struts.action.ActionForm{
private int id;
private String customerName;
private String cifNumber;
private int idNumber;
private String idCountry;
private String idType;
private int master_id;
private String rmCode;
private String customerCountry;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCifNumber() {
return cifNumber;
}
public void setCifNumber(String cifNumber) {
this.cifNumber = cifNumber;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getIdCountry() {
return idCountry;
}
public void setIdCountry(String idCountry) {
this.idCountry = idCountry;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public int getMaster_id() {
return master_id;
}
public void setMaster_id(int master_id) {
this.master_id = master_id;
}
public String getRmCode() {
return rmCode;
}
public void setRmCode(String rmCode) {
this.rmCode = rmCode;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
SearchCustomer.java
import javax.servlet.http.HttpServletRequest;
import java.beans.*;
import java.util.List;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.util.MessageResources;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.java.bean.Customer;
import com.java.bean.LoginUser;
public class SearchCustomer extends org.apache.struts.action.Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
CustomerSearchActionForm customerSearch = (CustomerSearchActionForm) form;
MessageResources msgResource = getResources(request);
String cifNumber_=customerSearch.getCifNumber();
String Result_ = "success";
System.out.println("CIF NUMBER:"+cifNumber_);
SearchCustomer Scust = new SearchCustomer();
List customer=Scust.listCustomers(cifNumber_);
request.setAttribute("customerList",customer);
Iterator iterator = customer.iterator();
if(iterator.hasNext()){
System.out.println("customer found");
customerSearch.setMessage(msgResource.getMessage("msg.customerfound"));
}
else{
System.out.print("Customer Not Found");
customerSearch.setMessage(msgResource.getMessage("error.nocustomerfound"));
}
System.out.println("List of Customers : "+customer);
return mapping.findForward(Result_);
}
public List listCustomers(String cifNumber_){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = null;
List customer = null;
try{
tx = session.beginTransaction();
Query sql = session.createQuery("from Customer where cifNumber=:cifNumbervalue");
System.out.println("Query printing "+sql);
sql.setParameter("cifNumbervalue",cifNumber_);
customer = sql.list();
System.out.println("CUSTOMER LIST ITERATION"+customer);
for (Iterator iterator = customer.iterator(); iterator.hasNext();){
Customer cust = (Customer) iterator.next();
String cifNumber=cust.getCifNumber();
String custName=cust.getCustomerName();
System.out.println("----------------------------------------------------------- - -------------------------------------------");
System.out.print("CifNumber: " + cifNumber+" CustomerName :"+custName);
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return customer;
}
}
LoginHome.jsp (to display my records from database)
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginActionForm" property="userName" />
Password :<html:password name="LoginActionForm" property="passWord" />
<html:submit value="Login" />
</html:form>
</body>
OUTPUT
CifNumber: 10000
CustomerName: JP Morgon
IDNumber: 123321
ID Country: SINGAPORE
RM CODE: E001
CustomerCountry: USA
Customer Details
CIF NUMBER :
CUSTOMER NAME :
ID NUMBER :
ID COUNTRY :
RM CODE :
CUSTOMER COUNTRY :
login

Determine what fields to save in Windows Azure Table Storage

I'm trying to store an entity called Tshirt into a Windows Azure table storage along with a Blob on Windows Azure Blob storage.
That entity Tshirt contains a field called Image (byte[]) but I don't want to save that in my table.
How can I indicate in my class that I don't want to save that field?
public class Tshirt : TableServiceEntity
{
public Tshirt(string partitionKey, string rowKey, string name)
{
this.PartitionKey = partitionKey;
this.RowKey = rowKey;
this.Name = name;
this.ImageName = new Guid();
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _color { get; set; }
public string Color
{
get { return _color; }
set { _color = value; }
}
private int _amount { get; set; }
public int Amount
{
get { return _amount; }
set { _amount = value; }
}
[NonSerialized]
private byte[] _image;
public byte[] Image
{
get { return _image; }
set { _image = value; }
}
private Guid _imageName;
public Guid ImageName
{
get { return _imageName; }
set { _imageName = value; }
}
}
The easy way is to expose the field as a pair of methods rather than an actual property:
public byte[] GetImage()
{
return _image;
}
public void SetImage(byte[] image)
{
_image = image;
}
If that's not an option, then you can remove the Image property when you're storing the entity by handling the WritingEntity event. (Credit to Neil Mackenzie)
public void AddTshirt(Tshirt tshirt)
{
var context = new TableServiceContext(_baseAddress, _credentials);
context.WritingEntity += new EventHandler<ReadingWritingEntityEventArgs>(RemoveImage);
context.AddObject("Tshirt", tshirt);
context.SaveChanges();
}
private void RemoveImage(object sender, ReadingWritingEntityEventArgs args)
{
XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
XElement imageElement = args.Data.Descendants(d + "Image").First();
imageElement.Remove();
}