I want to store json values in my device. Because everytime application takes time to load json values. Instead of doing number of times to load, just want to load entire json values once. and without internet I can work with that. Once internet get connected, the application automatically load json values. How can I do this ?
You Can use Database for that.
This way also you can store it.
Arraylist<ClassName> jsondata=new ArrayList<ClassName>
Here's an example:
public Class ClassName
{
string fname;
string lname;
public void setfname(String fname)
{
this.fname=fname;
}
public void setlname(String lname)
{
this.lname=lname;
}
public String getlname(String lname)
{
return lname;
}
public String getfname(String fname)
{
return fname;
}
You can use SharedPreferences to save the json in application's storage space.
code
/* save */
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
Editor editor = pref.edit();
editor.put("myjson", json.toString());
editor.commit();
/* restore */
JSONObject ret = null;
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
String jsonStr = pref.getString("myjson", null);
if (!TextUtil.isEmpty(jsonStr)) {
ret = new JSONObject(jsonStr); // need try-catch
}
======
Do the restore every time the app is launching.
For the second part "Once internet get connected, the application automatically load json values."
You need to listen the network state change broadcast. When you get broadcast said the network (or wifi) is connected, grab the newest json from server, replace the json in the memory and save it to SharedPreferences
Related
I'm currently trying to use gestures recognizers in Unity3D. For this I need a library of gestures to be compared with the gesture I'm making.
I'm using a script to save and load from another Unity user since I have no idea how to do it myself.
The problem I'm facing is:
If I save the gestures as json file during gameplay, I can compare them in the same run. But if I restart the run, it stops being able to read the json file and returns NULL or no match as if there were nothing in the json file.
[Serializable]
public class GestureTemplates
{
public List<DrawnGesture> templates;
public GestureTemplates()
{
templates = new List<DrawnGesture>();
}
}
private string gestureFileName = "gestures.json";
void Start () {
LoadTemplates();
}
private void SaveTemplates()
{
string filePath = Application.dataPath + "/streamingAssets/" + gestureFileName;
string saveData = JsonUtility.ToJson(templates);
File.WriteAllText(filePath, saveData);
Debug.Log("Template Saved");
}
private void LoadTemplates()
{
templates = new GestureTemplates();
string filePath = Path.Combine(Application.streamingAssetsPath, gestureFileName);
if (File.Exists(filePath))
{
string data = File.ReadAllText(filePath);
templates = JsonUtility.FromJson<GestureTemplates>(data);
}
}
What I've noticed is it takes a while to save, but it does in fact save since it calls the debug.Log line and the save file can be used in the same run.
Any help would be highly appreciated.
Edit: Nevermind. It's not saving either. It's saving as a Json file with an empty list. The variable is working on the run, but it's not saving nor loading.
So I have an SSIS package that I am working on right now that requires something that I have yet to do. The package currently just has a For Each Loop container that stores the value of the file name it finds in the User::WatchFolder to a variable and then moves that file to another folder for a process to pick up. What I have been tasked with is augmenting this so that the process remains unchanged for .837 file that does not contain a certain set of character but redirecting the files that come through with the word 'RELAY' in them. From there I also need to open up this EDI file and replace the string '5010' with '5010R', save it and move to a separate folder.
I have moved data in a Data flow task based on certain criteria using a Conditional Split, but this is not data from a table or database, so I'm not sure if this can be accomplished in a Control Flow task. Also, I'm assuming that the string can be replaced via a Script Task, but I'm not sure (again) if this is something that would live in the Control flow or in some sort of Data Flow task.
This is what the package looks like thus far.
SSIS Package so far
EDIT: So far I have created a script task using C# to find and replace the values using ReadFile(FilePath) into a variable called FileContent and then doing a FileContent.Replace("someText","someOtherText")
and then writing the contents back to the file using StreamReader and StreamWriter. That part seems to work fine, but I'm not sure now how to move the file depending on whether it contains a certain value in the FileName.
public void Main()
{
String ErrInfo = "";
String FilePath = Dts.Variables["User::FileName"].Value.ToString();
try
{
String FileContent; //Variable to store File Contents
FileContent = ReadFile(FilePath, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while reading File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
//FileContent Before Replace;
MessageBox.Show(FileContent);
//Find and Replace --> Modify WHERE clause
FileContent = FileContent.Replace(
"Relay5010 ",
"Relay5010R"
);
//FileContent After Replace;
MessageBox.Show(FileContent);
Dts.Variables["User::FileContent"].Value = FileContent;
//Write the contents back to File
WriteToFile(FilePath, FileContent, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while writing File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
}
catch (Exception e)
{
Dts.Log(e.Message, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
public String ReadFile(String FilePath, String ErrInfo)
{
String strContents;
StreamReader sReader;
try
{
sReader = File.OpenText(FilePath);
strContents = sReader.ReadToEnd();
sReader.Close();
return strContents;
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
return "";
}
}
public void WriteToFile(String FilePath, String strContents, String ErrInfo)
{
StreamWriter sWriter;
try
{
sWriter = new StreamWriter(FilePath);
sWriter.Write(strContents);
sWriter.Close();
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Truth is, I'd love to leave the existing files alone and let them run down their normal path and just divert the ones containing the "R" value and those can have the script task applied to them. Is there possibly a way other than another script task? I am just trying to see if SSIS lends me another tool so that this can be done in the most straight forward way possible
This is my first question posted as well so if there is something else I missed here, I won't be offended if it is pointed out!
I am using a Vaadin upload component and so far I have managed to upload an image to a directory, and display it in a panel component after it is successfull uploaded. What I want to do after this, is to insert it in the database aswell. What I have is a table called Show which has a name, date and an image. In the Show class I have tried to have my image as a byte array or as a Blob.
Column(name="image")
private byte[] image;
#Lob
#Column(name="image")
private Blob image;
In the upload succeded method I want to convert the file to a byte array, and so far I have tried this:
File file = new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename());
byte[] bFile = new byte[(int) file.length()];
try {
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
uIP.uploadImage(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
I tried also this:
byte[] data = Files.readAllBytes(new File("C:\\Users\\Cristina_PC\\Desktop\\" + event.getFilename()).toPath());
uIP.uploadImage(data);
uIP it is actually my uploadImagePresenter, where I tried to transform the byte array to Blob, or simply pass it to the repository as byte array
public void uploadImage(byte[] data) throws SerialException, SQLException{
//Blob blob = new javax.sql.rowset.serial.SerialBlob(data);
showRepo.updateAfterImage(show, data); // or (show, blob)
}
In my repository, in my updateAfterImage method I have:
public void updateAfterImage(Show show, byte[] data) //or Blob data
{
em.getTransaction().begin(); //em - EntityManager
show.setImage(data);
em.getTransaction().commit();
}
Either with Blob or a byte array, I can't manage to update the existing show by setting its image and update it in the database (the cell remains NULL). Also I get no error to help me figure out what is going wrong. Any help/advice would be useful. Thanks!
I have found the solution. What made it work was:
em.getTransaction().begin();
em.find(Show.class, show.getId());
show.setImage(data);
em.merge(spectacol);
em.getTransaction().commit();
in my updateAfterImage method in the show repository.
I have a ASP.NET WebApi project that I am working on. The boss would like the returns to support "partial response", meaning that though the data model might contain 50 fields, the client should be able to request specific fields for the response. The reason being that if they are implementing for example a list they simply don't need the overhead of all 50 fields, they might just want the First Name, Last Name and Id to generate the list. Thus far I have implemented a solution by using a custom Contract Resolver (DynamicContractResolver) such that when a request comes in I am peeking into it through a filter (FieldListFilter) in the OnActionExecuting method and determining if a field named "FieldList" is present and then if it is I am replacing the current ContractResolver with a new instance of my DynamicContractResolver and I pass the fieldlist to the constructor.
Some sample code
DynamicContractResolver.cs
protected override IList<JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
{
List<String> fieldList = ConvertFieldStringToList();
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
if (fieldList.Count == 0)
{
return properties;
}
// If we have fields, check that FieldList is one of them.
if (!fieldList.Contains("FieldList"))
// If not then add it, FieldList must ALWAYS be a part of any non null field list.
fieldList.Add("FieldList");
if (!fieldList.Contains("Data"))
fieldList.Add("Data");
if (!fieldList.Contains("FilterText"))
fieldList.Add("FilterText");
if (!fieldList.Contains("PageNumber"))
fieldList.Add("PageNumber");
if (!fieldList.Contains("RecordsReturned"))
fieldList.Add("RecordsReturned");
if (!fieldList.Contains("RecordsFound"))
fieldList.Add("RecordsFound");
for (int ctr = properties.Count-1; ctr >= 0; ctr--)
{
foreach (string field in fieldList)
{
if (field.Trim() == properties[ctr].PropertyName)
{
goto Found;
}
}
System.Diagnostics.Debug.WriteLine("Remove Property at Index " + ctr + " Named: " + properties[ctr].PropertyName);
properties.RemoveAt(ctr);
// Exit point for the inner foreach. Nothing to do here.
Found: { }
}
return properties;
}
FieldListFilter.cs
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
// We need to determine if there is a FieldList property of the model that is being used.
// First get a reference to the model.
var modelObject = actionContext.ActionArguments.FirstOrDefault().Value;
string fieldList = string.Empty;
try
{
// Using reflection, attempt to get the value of the FieldList property
var fieldListTemp = modelObject.GetType().GetProperty("FieldList").GetValue(modelObject);
// If it is null then use an empty string
if (fieldListTemp != null)
{
fieldList = fieldListTemp.ToString();
}
}
catch (Exception)
{
fieldList = string.Empty;
}
// Update the global ContractResolver with the fieldList value but for efficiency only do it if they are not the same as the current ContractResolver.
if (((DynamicContractResolver)GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver).FieldList != fieldList)
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DynamicContractResolver(fieldList);
}
}
I can then send a request with the json content payload looking as such:
{
"FieldList":"NameFirst,NameLast,Id",
"Data":[
{
"Id":1234
},
{
"Id":1235
}
]
}
and I will receive a response like so:
{
"FieldList":"NameFirst,NameLast,Id",
"Data":[
{
"NameFirst":"Brian",
"NameLast":"Mueller",
"Id":1234
},
{
"NameFirst":"Brian",
"NameLast":"Mueller",
"Id":1235
}
]
}
I believe that using the ContractResolver might run into threading issues. If I change it for one request is it going to be valid for all requests thereafter until someone changes it on another request (seems so through testing) If that is the case, then I don't see the usefulness for my purpose.
In summary, I am looking for a way to have dynamic data models such that the output from a request is configurable by the client on a request by request basis. Google implements this in their web api and they call it "partial response" and it works great. My implementation works, to a point but I fear that it will be broken for multiple simultaneous requests.
Suggestions? Tips?
A simpler solution that may work.
Create a model class with all 50 members with nullable types.
Assign values to the requested members.
Just return the result in the normal way.
In your WebApiConfig.Register() you must set the null value handling.
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
You must not touch the configuration. You need the contract resolver on per-request basis. You can use it in your action method like this.
public class MyController : ApiController
{
public HttpResponseMessage Get()
{
var formatter = new JsonMediaTypeFormatter();
formatter.SerializerSettings.ContractResolver =
new DynamicContractResolver(new List<string>()
{"Id", "LastName"}); // you will get this from your filter
var dto = new MyDto()
{ FirstName = "Captain", LastName = "Cool", Id = 8 };
return new HttpResponseMessage()
{
Content = new ObjectContent<MyDto>(dto, formatter)
};
// What goes out is {"LastName":"Cool","Id":8}
}
}
By doing this, you are locking yourself into JSON content type for response messages but you have already made that decision by using a Json.NET specific feature. Also, note you are creating a new JsonMediaTypeFormatter. So, anything you configure to the one in the configuration such as media type mapping is not going to be available with this approach though.
I know this question is from many years ago, but if you're looking to do this with modern releases of the framework, I'd recommend nowadays to use OData services (http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/using-select-expand-and-value).
I spend most of my time in C# and am trying to figure out which is the best practice for handling an exception and cleanly return an error message from a called method back to the calling method.
For example, here is some ActiveDirectory authentication code. Please imagine this Method as part of a Class (and not just a standalone function.)
bool IsUserAuthenticated(string domain, string user, string pass, out errStr)
{
bool authentic = false;
try
{
// Instantiate Directory Entry object
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass);
// Force connection over network to authenticate
object nativeObject = entry.NativeObject;
// No exception thrown? We must be good, then.
authentic = true;
}
catch (Exception e) { errStr = e.Message().ToString(); }
return authentic;
}
The advantages of doing it this way are a clear YES or NO that you can embed right in your If-Then-Else statement. The downside is that it also requires the person using the method to supply a string to get the Error back (if any.)
I guess I could overload this method with the same parameters minus the "out errStr", but ignoring the error seems like a bad idea since there can be many reasons for such a failure...
Alternatively, I could write a method that returns an Error String (instead of using "out errStr") in which a returned empty string means that the user authenticated fine.
string AuthenticateUser(string domain, string user, string pass)
{
string errStr = "";
try
{
// Instantiate Directory Entry object
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass);
// Force connection over network to authenticate
object nativeObject = entry.NativeObject;
}
catch (Exception e) { errStr = e.Message().ToString(); }
return errStr;
}
But this seems like a "weak" way of doing things.
Or should I just make my method "void" and just not handle the exception so that it gets passed back to the calling function?
void AuthenticateUser(string domain, string user, string pass)
{
// Instantiate Directory Entry object
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass);
// Force connection over network to authenticate
object nativeObject = entry.NativeObject;
}
This seems the most sane to me (for some reason). Yet at the same time, the only real advantage of wrapping those 2 lines over just typing those 2 lines everywhere I need to authenticate is that I don't need to include the "LDAP://" string. The downside with this way of doing it is that the user has to put this method in a try-catch block.
Thoughts?
Is there another way of doing this that I'm not thinking of?
There is no "one size fits all". If you return a flag, that makes it easy to use a method in if() and loops. Exceptions always need a lot of boiler plate code. If you just want a string which you can display to the user (say, in a web UI), returning the error string (or null for "no error") is good, too.
But most of the time, I throw an exception (and in Java a subclass of RuntimeException) because that allows me to return more than a single information about the error (like: Which file caused the error? Which line/column? What was I doing? Which field in a form should be marked as illegal? etc).
In your case, you can't handle the exception in your method, so you shouldn't catch it. Only catch it when you can do something about it.
In this example, I agree, you should let the exception flow through to the consumer. However, as an alternative to the approaches you highlighted, consider this approach.
You can use a response object to hold information coming out of a method run, for example:
public abstract class BaseResponse
{
public bool IsOk { get; protected set;}
public string Message { get; protected set; }
}
public class AuthenticationResponse: BaseResponse
{
public AuthenticationResponse(bool isOk): this(isOk, "") {}
public AuthenticationResponse(bool isOk, string message)
{
IsOk = isOk;
Message = message;
}
}
AuthenticationResponse IsUserAuthenticated(string domain, string user, string pass)
{
bool authentic = false;
string errStr;
try
{
// Instantiate Directory Entry object
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass);
// Force connection over network to authenticate
object nativeObject = entry.NativeObject;
// No exception thrown? We must be good, then.
authentic = true;
}
catch (Exception e) { errStr = e.Message().ToString(); }
return new AuthenticationResponse(authentic, errStr);
}
Then to use it in your if statements:
AuthenticationResponse response;
if((response = IsUserAuthenticated("domain", "user", "pass")).IsOk)
{
// do successful activity
} else {
Console.WriteLine(response.Message)
}
The trick is the return value of an assignment operation is the value that was assigned. So, we can do the assignment and the valid check in the same line. If you didn't need to hold onto the result of the call, you could simply call the method and check the IsOk property.
if(IsUserAuthenticated("domain", "user", "pass").IsOk)
{
// do successful activity
}
Then you can build up your custom response object to return any combination of values from your method as you need.
Don't handle the exception or return a message of any kind. Let the consumer of your method take care of this.