SolrNet Duplicate File Conents - solr

All,
I wrote a method that extends some of the functionality in the SolrNet example MVC app. It's very simple and in my controller I added the following.
public string Index()
{
try
{
var solr = ServiceLocator.Current.GetInstance>();
String qs = Request.QueryString["q"];
var results = solr.Query(new SolrQueryByField("asciiname", qs));
StringBuilder buffer = new StringBuilder();
buffer.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buffer.Append("<kml xmlns=\"http://www.opengis.net/kml/2.2\"\n");
buffer.Append(" xmlns:gx=\"http://www.google.com/kml/ext/2.2\">\n");
buffer.Append("<Document>\n");
buffer.Append("<name>\n");
buffer.Append("Gazetteer\n");
buffer.Append("</name>\n");
buffer.Append("<description>\n");
buffer.Append("World Places\n");
buffer.Append("</description>\n");
foreach (var i in results)
{
String lat = i.latitude.ToString();
String lon = i.longitude.ToString();
String name = i.asciiName.ToString();
String coords = lon.ToString() + "," + lat.ToString();
name = name.Replace("&", "&");
name = name.Replace("<", "<");
name = name.Replace(">", ">");
buffer.Append("<Placemark>\n");
buffer.Append("<name>\n");
buffer.Append(name);
buffer.Append("</name>\n");
buffer.Append("<Point>\n");
buffer.Append("<coordinates>\n");
buffer.Append(coords);
buffer.Append("</coordinates>\n");
buffer.Append("</Point>\n");
buffer.Append("</Placemark>\n");
}
buffer.Append("</Document>\n");
buffer.Append("</kml>");
Response.Write(buffer.ToString());
Response.AddHeader("content-disposition", "attachment; filename=geonames.kml");
Response.ContentType = "application/vnd.google-earth.kml+xml";
Response.AppendHeader("Content-Encoding", "kml");
return buffer.ToString();
}
catch (Exception)
{
return "ERROR";
}
}
The KML file is generated but the content is duplicated starting at the tag. Is this happening in var solr = ServiceLocator.Current.GetInstance>(); for some reason? I have been walking through the debugger all day and can't seem to figure out why it's writing out the whole thing twice. It does utilize the foreach loop and iterate properly through that but again, it's duplicating the contents of the entire file.
Any help on this would be great!
Adam

Ughhh...I completely overlooked the fact that I was writing the buffer out twice!
Response.Write(buffer.ToString());
and
return buffer.ToString();
Adam

Related

PHP mailer and FPDF attachment with loop - script stops after first run

