The following code was working fine. I then transported the files to another location (another instance of VS2019 Community). Now, the exception doesn't get caught any more and the code breaks during debug. How can this be explained? Thanks
private List<string> getMembers(string objectName)
{
List<string> result = new List<string>();
List<string> listMembers = new List<string>();
try
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, objectName);
string groupList = "";
foreach (var group in up.GetGroups())
{
groupList += group.SamAccountName + "|";
}
result.Add(objectName + tab + groupList);
}
catch (Exception ex)
{
result.Add(objectName + tab + "Error: " + ex.Message);
}
return result;
}
Case of corrupted/missing pdb files. Nothing wrong with code.
Related
i am trying to choose form the autocomplete a place and drew a path to it and when i pick a place from the autocomplete the app crashes.
please see the
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.saoutimohamed.tewsila, PID: 5924
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown
Source:8)
at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source:10)
at com.saoutimohamed.tewsila.WelcomeDriver$4.onResponse(WelcomeDriver.java:271)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
logcat and tall me what is wrong with my code
and this is the code
private void getDirection() {
String requestApi;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.d("SAOUTI", requestApi);
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 5);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tewsila_car)));
handler = new Handler();
} catch (JSONException e) {
e.printStackTrace();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 3000);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(WelcomeDriver.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
the line that not responding in the logcat is (LatLngBounds bounds = builder.build();)
I had this same issue and i removed
"+getResources().getString(R.string.google_direction_api)" part from the requestApi. Perfectlr worked for me. But i don't know the reason.
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=";
I find the best way to save game data in Unity3D Game engine.
At first, I serialize objects using BinaryFormatter.
But I heard this way has some issues and is not suitable for save.
So, What is the best or recommended way for saving game state?
In my case, save format must be byte array.
But I heard this way has some issues and not suitable for save.
That's right. On some devices, there are issues with BinaryFormatter. It gets worse when you update or change the class. Your old settings might be lost since the classes non longer match. Sometimes, you get an exception when reading the saved data due to this.
Also, on iOS, you have to add Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); or you will have problems with BinaryFormatter.
The best way to save is with PlayerPrefs and Json. You can learn how to do that here.
In my case, save format must be byte array
In this case, you can convert it to json then convert the json string to byte array. You can then use File.WriteAllBytes and File.ReadAllBytes to save and read the byte array.
Here is a Generic class that can be used to save data. Almost the-same as this but it does not use PlayerPrefs. It uses file to save the json data.
DataSaver class:
public class DataSaver
{
//Save Data
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Convert To Json then to bytes
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
//Debug.Log(path);
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
//Load Data
public static T loadData<T>(string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
//Load saved Json
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
//Convert to json string
string jsonData = Encoding.ASCII.GetString(jsonByte);
//Convert to Object
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
public static bool deleteData(string dataFileName)
{
bool success = false;
//Load Data
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return false;
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return false;
}
try
{
File.Delete(tempPath);
Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
Debug.LogWarning("Failed To Delete Data: " + e.Message);
}
return success;
}
}
USAGE:
Example class to Save:
[Serializable]
public class PlayerInfo
{
public List<int> ID = new List<int>();
public List<int> Amounts = new List<int>();
public int life = 0;
public float highScore = 0;
}
Save Data:
PlayerInfo saveData = new PlayerInfo();
saveData.life = 99;
saveData.highScore = 40;
//Save data from PlayerInfo to a file named players
DataSaver.saveData(saveData, "players");
Load Data:
PlayerInfo loadedData = DataSaver.loadData<PlayerInfo>("players");
if (loadedData == null)
{
return;
}
//Display loaded Data
Debug.Log("Life: " + loadedData.life);
Debug.Log("High Score: " + loadedData.highScore);
for (int i = 0; i < loadedData.ID.Count; i++)
{
Debug.Log("ID: " + loadedData.ID[i]);
}
for (int i = 0; i < loadedData.Amounts.Count; i++)
{
Debug.Log("Amounts: " + loadedData.Amounts[i]);
}
Delete Data:
DataSaver.deleteData("players");
I know this post is old, but in case other users also find it while searching for save strategies, remember:
PlayerPrefs is not for storing game state. It is explicitly named "PlayerPrefs" to indicate its use: storing player preferences. It is essentially plain text. It can easily be located, opened, and edited by any player. This may not be a concern for all developers, but it will matter to many whose games are competitive.
Use PlayerPrefs for Options menu settings like volume sliders and graphics settings: things where you don't care that the player can set and change them at will.
Use I/O and serialization for saving game data, or send it to a server as Json. These methods are more secure than PlayerPrefs, even if you encrypt the data before saving.
In a java service, without a function declaration, a function call is there and only compile time error comes. But the output is as expected with no run time errors. How is that possible? Can anyone please explain?
"The method functionName() is undefined" is the error it shows.
Below is the code.
public static final void documentToStringVals(IData pipeline)
throws ServiceException {
// pipeline
IDataCursor pipelineCursor = pipeline.getCursor();
String success = "false";
IData inputDoc = null;
String outputValue = "";
String headerYN = "N";
boolean headerValue = false;
String delimiter = ",";
String newline = System.getProperty("line.separator");
if (pipelineCursor.first("inputDocument") ) {
inputDoc = (IData) pipelineCursor.getValue();
}
else {
throw new ServiceException("inputDocument is a required parameter");
}
if (pipelineCursor.first("delimiter") ) {
delimiter = (String) pipelineCursor.getValue();
}
if (pipelineCursor.first("headerYN") ) {
headerYN = (String) pipelineCursor.getValue();
}
if (headerYN.equalsIgnoreCase("Y")) {
headerValue = true;
}
try {
outputValue = docValuesToString(inputDoc, headerValue, delimiter);
outputValue += newline;
success = "true";
}
catch (Exception e) {
System.out.println("Exception in getting string from document: " + e.getMessage());
pipelineCursor.insertAfter("errorMessage", e.getMessage());
}
pipelineCursor.insertAfter("success", success);
pipelineCursor.insertAfter("outputValue", outputValue);
pipelineCursor.destroy();
}
The code you posted has no reference to "functionName", so I suspect there's a reference to it either in the shared code section or in another Java service in the same folder. Given that all Java services in a folder get compiled into a single class, and therefore all those services need to be compiled together, this could cause the error message when you're compiling the service above.
I try to retrieve data from database and populate it in the Jlist. After that, when I click the Jlist, the data will be populated to 3 textfields. Two of them will be populated to a Jeditorpane as a combination in the form of a html file. I have tried the following method but it creates an error.
String meaning1 = txtMeanings.getText();
String source1 = txtSources.getText();
String htmlText = "<html>"
+ "<body>"
+ "<div class='content'>{meaning1}</div>"
+ "<div class='footer'>{source1}</div>"
+"</body>"
+ "</html>";
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(10, 40, 529, 387);
panel_2.add(scrollPane_1);
HTMLEditorKit hed = new HTMLEditorKit();
StyleSheet ss = hed.getStyleSheet();
ss.addRule("BODY {...}");
ss.addRule("h1{...}");
ss.addRule("p{...}");
ss.addRule("blockquote{...}");
ss.addRule("#title{...}");
ss.addRule("hr{...}");
ss.addRule("#content{ ...}");
ss.addRule("#footer{...}");
Document doc = hed.createDefaultDocument();
editorPane = new JEditorPane();
editorPane.setContentType("text/html");
editorPane.setEditorKit(hed);
editorPane.setDocument(doc);
editorPane.setEditable(false);
scrollPane_1.setViewportView(editorPane);
ListboxEntry.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
String query ="select EntryLists, Meanings, Sources from Entry where EntryLists like ? ";
PreparedStatement pst=Connection.prepareStatement(query);
pst.setString(1,(String)ListboxEntry.getSelectedValue());
ResultSet rs=pst.executeQuery();
while(rs.next())
{
txtEntry.setText(rs.getString("EntryLists"));
txtMeanings.setText(rs.getString("Meanings"));
txtSources.setText(rs.getString("Sources"));
}
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();}
editorPane.setText(htmlText);
}
});
What should I do? Is is possible to populate two data (meaning and source) directly to Jeditorpane without populating it first in the two textfield? In the VB.Net, I solve the problem simply by putting this simple code:
WebBrowser1.DocumentText = String.Format("<html><head><style><!--body{{....}}--></style></head></head><body><div id=content>{0}</div><div id=footer><b>Notes:<br></b>{1} </div></body></html>", txtMeanings.Text, txtSources.Text)
How to do that in Java?
I solve my own problem by changing to the following code:
ListboxEntry.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
String query ="select EntryLists, Meanings, Sources from Entry where EntryLists like ? ";
PreparedStatement pst=Connection.prepareStatement(query);
pst.setString(1,(String)ListboxEntry.getSelectedValue());
ResultSet rs=pst.executeQuery();
while(rs.next())
{
txtEntry.setText(rs.getString("EntryLists"));
txtMeanings.setText(rs.getString("Meanings"));
txtSources.setText(rs.getString("Sources"));
}
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();}
String htmlText = "<html>"
+ "<body>"
+ "<div class='content'>"+ txtMeanings.getText() +"</div>"
+ "<div class='footer'>"+ txtSources.getText() +"</div>"
+"</body>"
+ "</html>";
editorPane.setText(htmlText);
}
});
But, if anyone wants to improve it, your suggestion is welcome.
I am making a profile encryption program with 2 ciphers. I want to have a GUI with buttons for enciphering, deciphering and exiting.
My problem is with the actionPerformed method. It needs to throw the exception that the outputStream throws. This is the error I get when I try to complie it:
:53: error: actionPerformed(ActionEvent) in ProfileEncryption_2 cannot implement actionPerformed(ActionEvent) in ActionListener
public void actionPerformed (ActionEvent e) throws FileNotFoundException//When a button is clicked
I have though of multiple solutions, but am not sure how to implement them properly. I could catch the exception and do something with it, but I am not sure how and what. I could also check if the file exists, and if so, then output, but what I tried for that didn't work either.
public void actionPerformed (ActionEvent e) throws Exception //When a button is clicked
{
if (e.getSource() == encrBtn)
{
menu.setVisible(false);
createProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == decrBtn)
{
menu.setVisible(false);
viewProfile();
menu.setVisible(true);
}
else
{
if (e.getSource() == exitBtn)
{
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
}
}
//End of menu
//Start of create/view section
public static void createProfile() throws Exception //Create profile
{
String username = JOptionPane.showInputDialog("Enter your username.");
String password, confirmPass, strEncrType;
int intEncrType = 0, unlock = 0;
do
{
password = JOptionPane.showInputDialog("Enter your password.\nIt must be more than 7 characters long.");
confirmPass = JOptionPane.showInputDialog("Confirm password");
if (password.equals(confirmPass) && (password.length() >= 7))
{
JOptionPane.showMessageDialog(null, "Passwords match!");
unlock = 1;
}
else
{
if (!password.equals(confirmPass))
JOptionPane.showMessageDialog(null, "Passwords do not match!");
if (password.length() < 7)
JOptionPane.showMessageDialog(null, "Password is not long enough!");
}
}
while (unlock==0);
do
{
strEncrType = JOptionPane.showInputDialog("Choose which encryption type you would prefer:\n1. Vigenère\n2. Erénegiv mod 4");
if(!strEncrType.equals("1")&&!strEncrType.equals("2"))
JOptionPane.showMessageDialog(null, "Invalid response, try again.");
}
while (!strEncrType.equals("1")&&!strEncrType.equals("2"));
intEncrType = Integer.parseInt(strEncrType);
String name = JOptionPane.showInputDialog("Enter your real name.");
String phone = JOptionPane.showInputDialog("Enter your phone number.");
String email = JOptionPane.showInputDialog("Enter your email.");
String other = JOptionPane.showInputDialog("Enter notes/extra data you want stored.");
String data = password + "-" + username + "-tester-" + name + "-" + phone + "-" + email + "-" + other + "-" + strEncrType;
if (intEncrType ==1)
data = encrypt1(data);
else
data = encrypt2(data);
data = data + strEncrType;
OutputStream output = new FileOutputStream(username + ".txt");
byte buffer[] = data.getBytes();
output.write(buffer);
output.close();
}