How to save objects in a proper way with the stream writer? - streamwriter

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

Related

How can i append a pdf into another? Alfresco

How can i append a pdf into another?
I tried using this code, but I am getting java.lang.NullPointerException when i try to getContentInputStream.
what am I doing wrong? How can I attach one pdf to another?
PDDocument pdfTarget = null;
InputStream is = null;
InputStream tis = null;
for (ChildAssociationRef file: quotationsFiles) {
try {
NodeRef toAppend = file.getChildRef(); //workspace://SpacesStore/11bce382-45bf-4c67-95bc-a65361b323ef
ContentReader append = getReader(toAppend);
is = append.getContentInputStream(); // Here iam getting java.lang.NullPointerException
NodeRef targetNodeRef = reportFile.getNodeRef();
ContentReader targetReader = getReader(targetNodeRef);
tis = targetReader.getContentInputStream();
String fileName = String.valueOf(serviceRegistry.getNodeService().getProperty(targetNodeRef, ContentModel.PROP_NAME));
// stream the document in
pdf = PDDocument.load(is);
pdfTarget = PDDocument.load(tis);
// Append the PDFs
PDFMergerUtility merger = new PDFMergerUtility();
merger.appendDocument(pdfTarget, pdf);
merger.setDestinationFileName(fileName);
merger.mergeDocuments();
} catch (Exception e) {
//throw new AlfrescoRuntimeException("IOException", e);
ColorLogUtil.debug(LOGGER, "IOException Error caused by :" + e);
}
}
private ContentReader getReader(NodeRef nodeRef) {
if (serviceRegistry.getNodeService().exists(nodeRef) == false) {
throw new AlfrescoRuntimeException("NodeRef: " + nodeRef + " does not exist");
}
QName typeQName = serviceRegistry.getNodeService().getType(nodeRef);
if (serviceRegistry.getDictionaryService().isSubClass(typeQName, ContentModel.TYPE_CONTENT) == false) {
throw new AlfrescoRuntimeException("The selected node is not a content node");
}
ContentReader contentReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
if (contentReader == null) {
throw new AlfrescoRuntimeException("The content reader for NodeRef: " + nodeRef + "is null");
}
return contentReader;
}
See if this code works for you:
public NodeRef mergePdfs(List<NodeRef> nodeRefList, String fileName,NodeRef destinationNode)
throws FileNotFoundException,FileExistsException,Exception {
InputStream originalInputStream = null;
ContentReader reader = null;
NodeRef newDocNoderef = null;
PDFMergerUtility PDFmerger = new PDFMergerUtility();
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
try {
LOGGER.debug("Merging of Doc Started");
for (NodeRef node : nodeRefList) {
reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
originalInputStream = reader.getContentInputStream();
PDFmerger.addSource(originalInputStream);
}
PDFmerger.setDestinationStream(outputstream);
PDFmerger.mergeDocuments();
if(originalInputStream!=null) {
originalInputStream.close();
}
newDocNoderef = writeContentToAlfresco(outputstream, nodeRefList, fileName,destinationNode);
LOGGER.debug("Documents are merged and new pdf is created at "+newDocNoderef);
} finally {
if(outputstream!=null)
outputstream.close();
}
return newDocNoderef;
}
public NodeRef writeContentToAlfresco(ByteArrayOutputStream outputstream, List<NodeRef> childRefList,
String fileName,NodeRef destinationNode) throws FileExistsException,IOException,Exception {
NodeRef pdf = null;
Map<QName, Serializable> props = new HashMap<>();
Map<Date, NodeRef> dateMap = new HashMap<Date, NodeRef>();
NodeRef parentNodeRef=null;
try {
LOGGER.debug("Upload to Alfresco Started");
for(NodeRef noderef : childRefList) {
Date date = (Date) nodeService.getProperty(noderef, ContentModel.PROP_MODIFIED);
dateMap.put(date, noderef);
}
Map<Date, NodeRef> m1 = new TreeMap<Date, NodeRef>(dateMap);
Map.Entry<Date, NodeRef> entry = m1.entrySet().iterator().next();
NodeRef finalnodeRef = entry.getValue();
if(destinationNode!=null) {
parentNodeRef = destinationNode;
}else {
parentNodeRef = nodeService.getPrimaryParent(finalnodeRef).getParentRef();
}
QName[] myModelProps = CommonConstants.myModelProps;
for (QName myModelProp : myModelProps) {
Serializable object = nodeService.getProperty(finalnodeRef, myModelProp);
props.put(myModelProp, object);
}
FileInfo pdfInfo = fileFolderService.create(parentNodeRef, fileName + ".pdf",
MyModel.TYPE_CUSTOM_MYMODEL_TYPE);
pdf = pdfInfo.getNodeRef();
nodeService.setProperties(pdf,props);
nodeService.setProperty(pdf, ContentModel.PROP_TITLE,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_TITLE));
nodeService.setProperty(pdf, ContentModel.PROP_DESCRIPTION,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_DESCRIPTION));
nodeService.setProperty(pdf,ContentModel.PROP_NAME,fileName + ".pdf");
ContentWriter writer = contentService.getWriter(pdf, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
writer.setEncoding("UTF-8");
writer.putContent(new ByteArrayInputStream(outputstream.toByteArray()));
LOGGER.debug("Upload to Alfresco Ended");
} catch(FileExistsException fee) {
ExceptionUtils.printRootCauseStackTrace(fee);
throw new FileExistsException(parentNodeRef, fileName);
}
catch (Exception e) {
ExceptionUtils.printRootCauseStackTrace(e);
throw new Exception(e);
} finally {
if (outputstream != null)
outputstream.close();
}
return pdf;
}
This actually seems like one of the features we support in alfresco-pdf-toolkit out of the box. You could either use that addon, or get some inspiration from the code backing it.