I'm running a following script to generate and send email. The email body is generated in a while loop (content differs) - it works fine. But now I have tried to include a script to generate PDF attachment (via FPDF library), in each iteration the attachment is different.
Problem is: the loop runs just once, for the first case and after it stops. Thank you for your commnents in advance.
My code:
<?
$mail = new PHPMailer();
$mail->SMTPDebug = 1;
$mail->isSMTP();
$mail->addReplyTo('');
$mail->isHTML(true);
$mail->Subject = "";
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->CharSet = 'utf-8';
$mail->setFrom('');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
require_once('invoicetopdf.php');
$message="";
$mail->AddStringAttachment($invoice, 'Invoice.pdf', 'base64', 'application/pdf');
$mail->Username = "";
$mail->Password = "";
$mail->addAddress($to);
$mail->Body = $message;
if (!$mail->send()) {echo "Mailer Error: " . $mail->ErrorInfo;}
else {
$mail->clearAddresses();
$mail->ClearAllRecipients();
$mail->clearAttachments();
echo "Ok";
}
} //while
//invoicetopdf.php:
$data = MySQL_Fetch_Array($vysl);
require_once('../knihovny/pdf/fpdf.php');
$pdf = new PDF();
$pdf->.....;
$invoice=$pdf->Output('S');
?>
That's a bit of an odd way to run that code repeatedly. I would define a function in your invoicetopdf.php file, load it at the top of your script, and then call the function inside the loop to get the PDF data. You're also calling mysql_fetch_array twice - once in the while loop, once in the function, meaning half your data will be going astray.
require_once('invoicetopdf.php');
while(($data=MySQL_Fetch_Array($vysl))!=NULL) {
$message="";
$mail->AddStringAttachment(generatePDF($data), 'Invoice.pdf', 'base64', 'application/pdf');
...
//invoicetopdf.php:
require_once('../knihovny/pdf/fpdf.php');
function generatePDF($data) {
$pdf = new PDF();
$pdf->.....;
return $invoice=$pdf->Output('S');
}
I also recommend moving the Username and Password out of the loop, and you probably don't need to call clearAllRecipients(); clearAddresses() is enough.
Setting SMTPDebug = 2 will let you see more of what's happening in SMTP land.
Now it works: the main problem was a mixing a class and functions together. See:Multiple PDFs in Loop with FPDF
Thank you guys!

How to convert dictionary to a string angularjs

I am currently working on my project using angularjs. I got everything already it is just that, i need to convert the dictionary list to a string separated by comma. I can only do this using python.
[{"name":"john"},{"name":"mark"},{"name":"peter"}]
I want to convert them to string
"john,mark,peter"
I would really appreciate your help. :)
.map and then .join will do
var array = [{"name":"john"},{"name":"mark"},{"name":"peter"}];
var names = array.map(function(item) {
return item.name;
}).join(',');
The map() method creates a new array with the results of calling a function for every array element. Use this to loop and then add that value to a variable.
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var string;
dict.map(function(value){
//do any stuff here
string+=value["name"]+",";
});
console.log(string);
Try map function to concatenate the values:
var dict=[{"name":"john"},{"name":"mark"},{"name":"peter"}];
var str="";
dict.map(function(a){
str+=a["name"]+",";
});
//feels ironical as question has AngularJS tag
document.getElementById("log").innerText=str;
<div id="log"></div>
You can simply iterate over each key-value pair and concat the extracted value with comma.
var obj = [{"name":"john"},{"name":"mark"},{"name":"peter"}]
var result = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
result += obj[p].name + ",";
}
}
result = result.replace(/,$/g,''); // to trim trailing comma

How to read data from csv file when file name changes at runtime after downloading

