Which way of returning list is better? New in local or Clear in local - return

For example:
New in local
class AAA{
public List<STH> GetList(){
List<STH>list = new List<STH>();
//do something
return list;}
}
Clear in local
class BBB{
List<STH> list = new List<STH>();
public List<STH> GetList(){
list.Clear();
//do something
return list;
}
}
Who calls GetList() takes the lists which returned as his field.
Which way is the better way?

Related

Neo4j - Custom converter for field of type List

I am trying to write a custom converter for a nested object so that this object gets saved as string in Neo4j database.
I am using #Convert annotation on my field and passing ImageConverter.class which is my AttributeConverter class.
Everything works fine as expected and I am able to save string representation of Image class in Neo4j db.
However, now instead of single image I want to have List<Image> as my nested field. In this case, putting #Convert(ImageConverter.class) doesn't work.
I see that there is a class called ConverterBasedCollectionConverter which gets used when I have a field of type List<LocalDateTime.
However, I couldn't find any exammples on how to use this class in case of custom converters.
Please can anyone help me with this or if there is any other approach to use custom converter on field of type List.
I am using Neo4j (version 3.4.1) and Spring-data-neo4j (5.0.10.RELEASE) in my application. I am also using OGM.
PS: I am aware that it is advised to store nested objects as separate node establishing a relationship with parent object. However, my use case demands that the object be stored as string property and not as separate node.
Regards,
V
It is not so difficult as I assumed it would be.
Given a class (snippet)
#NodeEntity
public class Actor {
#Id #GeneratedValue
private Long id;
#Convert(MyImageListConverter.class)
public List<MyImage> images = new ArrayList<>();
// ....
}
with MyImage as simple as can be
public class MyImage {
public String blob;
public MyImage(String blob) {
this.blob = blob;
}
public static MyImage of(String value) {
return new MyImage(value);
}
}
and a converter
public class MyImageListConverter implements AttributeConverter<List<MyImage>, String[]> {
#Override
public String[] toGraphProperty(List<MyImage> value) {
if (value == null) {
return null;
}
String[] values = new String[(value.size())];
int i = 0;
for (MyImage image : value) {
values[i++] = image.blob;
}
return values;
}
#Override
public List<MyImage> toEntityAttribute(String[] values) {
List<MyImage> images = new ArrayList<>(values.length);
for (String value : values) {
images.add(MyImage.of(value));
}
return images;
}
}
will print following debug output on save that I think is what you want:
UNWIND {rows} as row CREATE (n:Actor) SET n=row.props RETURN row.nodeRef as ref, ID(n) as id, {type} as type with params {type=node, rows=[{nodeRef=-1, props={images=[blobb], name=Jeff}}]}
especially the images part.
Test method for this looks like
#Test
public void test() {
Actor jeff = new Actor("Jeff");
String blobValue = "blobb";
jeff.images.add(new MyImage(blobValue));
session.save(jeff);
session.clear();
Actor loadedActor = session.load(Actor.class, jeff.getId());
assertThat(loadedActor.images.get(0).blob).isEqualTo(blobValue);
}
I am came up with a solution to my problem. So, in case you want another solution along with the solution provided by #meistermeier, you can use the below code.
public class ListImageConverter extends ConverterBasedCollectionConverter<Image, String>{
public ListImageConverter() {
super(List.class, new ImageConverter());
}
#Override
public String[] toGraphProperty(Collection<Image> values) {
Object[] graphProperties = super.toGraphProperty(values);
String[] stringArray = Arrays.stream(graphProperties).toArray(String[]::new);
return stringArray;
}
#Override
public Collection<Image> toEntityAttribute(String[] values) {
return super.toEntityAttribute(values);
}
}
ImageConverter class just implements AttributeConverter<Image, String> where I serialize and deserialize my Image object to/from json.
I chose to go with this approach because I had Image field in one object and List<Image> in another object. So just by changing #Convert(ListImageConverter.class) to #Convert(ImageConverter.class) I was able to save list as well as single object in Neo4j database.
Note: You can skip overriding toEntityAttribute method if you want. It doesn't add much value.
However you have to override toGraphProperty as within Neo4j code it checks for presence of declared method with name toGraphProperty.
Hope this helps someone!
Regards,
V

Updating a single value in a database

I'm trying to update a value in an existing row of a database but I can't seem to get the changes to stick. the code in my controller currently looks like this:
[HttpPost]
public ActionResult AddCredit(int employeeNumber, decimal amount)
{
var employee = new GetEmployeeForEmployeeNumber<Employee>(employeeNumber).Query().FirstOrDefault();
var employeeAccount = new GetEmployeeAccountForId<EmployeeAccount>(employee.Id).Query().FirstOrDefault();
employeeAccount.Credit = employeeAccount.Credit + amount;
db.SaveChanges();
return RedirectToAction("Home", new { employeeNumber });
}
Based on research that I've done into the subject, this should work as I've modelled it off working example. The Credit does increase by the given amount but after the db.SaveChanges, the values in the database are still as they were.
Am I missing something obvious?
Edit:
The GetEmployeeAccountForId looks like this:
public class GetEmployeeAccountForId<T>
{
private TestContext db = new TestContext();
private readonly int _id;
public GetEmployeeAccountForId(int id)
{
_id = id;
}
public IQueryable<EmployeeAccount> Query()
{
return from employeeAcount in db.EmployeeAccounts
where employeeAcount.Id == _id
select employeeAcount;
}
}
Try this:
employeeAccount.Credit = employeeAccount.Credit + amount;
db.Entry(employeeAccount).State = EntityState.Modified;
db.SaveChanges();
Update
You have to "tell" EF to track changes of editet entity, that's why
db.Entry(employeeAccount).State = EntityState.Modified
is required.
But You also shoudn't use 2 different instances of one DbContext. I highly recomend using DI, and set DbContext life time to instance per request.

