c# – Create a Generic Controller that has all entities in OData Web API

I have a Master table in database with list of other tables whose details I want to fetch through the API.
Steps to be incorporated –
1. Create a Generic OData Controller to fetch Master table details.
2. Because does not want to create controller for each entity in Master table, so want each entity in Master table to get registered automatically so that it can be accessed through API without building each of their controller.

I am pretty new to building Web APIs using OData. So require some help as to how go forward with this requirement

unity – I wrote a 2D player controller, but that is not working perfectly

I wrote a C# script to control a 2D player, but the script is not fully working. When I press the right arrow/d key to move the player is not moving in the right direction, but I have done the same exact thing for left key which works fine.The script shows no errors too.Kindly help me to solve the issue.The code is:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    (SerializeField) private Rigidbody2D _rb2d;
    (SerializeField) private float _speed;
    (SerializeField) private float _jump;
    private static float _tempspeed;
    private static float _tempjump;
    private bool _isRight;
    private bool _isLeft;
    private bool _isSpace;

    private void Start()
    {
        _isLeft = false;
        _isRight = false;
        _isSpace = false;
        _speed = 5f;
        _jump = 7f;
        _tempjump = _jump;
        _tempspeed = _speed;
    }

    private void Update()
    {
        ReadInput();
    }

    private void FixedUpdate()
    {
        Move();
    }

    private void ReadInput()
    {
        if (UnityEngine.Input.GetKey("d") || UnityEngine.Input.GetKey("right"))
        {
            _isRight = true;
        }else {
            _isRight = false;
        }
        if (UnityEngine.Input.GetKey("a") || UnityEngine.Input.GetKey("left"))
        {
            _isLeft = true;
        }else {
            _isLeft = false;
        }
        if (UnityEngine.Input.GetKey("w") || UnityEngine.Input.GetKey("up"))
        {
            _isSpace = true;
        }else {
            _isSpace = false;
        }
    }

    private void Move()
    {
        Vector2 speedVectorRight=new Vector2(_tempspeed,_rb2d.velocity.y);
        Vector2 speedVectorLeft=new Vector2(-_tempspeed,_rb2d.velocity.y);
        Vector2 jumpVector=new Vector2(_rb2d.velocity.x,_tempjump);

        if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }
        if (_isLeft)
        {
            _rb2d.velocity = speedVectorLeft;
        }else {
            speedVectorLeft.x=0f;
            _rb2d.velocity = speedVectorLeft;
        }
        if (_isSpace)
        {
            _rb2d.velocity=jumpVector;
        }
    }

When I tried to print debug statements in different parts of if statements, they work fine. The problem in my observation is in :

if (_isRight)
        {
            _rb2d.velocity = speedVectorRight;
        }else {
            speedVectorRight.x=0f;
            _rb2d.velocity = speedVectorRight;
        }

The _rb2.velocity is not accepting speedVectorRight I guess.Thanks in advance!

asp.net – Como criar um Controller para o ApplicationUser

Boa Tarde,
Estou tentando criar uma area de administrador para administrar as contas do banco de dados, mas estou tendo dificuldades, tenho a classe ApplicationUser e a classe LoginViewModel:

public class LoginViewModel 
{
    (Required)
    (Display(Name = "Usuario"))
    public string UserName { get; set; }
    (Required)
    (EmailAddress)
    (DataType(DataType.EmailAddress))
    public string Email { get; set; }
    (DataType(DataType.EmailAddress))
    (Display(Name = "Confirmar Email"))
    (Compare("Email", ErrorMessage = "O email e a confimação de email não são iguais."))
    public string ConfirmEmail { get; set; }
    (Required)
    (DataType(DataType.Password))
    public string Password { get; set; }
    (DataType(DataType.Password))
    (Display(Name = "Confirmar senha"))
    (Compare("Password", ErrorMessage = "A senha e a confimação de senha não são iguais."))
    public string ConfirmPassword { get; set; }
    (Required)
    (Display(Name = "Primeiro nome"))
    (DataType(DataType.Text))
    public string PrimeiroNome { get; set; }
    (Required)
    (Display(Name = "Ultimo nome"))
    (DataType(DataType.Text))
    public string UltimoNome { get; set; }
    (Required)
    (Display(Name = "Numero para contato"))
    (DataType(DataType.PhoneNumber))
    public  string PhoneNumber { get; set; }
    (Required)
    (Display(Name = "Data de Nascimento"))
    (DataType(DataType.Date))
    public string DataNascimento { get; set; }
    public string ReturnUrl { get; set; }
    (Display(Name = "Lembrar senha?"))
    public bool RememberMe { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public string PrimeiroNome { get; set; }
    public string UltimoNome { get; set; }
    public string DataNascimento { get; set; }
}

queria criar uma tela mais ou menos assim:
inserir a descrição da imagem aqui

O que eu faco, estou perdido.

php – Laravel Page Controller

Aim: To make pages located in site.com/page-1, site.com/page-2. Those pages are pretty much static so I won’t use database.

First, I’ve created the PageController.

class PageController extends Controller
{