I am trying to automate download csv file and read data from there.
I tried with:
CSVReader reader = new CSVReader(new FileReader("D:\\File\\1453.csv"));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
but the problem is here I need to give the file name while mentioning the path, here I can't write the name as it is getting changed at runtime after downloading. Please suggest
If the filename is same as the download link (even if it is partial), you can get the link from the download button or whatever element it is using getAttribute("href") and then you can use it to form the filename to read from.
String fileName = driver.findElement("<download_locator>").getAttribute("href")
CSVReader reader = new CSVReader(new FileReader("D:\\File\\" + fileName));
String [] csvCell;
//while loop will be executed till the last line In CSV.
while ((csvCell = reader.readNext()) != null) {
String FName = csvCell[0];
String LName = csvCell[1];
String Email = csvCell[2];
String Mob = csvCell[3];
String company = csvCell[4];
Have you tried this? And passing in the parameter from a method?
CSVReader reader = new CSVReader(new FileReader("D:\\File\\" + provideFileName));

Objectify return List & Cursor

I am trying to use a cursor with Objectify and Google App Engine to return a subset of data and a cursor so that I can retrieve more data when the user is ready. I found an example here that looks exactly like what I need but I don't know how to return the final list plus the cursor. Here is the code I have:
#ApiMethod(name = "listIconThemeCursor") //https://code.google.com/p/objectify-appengine/wiki/Queries#Cursors
public CollectionResponse<IconTheme> listIconThemeCursor(#Named("cursor") String cursorStr) {
Query<IconTheme> query = ofy().load().type(IconTheme.class).limit(10);
if (cursorStr != null ) {
query.startAt(Cursor.fromWebSafeString(cursorStr));
}
List<IconTheme> result = new ArrayList<IconTheme>();
int count = 0;
QueryResultIterator<IconTheme> iterator = query.iterator();
while (iterator.hasNext()) {
IconTheme theme = iterator.next();
result.add(theme);
count++;
}
Cursor cursor = iterator.getCursor();
String encodeCursor = cursor.toWebSafeString();
return serial(tClass, result, encodeCursor);
}
Note that this was modified from a previous endpoint in which I returned the CollectionResponse of ALL the data. My dataset is large enough that this is no longer practical. Basically, I don't know what was in the user's function of 'serial(tClass, result, encodeCursor) that let it get returned to the user.
There is another example here but it doesn't appear to answer my question either.
I don't quite understand what you are asking, but I see one immediate bug in your code:
query.startAt(Cursor.fromWebSafeString(cursorStr));
...should be:
query = query.startAt(Cursor.fromWebSafeString(cursorStr));
Objectify command objects are immutable, functional objects.
After a long slog, I figured out that CollectionResponse has the cursor in it :(
Here is the complete code I used incorporating the comment from stickfigure above:
#ApiMethod(name = "listIconThemeCursor", path="get_cursor")
public CollectionResponse<IconTheme> listIconThemeCursor(#Named("cursor") String cursorStr) {
Query<IconTheme> query = ofy().load().type(IconTheme.class)
.filter("errors <", 10)
.limit(10);
if (cursorStr != null ) {
query = query.startAt(Cursor.fromWebSafeString(cursorStr));
}
List<IconTheme> result = new ArrayList<IconTheme>();
QueryResultIterator<IconTheme> iterator = query.iterator();
while (iterator.hasNext()) {
IconTheme theme = iterator.next();
result.add(theme);
}
Cursor cursor = iterator.getCursor();
CollectionResponse<IconTheme> response = CollectionResponse.<IconTheme> builder()
.setItems(result)
.setNextPageToken(cursor.toWebSafeString())
.build();
return response;
}

Sort an Array, populated by an IsolatedStorageFile text file seems to move the 0 entry

I have the code below that splits a text file from IsolatedStorage, populates an Array with the data, sorts it, and then assigns it as the source for a ListPicker:
var splitFile = fileData.Split(';');
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
However, it doesn't seem to populating the array correctly and the sorting doesn't appear to be working as expected either.
The testArray[0] is blank, when it should be populated. When the output is shown the entry that should be at [0] appears at the bottom.
BEFORE SORTING:
AFTER SORTING:
It's only in sorting the array that it seems to screw up the order.
UPDATE: I tried the suggested:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] testArray = splitFile;
Array.Sort<string>(testArray);
testLocationPicker.ItemsSource = testArray;
This still results in the second screenshot, above.
When the app first ever runs I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
store.CreateDirectory("testLocations"); // Create a directory
IsolatedStorageFileStream rootFile = store.CreateFile("locations.txt"); // Create a file in the root.
rootFile.Close(); // Close File
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
string filePath = "locations.txt";
if (store.FileExists(filePath)) {
Debug.WriteLine("Files Exists");
StreamWriter sw =
new StreamWriter(store.OpenFile(filePath,
FileMode.Open, FileAccess.Write));
Debug.WriteLine("Writing...");
sw.WriteLine("Chicago, IL;");
sw.WriteLine("Chicago, IL (Q);");
sw.WriteLine("Dulles, VA;");
sw.WriteLine("Dulles, VA (Q);");
sw.WriteLine("London, UK;");
sw.WriteLine("London, UK (Q);");
sw.WriteLine("San Jose, CA;");
sw.WriteLine("San Jose, CA (Q);");
sw.Close();
Debug.WriteLine("Writing complete");
}
Then when I add to the file I do this:
StringBuilder sb = new StringBuilder(); // Use a StringBuilder to construct output.
var store = IsolatedStorageFile.GetUserStoreForApplication(); // Create a store
string[] filesInTheRoot = store.GetFileNames(); // Store all files names in an array
Debug.WriteLine(filesInTheRoot[0]); // Show first file name retrieved (only one stored at the moment)
byte[] data = Encoding.UTF8.GetBytes(locationName + ";");
string filePath = "locations.txt";
if (store.FileExists(filePath))
{
using (var stream = new IsolatedStorageFileStream(filePath, FileMode.Append, store))
{
Debug.WriteLine("Writing...");
stream.Write(data, 0, data.Length); // Semi Colon required for location separation in text file
stream.Close();
Debug.WriteLine(locationName + "; added");
Debug.WriteLine("Writing complete");
}
}
I'm splitting using a ";" could this be an issue?
There's no problem with the sort: 'space' is considered to come before 'a', so it appears on top of the list. The real problem is: why do you have an empty entry to begin with?
My guess is that, when creating the file, you're separating every entry with ;, including the last one. Therefore, when parsing the data with the string.Split method, you're left with an empty entry at the end of your array.
An easy way to prevent that is to use an overload of the string.Split method that filters empty entries:
var splitFile = fileData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
I went a different way using IsolatedStorageSetting and storing Arrays/Lists to do what I wanted.

Resources