Javafx TextArea setText method using text files

Hi I am trying to create a method to be used in the TextArea setText method for javafx.
I am trying to get a method that does this:
public static void setTextArea(String fileName) {
String line;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(fileReader);
while ((line = buffer.readLine()) != null) {
out.println(line);
}
buffer.close();
} catch //etc etc
but I can't use it in the setText method because it is a void method.
Can anyone help translate this method so it could work in the TextArea setText method?
-Thanks!
You just pring out the lines to System.out I guess. You have to add up the content of the text file by doing something like this
public static void setTextArea(String fileName) {
String line;
String content;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(fileReader);
while ((line = buffer.readLine()) != null) {
out.println(line);
content += line;
}
buffer.close();
} catch //etc etc
Then you can either return content or call setText(content) from the TextArea class. If it's a big file, then using StringBuilder would probably be a better idea instead of concatenating each line.
You will have to get the data from the file and and set the data to textArea..
TextArea txtArea = new TextArea();
String data = getDataForTextArea(String fileLocation);
txtArea.setText(data);
public String getDataForTextArea(String fileLocation) {
InputStream inputStream = new FileInputStream(fileLocation);
if (inputStream != null) {
int b;
String txtData = "";
try {
while ((b = inputStream.read()) != -1) {
txtData += (char) b;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
inputStream.close();
}
return txtData;
}
Make sure to check for nullpointerException.

SignalR. Timer is not stopping on the server

We are using SignalR for information exchange.
When the web browser is connected a timer starts, but it is not stopping when user close the browser.
Here is the code. starttimer function runs when browser connected.
When user disconnect the browser, timer still running on the server.
[HubName("myChatHub")]
public class InboundCallsDataShare : Hub
{
private OverrideTimer timer ;
private List<GroupNConnectionId> groupsList = new List<GroupNConnectionId>();
public void send(string message)
{
Clients.All.addMessage(message);
//Clients..addMessage(message);
}
public void starttimer(string queue)
{
//var connectionId = this.Context.ConnectionId;
//GroupNConnectionId objGroupNConnectionId=new GroupNConnectionId();
//objGroupNConnectionId.Group = queue;
//objGroupNConnectionId.ConnectionID = connectionId;
//if(groupsList.Contains(objGroupNConnectionId))return;
//////////////////////////////////////////////////////
//groupsList.Add(objGroupNConnectionId);
Groups.Add(this.Context.ConnectionId, queue);
timer = new OverrideTimer(queue);
timer.Interval = 15000;
timer.Elapsed +=new EventHandler<BtElapsedEventArgs>(timer_Elapsed);
//first time call
timer_Elapsed(timer,new BtElapsedEventArgs(){Queue = queue});
//ends
timer.Start();
Console.WriteLine("Timer for queue " +queue);
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
//timer.Stop();
return base.OnDisconnected();
}
public void getdatafromxml(string queue)
{
string list = (new Random()).Next(1, 10000).ToString();
Clients.All.getList(list);
//Clients..addMessage(message);
}
public ICBMObject GetInterationList(string queue)
{
//ININInterations.QueueListViewItemData _obj = new ININInterations.QueueListViewItemData();
return GetInboundCallCountFromXML(queue);
//return _obj.MainFunctionIB();
}
void timer_Elapsed(object sender, BtElapsedEventArgs e)
{
ICBMObject objICBMObject = GetInboundCallCountFromXML(e.Queue);
Clients.Group(e.Queue).getList(objICBMObject);
CreateFile(e.Queue);
//Clients.All.getList(objICBMObject);
}
private void CreateFile(string queue)
{
string path = #"D:\t.txt";
string text = File.ReadAllText(path);
text += queue+ DateTime.Now.ToString() + Environment.NewLine;
File.WriteAllText(path, text);
}
public ICBMObject GetInboundCallCountFromXML(string queue)
{
FileStream fs = null;
int totalInboundCalls = 0,
totalInboundCallsUnassigned = 0;
string longestDuration = "";
bool updateText = false;
try
{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "InboundXML/" + queue + ".xml",
FileMode.Open, FileAccess.Read);
if (fs.CanRead)
{
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName(queue);
for (i = 0; i <= xmlnode.Count - 1; i++)
{
totalInboundCalls = Convert.ToInt32(xmlnode[i].ChildNodes.Item(0).InnerText.Trim());
totalInboundCallsUnassigned = Convert.ToInt32(xmlnode[i].ChildNodes.Item(1).InnerText.Trim());
longestDuration = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
}
updateText = true;
}
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
return new ICBMObject()
{
TotalInboundCalls = totalInboundCalls,
TotalInboundCallsUnassigned = totalInboundCallsUnassigned,
LongestDuration = longestDuration,
UpdateText = updateText
//string.Format("{0:D2}:{1:D2}:{2:D2}",
// _LongetInbound.Hours,
// _LongetInbound.Minutes,
// _LongetInbound.Seconds)
};
}
}
Besides the fact that its commented out? Did you put a break point on the timer to see if its getting hit at all? It might be that there is a delay in calling the onDisconnect, if the timeout property is set too large, it might not fire. it might be entering onReconnected if it does not know the client is closed.

Handle file name duplication when creating files in alfresco

I have a Java-backed webscript in repo tier that creates files (with given name) in a given folder in Alfresco.
To handle the file name duplication issue I wrote this code:
NodeRef node = null;
try {
node = createNode(fullName, folderNodeRefId);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRefId);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
ContentWriter writer = serviceRegistry.getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(getFileFormatMimetype(fileFormat));
writer.putContent(inputStream);
writer.guessEncoding();
and
private NodeRef createNode(String filename, String folderNodeRefId)
throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
NodeRef folderNodeRef = new NodeRef(folderNodeRefId);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService()
.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,
props)
.getChildRef();
}
The codes work very fine if there is no file name duplication (a new name). But it does nothing when there is a duplication, although it executes without any errors! When I test it it doesn't throw any exceptions but no file is created either!
Any hints about the cause of that?
Thanks,
I tested this code , It's working fine
#Test
public void createNode() {
AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
NodeRef node = null;
String fileFormat = "txt";
String filename = "test";
NodeRef folderNodeRef = getCompanyHome();
//Create first node
node = createNode(filename, folderNodeRef);
try {
node = createNode(filename, folderNodeRef);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRef);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
}
private NodeRef getCompanyHome() {
return nodeLocatorService.getNode("companyhome", null, null);
}
private NodeRef createNode(String filename, NodeRef folderNodeRef) throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService().createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,props).getChildRef();
}