 public function page($slug)
 {
  $page = $this->pageContents($slug);
  return view('page', ('page' => $page));
 }

 public function pageContents($slug)
 {
  $page = ();
  $page("slug") = $slug;
  if ($slug == "page-1") {
   $page("title") = "Page 1";
   $page("content") = "Content..";
  }

  if ($slug == "page-2") {
   $page("title") = "Page 2";
   $page("content") = "Content..";
  }  

  return $page;
 }
}

web.php (Routes):

Route::get('/{page-1}', 'PageController@page')->name('page-1');
Route::get('/{page-2}', 'PageController@page')->name('page-2');

Would appreciate any reviews!

magento2 – La validation de la demande a échoué pour l'action "Apriljune Testimonial Controller Index Add Interceptor

Voici le contrôleur qui est responsable de l'ajout des données de formulaire du frontend à plusieurs tables de base de données.

namespace ApriljuneTestimonialControllerIndex;

use MagentoFrameworkAppActionAction;
use MagentoFrameworkAppActionContext;
use MagentoFrameworkAppResponseInterface;
use ApriljuneTestimonialModelTestimonial;
use ApriljuneTestimonialModelAuthor;
use ApriljuneTestimonialModelSocial;
use ApriljuneTestimonialModelContent;
use ApriljuneTestimonialModelResourceModelTestimonial as TestimonialResource;
use ApriljuneTestimonialModelResourceModelAuthor as AuthorResource;
use ApriljuneTestimonialModelResourceModelSocial as SocialResource;
use ApriljuneTestimonialModelResourceModelContent as ContentResource;
use MagentoFrameworkControllerResultFactory; 

class Add extends Action
 {
/**
 * @var Testimonial
 */
private $testimonial;

/**
 * @var Social
 */
private $social;

/**
 * @var Content
 */
private $content;

/**
 * @var Author
 */
private $author;

/**
 * @var TestimonialResource
*/
private $testimonialResource;

/**
 * @var SocialResource
*/
private $socialResource;

/**
 * @var ContentResource
*/
private $contentResource;

/**
 * @var AuthorResource
*/
private $authorResource;

/**
 * Add constructor.
 * @param Context $context
 * @param Testimonial $testimonial
 * @param Social $social
 * @param Author $author
 * @param Content $content
 * @param TestimonialResource $testimonialResource
 * @param SocialResource $socialResource
 * @param ContentResource $contentResource
 * @param AuthorResource $authorResource
 */

public function __construct(

    Context $context,
    Testimonial $testimonial,
    Social $social,
    Author $author,
    Content $content,
    TestimonialResource $testimonialResource,
    SocialResource $socialResource,
    AuthorResource $authorResource,
    ContentResource $contentResource
)
{
    parent::__construct($context);
    $this->testimonial = $testimonial;
    $this->social      = $social;
    $this->content     = $content;
    $this->author      = $author;

    $this->testimonialResource = $testimonialResource;
    $this->socialResource      = $socialResource;
    $this->contentResource     = $contentResource;
    $this->authorResource      = $authorResource;
}

/**
 * Execute action based on request and return result
 *
 * Note: Request will be added as operation argument in future
 *
 * @return MagentoFrameworkControllerResultInterface|ResponseInterface
 * @throws MagentoFrameworkExceptionNotFoundException
 */

public function execute()
{

    /* Get the post data */
    $data = (array) $this->getRequest()->getPost();

    if (!empty($data)) {

        /* Set the data in the model */
        $testimonialModel = $this->testimonial;
        $authorModel = $this->author;
        $contentModel = $this->content;
        $socialModel = $this->social;

        $date             = date('Y-m-d h:i:sa'); 

        // Set Parent Table Testimonial Data
        $testimonialModel->setData('status', 0 );
        $testimonialModel->setData('created_at', $date);
        $testimonialModel->setData('modified_at', $date);

        //Save Testimonial Table Data
        $this->testimonialResource->save($testimonialModel);

        //Get the last added Testimonial
        $lastTestimonialId = $testimonialModel->getId();

        //Set Testimonial Author Data
        $authorModel->setData('testimonial_id', $lastTestimonialId);
        $authorModel->setData('author_name', $data('author_name'));
        $authorModel->setData('author_email', $data('author_email'));
        $authorModel->setData('author_company', $data('author_company'));
        $authorModel->setData('author_job_title', $data('author_job_title'));
        $authorModel->setData('author_city', $data('author_city'));
        $authorModel->setData('author_image', '123456789');

        //Set Testimonial Social Data
        $socialModel->setData('testimonial_id', $lastTestimonialId);
        $socialModel->setData('facebook_url', $data('facebook_url'));
        $socialModel->setData('linkedin_url', $data('linkedin_url'));
        $socialModel->setData('twitter_url', $data('twitter_url'));
        $socialModel->setData('youtu_url', $data('youtu_url'));

        //Set Testimonial Content Data
        $contentModel->setData('testimonial_id', $lastTestimonialId);
        $contentModel->setData('testimonial_title', $data('testimonial_title'));
        $contentModel->setData('testimonial_description', $data('testimonial_description'));
        $contentModel->setData('testimonial_rating_number', $data('testimonial_rating_number'));

        //Save Testimonial Author Data
        $this->authorResource->save($authorModel);

        //Save Social Informaiton
        $this->socialResource->save($socialModel);

        //Save Testimonial Content Informaiton
        $this->contentResource->save($contentModel);

        $this->messageManager->addSuccessMessage("Testimonial saved successfully!");

        /* Redirect back to Testimonial page */
        $redirect = $this->resultRedirectFactory->create(ResultFactory::TYPE_REDIRECT);
        $redirect->setPath('/testimonial/index/add');
        return $redirect;
    }

    $this->_view->loadLayout();
    $this->_view->renderLayout();
}
}

tout fonctionnait bien sauf si j'ai effectué la compilation magento / bin di: après cela ne fonctionne pas correctement.

J'ai une autre section pour l'administrateur qui nécessitait d'exécuter magento / bin di: compile, donc avant que cette section fonctionne correctement, car je l'ai compilée, commencez à me donner l'erreur:

(2020-05-21 11:36:09) main.DEBUG: Request validation failed for action "ApriljuneTestimonialControllerIndexAddInterceptor" () ()

Typescript Express – Controller in the controller via dependency injection or logic in the routes

I am trying to give an operation to a controller. However, some controllers exist in 2 or more operations. I don't know what is the best way to structure this part of the application.

For example, I have 2 controller functions, each doing its own thing
1. attemptGetUserById (checks entry, calls database provider, returns user or error)
2. tryVerifyToken (check entry, try to check token, return valid / invalid)

Then there is another controller "tryCheckUser"which basically calls
-> attemptVerifyToken -> if the token is valid -> attemptGetUserById

This controller is called via a route.

Now I have 3 variations that might be acceptable.

Variant1
This variant is that described above. When the API endpoint is accessible, it calls tryCheckUser, which calls the other 2 controllers. No logic in Endpoint.

// routes.ts
{
    path: '/api/core/users/check',
    method: 'post',
    handler: (
      async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
        const { error, user } = await attemptCheckUser(authorization)
        if (error) return next(error);
        return res.status(200).send(user);
      },
    ),
  },
  ...

// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
  if (token) {
    const secret = "xxx";
    // only provider - no logic in verifyToken
    const { error, userId } = verifyToken(token, secret); 
    if(error) return { error };
    return { userId, token };
  }
  return { error: new HTTP400Error() };
};


// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
  if (_id) {
    try {
      // only provider - no logic in getFullUserById only db operation
      const user = await getUserById(_id);
      if (user) return { user };
      return { error: new HTTP404Error() };
    } catch (e) {
      return { error: new HTTP400Error(e) };
    }
  }
  return { error: new HTTP400Error() };
};

export const attemptCheckUser = async (token: string) => {
  const { error, userId} = attemptVerifyToken(token);
  if (error) return { error };

  if (userId) {
    const { error, user } = await attemptGetUserById(userId);
    if (error) return { error };
    return { user };
  }
  return { error: new HTTP400Error() };
}

Variant2
Instead of having tryCheckUser, move the logic in Endpoint / Route so that each controller has only one operation. tryVerifyToken and tryGetUserById remain the same as in variant 1

// routes.ts
{
  path: '/api/core/users/check',
  method: 'post',
  handler: (
    async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
      const { error, userId } = attemptVerifyToken(authorization);
      if (error) return next(error);
      if (userId) {
        const { error, user } = await attemptGetUserById(userId);
        if (error) return next(error);
        return res.status(200).send(user);
      }
      return next();
    },
  ),
},
...

// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
  if (token) {
    const secret = "xxx";
    // only provider - no logic in verifyToken
    const { error, userId } = verifyToken(token, secret); 
    if(error) return { error };
    return { userId, token };
  }
  return { error: new HTTP400Error() };
};


// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
  if (_id) {
    try {
      // only provider - no logic in getFullUserById only db operation
      const user = await getUserById(_id);
      if (user) return { user };
      return { error: new HTTP404Error() };
    } catch (e) {
      return { error: new HTTP400Error(e) };
    }
  }
  return { error: new HTTP400Error() };
};

Variant3
This variant is almost identical to variant 1, however, the route injects the dependencies (the other 2 controllers) into tryCheckUser. This controller gets a new interface.

// routes.ts
{
  path: '/api/core/users/check',
  method: 'post',
  handler: (
    async ({ headers: { authorization } }: Request, res: Response, next: NextFunction) => {
      const { error, user } = await attemptCheckUser(
        {
          attemptVerifyToken,
          attemptGetUserById,
        },
        authorization,
      );
      if (error) return next(error);
      return res.status(200).send(user);
    },
  ),
},
...

// auth.controller.ts
export const attemptVerifyToken = (token: string) => {
  if (token) {
    const secret = "xxx";
    // only provider - no logic in verifyToken
    const { error, userId } = verifyToken(token, secret); 
    if(error) return { error };
    return { userId, token };
  }
  return { error: new HTTP400Error() };
};


// user.controller.ts
export const attemptGetUserById = async (_id: string) => {
  if (_id) {
    try {
      // only provider - no logic in getFullUserById only db operation
      const user = await getUserById(_id);
      if (user) return { user };
      return { error: new HTTP404Error() };
    } catch (e) {
      return { error: new HTTP400Error(e) };
    }
  }
  return { error: new HTTP400Error() };
};



interface OptionsCheckUser {
 attemptVerifyToken: (token: string, skipToken?: boolean) => any;
 attemptGetFullUserById: (userId: string, organisationId: string) => any;
}

