Recent Entries 10
- debug minor 112d agoValidation that also returns error messagesMy `Create`, `Update` and `Delete` methods should return a `success` and `errors` list depending up on the result. I want to avoid the out parameters in the method. Therefore I came up with an implementation of `ResultModel` class which gets returned for the above mentioned methods. Is my implementation elegant enough to go ahead with the real world project? Or could there be other better ways to return the result? Here is the sample code which actually works. I have inserted `comments` in the code where I think is necessary. ``` public sealed class CountryModel { public string CountryName { get; set; } //mandatory and upto 32 chars public string CountryCode { get; set; } //mandatory and upto 5 chars } /// /// To hold the results, be it the list of errors or just the success message. /// public sealed class ResultModel { private object _success; // to hold boolean and int value. public object Success { get { return _success; } } private List _errors; // to hold multiple errors, could be validation errors. public List Errors { get { return _errors; } } public void AddSuccess(object any) { this._success = any; } public void AddError(string text) { if (string.IsNullOrEmpty(text)) { return; } if (this._errors == null) { this._errors = new List(); } this._errors.Add(text); } } public sealed class CountryManager { private const string EmptyErrorSuffix = "is empty."; private const string LengthErrorSuffix = "has exceeded it's length."; private const short CountryCodeMaxLength = 5; private const short CountryNameMaxLength = 32; public ResultModel AddCountry(CountryModel model) { var result = this.ValidateTheModel(model); if (result.Errors == null) //if no errors then perform the Database operation, in this case Add a record. { try {
- pattern minor 112d agoSharePoint CRUD classI am writing an application where I have some objects like customer, supplier, product, etc. I have written a class for the object 'supplier' and wanted to ask if this is a good design. I have put in the class the object itself, some methods for saving and deleting, ... and some static methods for example to return all suppliers or for example delete a specific supplier other than the current object. This is my class: ``` using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MyApplication.Administration.Utility; using Microsoft.SharePoint; namespace MyApplication.Administration.Model { public class Supplier { public int id { get; set; } public string name { get; set; } public int su_id { get; set; } public string su_name { get; set; } public string portal { get; set; } public string sort_order { get; set; } public bool active { get; set; } public Supplier() { } public static Supplier GetSupplier(int supplierId) { Supplier supplier = new Supplier(); Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate () { string connString = Factories.Database.GetConnectionString(); using (SqlConnection conn = new SqlConnection(connString)) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT supplier.*, supplier_status.name AS su_name FROM supplier INNER JOIN supplier_status ON supplier.su_id = supplier_status.id WHERE supplier.id = @id"; cmd.Parameters.AddWithValue("@id", SqlDbType.Int).Value = supplierId; conn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { if (dr.HasRows) {
- pattern minor 112d agoCode for my first crud appI would like to ask more experienced developers to review my code, it's my first app, self-made, I know there is a lot to improve, it would be great if you could just point the main errors. I'm aware that my implementation is not universal, but I couldnt get past it. My edit option with usage of DTO seems shi*y to me, details can be found in the code. https://github.com/filemonczyk/crud Thanks to all in advance ``` @Controller public class AnimalsController { @Autowired private AnimalDAO animalDAO; @RequestMapping("") public String startPage() { return "home"; } //gives a list of animals of specified type (dog,cat,snake) @RequestMapping("write{animal}") public String getAnimalList(Model model, @PathVariable("animal") String animal ) { model.addAttribute("animalName", animalDAO.getAnimalList(animal)); return "list"; } @RequestMapping("{animal}/{name}/{id}/delete") public String dropAnimal(@PathVariable("id") int id, HttpServletResponse response) throws IOException{ animalDAO.delete(id); response.sendRedirect("http://localhost:8080/crud"); return "home"; } //following 3 methodes are adding new animals to the database, I have used here DTO, had no idea how I can turn it into more flexible solutions @RequestMapping("addCat") public String addAnimal(HttpServletRequest request,HttpServletResponse response, @ModelAttribute("catDto") @Valid CatDTO catDto, BindingResult result) throws IOException{ if(request.getMethod().equalsIgnoreCase("post") && !result.hasErrors()){ Cat cat = new Cat(); cat.setName(catDto.getName()); cat.setAge(catDto.getAge()); cat.setDateOfBirth(catDto.getBirthDay()); cat.setBreed(catDto.getBreed()); cat.setWeight(catDto.getWeight()); cat.setFurColor(catDto.getFurColor()); animalDAO.addAnimal(cat); response.sendRedirect("http://localhost:8080/crud"); return "home"; } return "addCat"; } @RequestMapping("addDog") public String
- debug minor 112d agoLinq-to-Sage: CRUD OperationsFollowing-up on my Linq-to-Sage implementation, I ended up implementing all CRUD operations, following the Sage 300 view protocols. So, the entities derive from classes that look like this: ``` namespace SageAPI.Views.PurchaseOrders { /// /// Defines view and key field mappings for 'Purchase Orders' view. /// [MapsTo("PO0620")] public class PO0620 { [Key(KeyType.GeneratedByView)] [MapsTo("PORHSEQ")] public decimal Key { get; set; } } } ``` The `KeyType` enum determines how keys are generated: ``` public enum KeyType { /// /// Indicates that the key value is specified manually. /// Manual, /// /// Indicates that the key value is handled by the view, like an identity column. /// GeneratedByView, /// /// Indicates that the key value is handled through composition. /// Use for a foreign key column referring to the parent view in a composite-key setup. /// GeneratedByHeader } ``` ...Which determines how the API is being used for inserting/updating these views. So I added 2 static helper methods in the `ViewSet` class: ``` private static bool HasAutomaticKey(TEntity entity) { return GetKeys(entity).Any(key => key.KeyType == KeyType.GeneratedByView || key.KeyType == KeyType.GeneratedByHeader); } private static IEnumerable> GetKeys(TEntity entity) { return entity.GetPropertyInfos().Where(property => property.KeyType != null); } ``` The `WriteKeys` and `WriteEntity` methods are used for writing to the active record: ``` private void WriteEntity(IEnumerable> properties) { foreach (var property in properties) { try { View.Fields.FieldByName(property.FieldName).SetValue(property.Value, false); } catch (COMException exception) { var error = View.Parent.Parent.Errors[0]; throw new SessionErrorException(error.Message, exception); } } } private void WriteKeys(T
- snippet minor 112d agoExample script for teaching DDL and CRUD/DML operationsI have taught some SQL to others before, and I thought of making a script that has these attributes, for the purposes of teaching: - Fully functional to run on local DB instance with no fuss - Easy to follow along - Representative examples of real-life types of operations - Documented The example first goes over some Data Definition Language (DDL) operations, including initializing a database and schema, creating tables with various data types, and creating a few simple triggers. Then it covers fundamental CRUD (or Data Manipulation Language (DDL)) operations. I would like to know, first of all, am I doing things optimally from a SQL standpoint? I want to make sure I am not accidentally teaching bad habits. Besides that, do you think this could be improved from a teaching standpoint to make it easier or more clear to a beginner who is interested in learning SQL? Here is the query: ``` /* Initialize by deleting the database if it already exists, then creating the database: */ use master; go if exists (select name from master.dbo.sysdatabases where name = 'ACME_MFG_CO') drop database ACME_MFG_CO; go create database ACME_MFG_CO; go /* Switch to our new database, so we can perform operations on it: */ use ACME_MFG_CO; go /* Initialize by deleting the schema if it already exists, then creating the schema: */ if (select 1 from sys.schemas where name = 'PRODUCTS') is not null drop schema PRODUCTS; go create schema PRODUCTS; go /***** Data Definition Language (DDL) operations *****/ /* The OBJECT_ID built-in function makes the DB engine check system objects by their name as string * and returns the OBJECT_ID, if found, otherwise null. The following commands will check if * the temporary tables we are about to create already exist, and if they do, they will be dropped/deleted. */ if object_id('ACME_MFG_CO.PRODUCTS.PRODUCT_CATALOG') is not null drop table ACME_MFG_CO.PRODUCTS.PRODUCT_CATALOG; if object_id('ACME_MFG_CO.PRODUCTS.PRODUCT_DEVELOPMEN
- pattern minor 112d agoProductManager: a basic CRUD for products with SQLiteI would like to have a review of this basic CRUD application so I can improve and learn from your experience. The code can be found here. - Design pattern/coding principles improvement that could be used - Exception handling - Readability - Coding best practices ProductManager.java ``` public class ProductManager { private IProductDatabase db; public ProductManager(String Dburl) throws ServiceException { try { db = new SQLiteProductDatabase(Dburl); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public int getNumberOfProducts() throws ServiceException{ try { return db.size(); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public void addProduct(Product product) throws ServiceException { try { db.addProduct(product); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public Product getProductByEan(Long ean) throws ServiceException { try { return db.getProductByEan(ean); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public Product getProductByHope(int hope) throws ServiceException { try { return db.getProductByHope(hope); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public Collection getAllProducts() throws ServiceException { try { return db.getAllProducts(); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public void updateProduct(Product product) throws ServiceException { try { db.updateProduct(product); } catch (DatabaseException ex) { throw new ServiceException(ex); } } public void deleteProduct(Long ean) throws ServiceException
- pattern minor 112d agoNode module for DRY CRUD endpointsAs a learning project I recently started writing a node module to generate / handle the creation of CRUD endpoints in a DRY way. The problem I was initially wanting to solve was that in my generator-angular-fullstack project I had several basic CRUD endpoints that all had identical controllers (e.g. this). My idea was a module that would generate those CRUD methods for different database types, something like: ``` var dryCrud = new DryCrud({ type: 'mongoose', collection: MyMongooseCollection }); app.get('/', dryCrud.read); app.get('/:', dryCrud.read({ query: {'_id':'^id'} // <-- the ^ = req.params. })); ``` Then I had the idea of generating a full set of basic CRUD endpoints: ``` dryCrud.init('routePrefix', app); ``` The .init creates a create, read, read/:id, update/:id and delete endpoint using the supplied express app (or router) with each route prefixed by the `'routePrefix'`, connecting with the database specified in the `dryCrud` creation. I have created a pretty basic module, and two database adaptors (Mongo native and Mongoose) here. I feel like I have been staring at this in isolation for a while, and I would love to know if anyone else thinks a module like this would be useful. Is it worth developing it further? I would also welcome any feedback on my code / structure. The Crudbrella module index.js ``` var _ = require('lodash'), utils = require("./lib/utils-prototype"), Crudbrella; Crudbrella = function(config){ //Check for required config if(!config.collection || !config.type){ //Raise an error here... console.error("dryCrud error: you must provide a database object and type"); process.exit(e.code); return false; } //Constructor of crudbrella object being returned to the user var newCrud = function(){ this.collection = config.collection; this.type = config.type; }; //Include core functionality and utility methods _.extend(newCrud.prot
- pattern minor 112d agoUserDAO with CRUD functionality for my UserRepositoryThis is my first attempt at creating a DAO. I would like to get some feedback regarding the following aspects if possible: - Code readability - Efficiency - Usability I also would appreciate any other suggestions for improvement as well. UserDAO ``` class UserDAO { private $pdo; public function __construct(PDO $pdo) { $this->pdo = $pdo; } public function fetchById($id) { $sql = 'SELECT id,'; $sql .= ' firstname,'; $sql .= ' lastname,'; $sql .= ' email,'; $sql .= ' password'; $sql .= ' FROM users'; $sql .= ' WHERE id = :id'; $sql .= ' LIMIT 1'; $sth = $this->pdo->prepare($sql); $sth->bindValue(':id', $id, PDO::PARAM_INT); $sth->execute(); return $sth->fetch() ?: null; } public function fetchByEmail($email) { $sql = 'SELECT id,'; $sql .= ' firstname,'; $sql .= ' lastname,'; $sql .= ' email,'; $sql .= ' password'; $sql .= ' FROM users'; $sql .= ' WHERE email = :email'; $sql .= ' LIMIT 1'; $sth = $this->pdo->prepare($sql); $sth->bindValue(':email', $email, PDO::PARAM_STR); $sth->execute(); return $sth->fetch() ?: null; } public function insert($firstname, $lastname, $email, $password) { $sql = 'INSERT INTO users (firstname, lastname, email, password) '; $sql .= 'VALUES(:firstname, :lastname, :email, :password)'; $sth = $this->pdo->prepare($sql); $sth->bindValue(':firstname', $firstname, PDO::PARAM_STR); $sth->bindValue(':lastname', $lastname, PDO::PARAM_STR); $sth->bindValue(':email', $email, PDO::PARAM_STR); $sth->bindValue(':password', $password, PDO::PARAM_STR); return $sth->execute(); } public function update($id, $firstname, $lastname, $email, $password) {
- pattern minor 112d agoUser Authentication/Permissions for PHP MySQL CRUDI took my first stab at a user authentication function. I invented my own way of doing this. Is this a safe and efficient way of giving a user Read/Edit/Delete permission on tables in a MySQL database? The Class ``` class Personnel { //set tables that will need permissions and actions protected static $actions = array("read", "edit", "delete"); protected static $table_names = array("species", "users", "news"); //this will generate a form with checkbox for each position in the permissions array public static function set_permissions_form($current_permissions) { for($i=0; $i"; for($z=0; $z"; $form .= ""; } } return $form; } } ``` The Form If this is a new user or an existing user with no permissions set then `$current_permissions` will be `NULL`. If a permissions array does exist in the database unserialize it and check any checkbox when name = array key. ``` $current_permissions = unserialize($personnel->permissions); $form = ""; $form .= Personnel::set_permissions_form($current_permissions); $form .= ""; $form .= ""; echo $form; ``` Save Once the form is submitted each box checked will be a "1" in the permissions array. This next snippet serializes the array and stores it in the database. I did not include code for $personnel->save() but you know what it does. Create user if does not exist, update user if it does. ``` $personnel = new Personnel(); $personnel->permissions = serialize($_POST['permissions']); if($personnel->save()) { redirect_to("manage_personnel.php"); } ``` Check for Permission The next steps I haven't completed yet but basically it will pull `$personnel->permissions` from database and unserialize it. Then say it is on a page where user is trying to edit species, `$permissions["species"]["read"] == '1' ? you shall pass : you shall not pass;`. Am I heading in the right direction with this or am I over complicating?
- pattern minor 112d agoC in CRUD for SilverlightThe C in CRUD Silverlight: - Create new Silverlight business application "CRUD" - Add ADO.NET Entity Data Model to CRUD.web - Select the db, the tables, build the project - Add Domain Service Class to CRUD.web - Select the tables and also select the allow editing option for the table "tname" - Build the project - Keep two textboxes "ID" and "NAME" on MainPage.xaml - Keep a button "SAVE NEW RECORD" on MainPage.xaml - Build - Add the following code ``` Partial Public Class MainPage Inherits UserControl Dim dserv As New DomainService1 //default methods generated Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click 'declare a table object Dim table As New tname 'assign values to fields table.ID = TextBox1.Text table.NAME = TextBox2.Text 'add table object entity dserv.tnames.Add(table) 'submit the changes, to make it permenant in the db dserv.SubmitChanges() End Sub ``` - Record inserted Is this the easiest way for having no side effects to add a new record? Is this the optimal way to add a new record?