Retrieving Multiple rows from SQLite in Xamarin iOS

I'm doing an app with Xamarin iOS.
I put a UITableView on XCode, so that when I click on a button, it retrieves from the database and slot it in. I'm able to put it onto a row, but couldn't figure it out how to have multiple rows of data in it. This is my partial code from which I'm able to display a row of data.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
while (dr.Read())
{
var table = new UITableView(this.retrieveData.Frame);
string[] tableItems = new String[] {dr["admin_num"] + ", " + dr["name"]};
table.Source = new TableSource(tableItems);
Add (table);
}
You are creating a completely new TableView for each row in your data. Instead, you should loop through your data and create a data structure (List, array, etc) containing ALL of the data you want to display, and then pass that data to your TableView/Source.
cmd.CommandType = CommandType.Text;
dr = cmd.ExecuteReader();
// you will need a class mydata with Num and Name properties
List<mydata> data = new List<mydata>();
while (dr.Read())
{
data.Add(new mydata { Num = dr["admin_num"], Name = dr["name"] });
}
dr.Close();
var table = new UITableView(this.retrieveData.Frame);
table.Source = new TableSource(data);
Add (table);
What you need to do is this:
public List<DemoClass> getDemoClassList()
{
List<DemoClass> lstDemoClass;
DemoClass objDemoClass;
try
{
String strCommandText;
strCommandText = "SELECT * FROM DemoClass ";
command = new SqliteCommand(strCommandText, connection);
lstDemoClass = new List<DemoClass>();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
objDemoClass = new Homes(false);
objDemoClass.ID = Convert.ToInt32(reader[0]);
objDemoClass.Name = Convert.ToString(reader[1]);
lstDemoClass.Add(objDemoClass);
}
}
return lstDemoClass;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
command = null;
lstDemoClass = null;
objDemoClass = null;
}
}
public void BindList()
{
List<DemoClass> lstDemoClass = new List<DemoClass>();
DemoClass hm = new DemoClass();
lstDemoClass = (List<DemoClass>)hm.getDemoClassList();
TableViewDataSource tdatasource = new TableViewDataSource(this, lstDemoClass);
table.Hidden = false;
table.DataSource = tdatasource;
table.Delegate = new TableViewDelegate(this, table, lstDemoClass);
table.ReloadData();
}
The getDemoClassList() will give the retrieved list from SQLite table, and later you can bind the list to the table datasource.
UPDATE:
As per your request I have updated my comment with the code for datasource and its delegate classes.
Now in this same class you need to add the following subclasses:
#region TableDelegate
public class TableViewDelegate : UITableViewDelegate
{
private DemoPageViewController _Controller;
private List<DemoClass> lst;
public TableViewDelegate(DemoPageViewController controller ,UITableView tableView, List<DemoClass> tblList)
{
try
{
this._Controller = controller;
this.lst = tblList;
}
catch(Exception ex)
{
}
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
try
{
//This loads the activity spinner till the selection code is completed
_Controller._loadPop = new LoadingOverlay (new System.Drawing.RectangleF(0,0,_Controller.View.Frame.Width,_Controller.View.Frame.Height),"Loading...");
_Controller.View.Add ( _Controller._loadPop );
// spin up a new thread to do some long running work using StartNew
Task.Factory.StartNew (
// tasks allow you to use the lambda syntax to pass work
() => {
InvokeOnMainThread(delegate{
DemoClass f = lst[indexPath.Row];
//Add your code here, usually some navigation or showing a popup
});
}).ContinueWith(t => InvokeOnMainThread(() => {
//Hide the activity spinner
_Controller._loadPop.Hide();
}));
}
catch(Exception ex)
{
}
finally
{
}
}
}
#endregion
#region TableDataSource
private class TableViewDataSource : UITableViewDataSource
{
static NSString kCellIdentifier = new NSString("MyIdentifier");
private List<DemoClass> lst;
private DemoPageViewController controller;
public TableViewDataSource (DemoPageViewController controller ,List<DemoClass> tblLst)
{
this.controller = controller;
this.lst = tblLst;
}
public override int NumberOfSections (UITableView tableView)
{
return 1;
}
public override int RowsInSection (UITableView tableView, int section)
{
return lst.Count;
}
// Override to support conditional editing of the table view.
public override bool CanEditRow (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
// Return false if you do not want the specified item to be editable.
return false;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
try
{
UITableViewCell cell = tableView.DequeueReusableCell (kCellIdentifier);
if (cell == null)
{
cell = new UITableViewCell (UITableViewCellStyle.Subtitle, kCellIdentifier);
cell.Tag = Environment.TickCount;
}
DemoClass objDemo = lst[indexPath.Row];
cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
cell.ImageView.Image = UIImage.FromFile("Images/CameraImg.png");
cell.DetailTextLabel.Text = "Show some detail: " + objDemo.DemoDescription.ToString();
cell.TextLabel.Text = "Some Title: " + objDemo.DemoTitle.ToString();
return cell;
}
catch(Exception ex)
{
return null;
}
finally
{
}
}
}
#endregion
Hope it helps.

Resources