export const attemptCheckUser = async (dependencies: OptionsCheckUser, token: string) => {
  const { error, userId} = dependencies.attemptVerifyToken(token);
  if (error) return { error };

  if (userId) {
    const { error, user } = await dependencies.attemptGetUserById(userId);
    if (error) return { error };
    return { user };
  }
  return { error: new HTTP400Error() };

I'm creating this question here on codereview, because I came up with the idea of Variant 3. I wanted to decouple these controllers by calling other controllers, but that doesn't seem right to me. The reason I'm not sure is that the interface has to describe the injected functions fairly precisely, which means that there are probably no other functions that I can inject because these functions would theoretically do the same job, so they just don't exist (as they would be duplicates).

Note: Please consider this to be a simplified example. The application will have multiple services and a controller will have to call other controller functions from a different service. This is why I found that I needed some sort of decoupling of these controllers and how they call other controller functions inside.

Which variant would you choose (if any) and why?

Thank you very much in advance!

8 – CKeditor doesn’t work in controller response within a default theme

In a Drupal 8 project I’ve a controller which returns a form that contains a text_format field.

CKeditor is working perfectly in my administration theme (Stable), but it does not on the default theme.

I’ve tried to attach ckeditor core module libraries to the controller returned response with no results.

The role which I test with has permissions “Use simple HTML text format”, “Use full HTML text format”, also the role is checked on /admin/config/content/formats/manage/basic_html also on /admin/config/content/formats/manage/full_html.

my_module/src/Controller/MyController.php :

<?php

namespace Drupalmy_moduleController;

use DrupalCoreControllerControllerBase;
use DrupaluserEntityUser;

/**
 * Provide user form.
 */
class MyController extends ControllerBase {

  /**
   * Return page content.
   */
  public function content() {
    // Load user edit form.
    $entity = User::load(Drupal::currentUser()->id());
    $formObject = Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($entity);
    $form = Drupal::formBuilder()->getForm($formObject);
    $render = Drupal::service('renderer');
    $render_form = $render->renderPlain($form);
    return (
      '#theme' => 'customize_user_form',
      '#form' => $render_form,
      '#attached' => (
        // Attach ckeditor core module libraries.
        'library' => (
          'ckeditor/drupal.ckeditor',
          'ckeditor/drupal.ckeditor.stylescombo.admin',
          'ckeditor/drupal.ckeditor.admin',
          'ckeditor/drupal.ckeditor.plugins.drupalimagecaption',
        ),
      ),
    );
  }

}

Results:

enter image description here

Any suggestions?

Many thanks.

8 – Is there a controller feedback with the meaning "stay on the current page and do not refresh"?

Is there a value that can be returned by a controller function that means, "Stay on the current page and don't refresh"? Kind of like, "Don't pay attention to this click."

For example, a form has "/ download" as action. This path is defined in routing.yml to call a download () function which determines whether the user has permission to download. Otherwise, when the user clicks on Submit, I want him to stay on the same page without changing anything.

I know I can just redirect to the same page. I know I can catch the click and use ajax to determine if they have permission and then ignore the click that way. I'm not looking for suggestions on alternative solutions like these. I just want to know if there is a return value from the controller which means "do nothing".

I have prepared many articles and I have tried to guess what could work (no return, zero return, empty table, empty markup, etc.) but I did not find an answer to this question.

Laravel – Validate the data received in the controller

I have this method in the controller which receives a data string from the request and creates a record.

    public function userCreate(Request $request): JsonResponse
{

    $input = $request->all();

    $validator = Validator::make($input, (
        'user_id' => 'integer',
        'name' => 'string',
        'age' => 'integer',
        'email' => 'required|unique:users,email',
    ));

    if($validator->fails()){
        return $this->jsonValidatorFailedResponse($validator->errors());
    }

    $user = User::create($input);

    return response()->json($user);

}

This code works correctly, if all the fields are filled, it creates the record and if a field is not of the expected type, it returns an error.

An example of an error would be this

The age field must be a number.

That makes it in Spanish because in resources lang es I put the files in this language, but if you look at "age" this is the name to which my field belongs in the model.

I always work with nomenclatures in English, even if my foreheads are in Spanish.

So my question is how do I change the returned error response?
Although it is true that in the controller I only send the request name in English … with that I can't think of how to ask this.

Thank you.

Java – how to get and set the session attribute correctly for multiple variables in the spring boot controller?

I am writing an application that uses Spring boot security and session management with a JDBC. However, I first designed the app under the impression that the Controller was not a singleton. So my controller class was dynamic even if I had read the documents beforehand, I would have realized that it should not be. Although once hosted on a web server, I realized that I had problems with the user session and that I had to read the documentation to better understand it. So now I'm using session management and I'm trying to get all of my variables out of my controller and into my session information in my JDBC. However, I see my car constantly calling Object name = (Object) session.getAttribute() or session.setAttribute("","") in each method where I placed my variables. I am trying to find the best way to call and send data to my session in JDBC.

FYI: I used as 7 global variables in my controller.

Java method:


@RequestMapping(value = "/edit")
    public ModelAndView editPage(@RequestParam(value = "Appcode", required = false, defaultValue = "Appcode") String appcode,HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        session.setAttribute("SELECTED_APP",queryService.findDtoById(appcode)); 
        allPlants = queryService.serverWork();

        try {
            OTSApplication selected_app = (OTSApplication) session.getAttribute("SELECTED_APP");
            rc.setProxy();

            if (rc.ValidateUser(id, selected_app.getSys_id()) != 0 || queryService.isAuditor(id)) { 
                gpSelected = apiRunner.runGPData(selected_app.getGuid());
                modelAndView.setViewName("create");
            } else {
                modelAndView.setViewName("forbidden");
            }

        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.setViewName("test");
        }
        modelAndView.addObject("id", id);
        modelAndView.addObject("hasAccess", false);

        return modelAndView;
    }

Variables that must be in session

    private APIRunner apiRunner;
    private Set aryServer = new HashSet();
    private List aryTier = new ArrayList();
    private List hmap = new ArrayList();
    public List mqlSelectorList = new ArrayList();
    private String name, system, mqlList, tag1, tag2, mqlSelector, parseInstruc, myObject, id;
    private String queryWithServerAttached, secondQuery;
    private List allPlants = new ArrayList();
    private static final Logger logger = LoggerFactory.getLogger(OTSController.class);

I know there must be a simple or better standard way to contain these variables and objects in a JDBC session. If I have to, I don't mind, but I don't want to declare a new object Object name = (Object) session.getAttribute() whenever I want to use the field. Please let me know of any other means.