Need to pass a ds(data structure) when Http server is being started, and to make that ds global across controllers

So,
Here is the code setup.
There is a driver application, which starts the HTTP server(ASP.NET core Web API project).
The method called by driver application for starting HTTP server is
this:
public class Http_Server
{
public static ConcurrentQueue<Object> cq = new ConcurrentQueue<Object>();
public static void InitHttpServer(ConcurrentQueue<Object> queue)
{
cq = queue;
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
Controller Action Task:
[HttpPost]
[Route("XYZ")]
public virtual IActionResult AddXYZ([FromBody]List<Resourcemembers> resourcemembers)
{
//add something to ds
Http_Server.cq.Enqueue(new object());
//respond back
return new ObjectResult(example);
}
The data structure(a concurrent queue) being passed is to be made visible at controller level(like a global variable accessible across all controllers).
Is it fine to make the ds a static variable and access it across controllers?
Or Is there a way to pass this ds across to different layers?
This is my go at a better solution for this. What you are trying to do doesn't seem like the best way to approach this.
First, you want to enable caching in the application by calling the AddMemoryCache in the application StartUp.ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMemoryCache();
...
}
Then, you want to use the cache. Something like this should get you going in the right direction.
public class XYZController : Controller {
private IMemoryCache _memoryCache;
private const string xyzCacheKey = "XYZ";
public XYZController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
[HttpPost("XYZ")]
public IActionResult AddXYZ([FromBody]ResourceMember[] resourceMembers)
{
try
{
if (!_memoryCache.TryGetValue(xyzCacheKey, out ConcurrentQueue<Object> xyz))
{
xyz = new ConcurrentQueue<Object>();
_memoryCache.Set(xyzCacheKey, xyz, new MemoryCacheEntryOptions()
{
SlidingExpiration = new TimeSpan(24, 0, 0)
});
}
xyz.Enqueue(resourceMembers);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
public class ResourceMember { }
What this does is allow you to use a Memory Cache to hold your object(s), and what ever you Enqueue in the ConcurrentQueue object, should you stay with that as your main object within the Cache. Now, you can cache any object type in the MemoryCache, and pull the value when you need to based on the key you gave it when you added it to the cache. In the case above, I created a const named xyzCacheKey with a string value of XYZ to use as the key.
That static global variable thing you are trying is just not... good.
If this doesn't help, let me know in a comment, I will delete the answer.
Good luck!

MVC simple insert not updating database

The is driving me nuts. Im trying to do a "simple" record insert and I can only get it to work if I store the context in a variable or create a local context. I tried to keep the context and model object tied together but no luck so far.
public class TransactionDataAccessLayer
{
public cartableContext transactionContext
{
get
{
return new cartableContext();
}
}
}
class TransactionBusinessLayer
{
Cardata newCar = new Cardata();
public void addCar(Cardata cd)
{
try
{
//this works. Storing the context in ctc2 seems to make it work???
TransactionDataAccessLayer tdal = new TransactionDataAccessLayer();
cartableContext ctc2 = tdal.transactionContext;
ctc2.cardata.Add(cd);
ctc2.SaveChanges();
//this does not work
tdal.transactionContext.cardata.Add(cd);
tdal.transactionContext.Entry(cd).State = EntityState.Modified;
tdal.transactionContext.SaveChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
}
}
}
In C#, properties are basically just fancy methods, designed to make it easier to access private fields. Therefore, returning a new Context in your getter will do just that; return a new one each time it is accessed. To preserve state, you need to contain your context in a private field, like so:
public class TransactionDataAccessLayer
{
private cartableContext _transactionContext;
public cartableContext transactionContext
{
get
{
if (_transactionContext == null)
_transactionContext = new cartableContext();
return _transactionContext;
}
}
}

Smarty Fetch is not loading anything into my variable

I have a class that sets up my smarty instances:
class View {
protected $templateEngine;
protected $templateExtension = '.tpl';
public function __construct(){
global $ABS_PUBLIC_PATH;
global $ABS_PUBLIC_URL;
$this->templateEngine = new Smarty();
$this->templateEngine->error_reporting = E_ALL & ~E_NOTICE;
$this->templateEngine->setTemplateDir($ABS_PUBLIC_PATH . '/templates/');
$this->templateEngine->setCompileDir($ABS_PUBLIC_PATH . '/templates_c/');
$this->templateEngine->assign('ABS_PUBLIC_URL', $ABS_PUBLIC_URL);
if(isset($_SESSION['loggedIn'])){
$this->assign('session', $_SESSION);
}
}
public function assign($key, $value){
$this->templateEngine->assign($key, $value);
}
public function display($templateName){
$this->templateEngine->display($templateName . $this->templateExtension);
}
public function fetch($templateName){
$this->templateEngine->fetch($templateName . $this->templateExtension);
}
}
Then in my functions, I use the class like this:
public function showMeSomething()
{
$view = new View();
$view->assign('session', $_SESSION);
$view->display('header');
$view->display('index');
$view->display('footer');
}
Now, I'm trying to fetch some data into a variable, in order to send emails from my template files as well. Unfortunately, this var_dumps below (both of them) output NULL - even though the template file referenced has a lot of HTML in it. Furthermore, changing the word fetch to display below will correctly display the template file. So, the problem certainly lies within the fetch command. I'm not sure what to do to continue debugging.
function emailPrep($data,){
$mailView = new View();
$emailHTML = $mailView->fetch('myEmail');
var_dump($mailView->fetch("myEmail"));
var_dump($emailHTML);
}
Your code must be
public function fetch($templateName){
return $this->templateEngine->fetch($templateName . $this->templateExtension);
}

Resources