PHPExcel - Export Missing Row - phpexcel

Can someone tell me what is wrong with my code as it exports the headers ok but i am missing 1 record from the export. Many Thanks
$rowNumber = 1; //start in cell 1
while ($row = mysql_fetch_assoc($result)) {
$col = 'A'; // start at column A
// returns title row
if ( $rowNumber == 1 ){
$headers = array_keys($row);
foreach($headers as $header) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$header);
$col++;
}
$rowNumber++;
}else{ //returns content rows
$col = 'A';
$rowNumber
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
}
$objPHPExcel->getActiveSheet()->removeColumn('A',3);

You're only displaying the headers for the first row retrieved from your database, not the data from that row....
$rowNumber = 1; //start in cell 1
while ($row = mysql_fetch_assoc($result)) {
$col = 'A'; // start at column A
// returns title row
if ( $rowNumber == 1 ){
$headers = array_keys($row);
foreach($headers as $header) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$header);
$col++;
}
$rowNumber++;
}
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
$objPHPExcel->getActiveSheet()->removeColumn('A',3);

Related

Filling in PDF from web form in PHP

I have a form which on posting submits data to a controller which should then fill necessary fields and present form to users to physically sign before submitting back.
I used Dhek https://github.com/cchantep/dhek do define the fields on which the form data will be placed and FPDF to generate the final PDF for downloading. I am able to get selected checkboxes marked but no text fields are rendered. Here is what I have tried so far
$json = json_decode(file_get_contents($this->getRequest()->getUriForPath('/bundles/app/form.json')));
$responses = $request->query->all();
$pdfSrcPath = $this->container->getParameter('write_to') . '/bundles/app/Membership_App__form.pdf';
$pdf = new \FPDF_FPDI("P", //L=>Landscape / P=>Portrait
"pt" /* point */ );
$fontSize = 14;
$pagecount = $pdf->setSourceFile($pdfSrcPath);
$testText = "abcdefghijklmnopqrstuvwxyz0123456789";
for ($i = 0; $i < $pagecount; $i++)
{
$pdf->AddPage();
$tplIdx = $pdf->importPage($i + 1);
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
if (isset($json->pages[$i]) && isset($json->pages[$i]->areas))
{
for ($j = 0; $j < count($json->pages[$i]->areas); $j++)
{
$area = $json->pages[$i]->areas[$j];
$x = $area->x;
$y = $area->y;
$w = $area->width;
$h = $area->height;
// Draw blue rect at bounds
$pdf->SetDrawColor(0, 0, 255);
$pdf->SetLineWidth(0.2835);
$pdf->Rect($x, $y, $w, $h);
if ($area->type == "checkbox" && $area->name == $responses['title'])
{
$pdf->SetDrawColor(105, 105, 105);
$pdf->SetLineWidth(2.0);
$pdf->Line($x, $y, $x + $w, $y + $h);
$pdf->Line($x, $y + $h, $x + $w, $y);
}
else if ($area->type == "text")
{
// 'Free' text
$pdf->SetLineWidth(1.0); // border
$iw = $w - 2 /* 2 x 1 */ ;
$v = utf8_decode($responses[$area->name]);
$overflow = ($pdf->GetStringWidth($v) > $iw);
while ($pdf->GetStringWidth($v) > $iw)
{
$v = substr($v, 0, -1);
}
if ($overflow)
{
$v = substr($v, 0, -1) . "\\";
}
$pdf->SetXY($x, $y);
// this line is not rendering
// tried $pdf->Write(intval($h),$v);
// and also tried $pdf->Cell($w, intval($h), $v);
$pdf->MultiCell($w, intval($h), $v, true);
}
}
}
}
$pdf->Output("test-dhek.pdf", "F");

WooCommerce - Multiple cart dicounts

I want a cart discount based on the total
5% over $600 order and 10% over $1000?
I can get it to work for the over $600 but not the over $1000. I get an error on line 15.
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code = 'over600'; // your coupon code here
$coupon_codeb = 'over1000'; // your coupon code here
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
if ( $woocommerce->cart->cart_contents_total >= 600 ) {
$woocommerce->cart->add_discount( $coupon_code );
$woocommerce->show_messages();
}
if ( $woocommerce->cart->cart_contents_total >= 1000 ) {
$woocommerce->cart->add_discount( $coupon_codeb );
$woocommerce->show_messages();
}
}
Ended up doing it a completely different way
function nh_custom_coupon_filter() {
global $woocommerce;
$excluded_amount = $discount_percent = 0;
$working_total = $woocommerce->cart->cart_contents_total;
$excluded_categories = array(
217, # Training
223, # Starter Kits
);
# Only apply manual discount if no coupons are applied
if (!$woocommerce->cart->applied_coupons) {
# Find any items in cart that belong to the restricted categories
foreach ($woocommerce->cart->cart_contents as $item) {
$product_categories = get_the_terms($item['product_id'], 'product_cat');
if (empty($product_categories) || is_wp_error($product_categories) || !$product_categories) {
if (is_wp_error($product_categories)) {
wp_die($product_categories->get_error_message());
}
else {
$product_categories = new WP_Error('no_product_categories', "The product \"".$item->post_title."\" doesn't have any categories attached, thus no discounts can be calculated.", "Fatal Error");
wp_die($product_categories);
}
}
foreach ($excluded_categories as $excluded_category) {
foreach ($product_categories as $category) {
if ($excluded_category == $category->term_id) {
$excluded_amount += $item['line_subtotal']; # Increase our exclusion amount
$working_total -= $item['line_subtotal']; # Decrease our discountable amount
}
}
}
}
# Logic to determine WHICH discount to apply based on subtotal
if ($working_total >= 600 && $working_total < 1000) {
$discount_percent = 5;
}
elseif ($working_total >= 1000) {
$discount_percent = 10;
}
else {
$discount_percent = 0;
}
# Make sure cart total is eligible for discount
if ($discount_percent > 0) {
$discount_amount = ( ( ($discount_percent/100) * $working_total ) * -1 );
$woocommerce->cart->add_fee('Bulk Discount', $discount_amount);
}
}
}
add_action('woocommerce_cart_calculate_fees', 'nh_custom_coupon_filter');

Need assistance with recursion in JS

I'm having a great deal of trouble wrapping my head around recursion. Simple recursion I can do but this is one is not easy for me. My goal here is to speed up this search algorithm. I'm guessing recursion will help. It takes 15 seconds on a simple 43 node tree with children as it is. Below is my unrolled recursion fomr of the code that works.
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
var find = function ( condition )
{
}
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var j = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var k = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
}
j++;
}
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
*** second revision suggested by Mirco Ellmann *****
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
n = this.treeIDMap.igTree( "childrenByPath", count );
while ( n[i] )
{
if ( n[i].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var j = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i );
while ( n[j] )
{
if ( n[j].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var k = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i + "_" + j);
while ( n[k] )
{
if ( n[k].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
****using my branchable trees to get the data no need for any calls to tree****
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
if ( n.data.branch )//look at all childer under the root node
{
var i = 0;
n = n.data.branch;
while ( n[i] )//look at all childer under the root node
{
if ( n[i].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[i].branch )//look deeper
{
var j = 0;
n = n[i].branch;
if ( n[j].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[j].branch )//look deeper
{
var k = 0;
n = n[j].branch;
if ( n[k].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
instead of always use "nodeByPath" you should use "childrenByPath".
that would minimize the search calls on the igTree.
PS: USE not REPLACE ;)
You're not really doing this recursively. You're rather repeating your code for each level in the hierarchy. What you want is a helper function which takes the current node-path as a parameter and recursively calls the same method for each of its children with their id added to the path of the current node. Recursively means the code should work for any depth of tree. To me it looks like your code will only work for a set depth.
For the speed issue, there might be two issues. I didn't really read your code too closely, so I leave it to you to figure out which one is more likely.
You might be revisiting nodes. If so, obviously that would impact performance.
The framework you're using might be slow with looking up the nodes. One solution could be to find alternate methods to call on the framework which is meant for what you're doing. For instance the framework might have a hierarchical representation internally, but has to rebuild it or parse it when you pass in your full paths. Look for methods taking a source and relative path instead. If that's not the problem the framework might just be slow, and you might be better of to read all the nodes and build your own in-memory tree to use instead.
ok, I found a way to use the data provider and use a normal Json search. Still if anyone can speed this up I'd be grateful. I just when from 15 seconds to 1. This one has the recursion I need.
findInObject = function( obj, prop, val )
{
if ( obj !== null && obj.hasOwnProperty( prop ) && obj[prop].toLowerCase().indexOf(val) > -1 )
{
return obj;
} else
{
for ( var s in obj )
{
if ( obj.hasOwnProperty( s ) && typeof obj[s] == 'object' && obj[s] !== null )
{
var result = findInObject( obj[s], prop, val );
if ( result !== null )
{
return result;
}
}
}
}
return null;
}
for ( var i = 0; i < this.treeData.length; i++)
{
if ( findInObject( this.treeData[i], "ITEM", filter ) ) foundNodes.push( this.treeData[i] )//does the node have a match?
}
this.treeIDMap.igTree( { dataSource: foundNodes } );
this.treeIDMap.igTree( "dataBind" );
};

Permission based access control

I am trying to implement permission based access control in ASP.NET. To implement this I have created some database tables that hold all the information about which roles are assigned what permissions and which roles are assigned to what user.
I am checking the permissions in the business access layer. Right now I have created a method which checks the permissions of the user. If the user has permissions then okay otherwise it redirects to another page.
I want to know if the following things are possible?
class User
{
[PremissionCheck(UserID,ObjectName,OperationName)]
public DataTable GetUser()
{
//coding for user
}
}
I have seen it in MVC3. Can I Create it in ASP.NET? If yes then how can I implement it?
Any permissions system requires two components -- authorization and access control. Authorization is the means to prove the user's identity. This is accomplished, usually, with some kind of user and password storage, but you can use systems like OpenID, or any number of federated identity systems (Active Directory/Kerberos/etc.) to accomplish the same thing.
Once you know who the user is, then there's access control, which is enforcing permssions against that user.
Now, in ASP.NET's case, you're not going to be able to just stick an attribute on something, because attributes do not run code. In order to get the validation code to run, you would need to write a plugin of some sort to do this validation for you. Webforms already has support for authentication and access control mechanisms; why reinvent the wheel?
I want to know if the following things are possible?
class User {
[PremissionCheck(UserID,ObjectName,OperationName)]
public DataTable GetUser()
{
//coding for user
} }
No. It´s not possible in ASP.Net webforms
However, I've implemented Role Based Access Control on a a classic 3-tier ASP.Net 3.5 web forms application, using a MasterPage, a BasePage class and a RoleBasedAccessControl database model.
Example
User "jtirado" is assigned role "HR-Assistant", can access route "mywebapp/employee.aspx?id=1452" to edit employee (id:1452) data.
Being "HR-Assistant", this user can change employee telephone number and e-mail, can view employee salary but not edit the amount.
Telephone number, email, salary are dabatase fields and are represented/rendered by a "asp.net-control" on the ASPX page. So I want to restrict access to these controls based on user's role.
MasterPage builds the options menu the user has access according to his assigned role. It's used by all my internal pages.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
CargaItemMenu(MnuPrincipal, Convert.ToInt32(Session["IdPais"]), Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdUsuario"]));
Session.Add("MenuDinamico", MnuPrincipal);
if (MnuPrincipal.Items.Count < 1)
{
MenuItem menuItems = new MenuItem();
menuItems.Text = "Principal";
menuItems.Value = "1";
menuItems.NavigateUrl = "";
menuItems.Selectable = true;
MnuPrincipal.Items.Add(menuItems);
}
}
}
private void CargaItemMenu(Menu ctrlmenu, int v_IdPais, int v_IdRol, int v_IdUsuario)
{
oBEOpcionRol = new SEGU.Entities.ENOpcionRol();
oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
List<ParametroGenerico> ArrayParam;
ArrayParam = CargarParamentrosOpcionRol(v_IdPais, v_IdRol, v_IdUsuario);
List<SEGU.Entities.ENOpcionRol> ListaMenuItems = oBLOpcionRol.ListaxIdPaisxIdRolxIdUsuario(ArrayParam);
foreach (SEGU.Entities.ENOpcionRol objOpcionRol in ListaMenuItems)
{
if (objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
{
MenuItem mnuMenuItem = new MenuItem();
mnuMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
mnuMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
if (objOpcionRol.IdOpcion.RutaFormulario != "")
{
mnuMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
}
if (objOpcionRol.IdOpcion.PageNew == "1")
{
mnuMenuItem.Target = "_blank";
}
//mnuMenuItem.Target = "iframePrincipal"
if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
{
mnuMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
}
if ((mnuMenuItem.NavigateUrl.Trim().Length > 0))
{
mnuMenuItem.Selectable = true;
}
else
{
mnuMenuItem.Selectable = false;
}
ctrlmenu.Items.Add(mnuMenuItem);
AddMenuItem(mnuMenuItem, ListaMenuItems);
}
}
}
private void AddMenuItem(MenuItem mnuMenuItem, List<SEGU.Entities.ENOpcionRol> listaOpcionRol)
{
foreach (SEGU.Entities.ENOpcionRol objOpcionRol in listaOpcionRol)
{
if (objOpcionRol.IdOpcion.IdMenu.ToString().Equals(mnuMenuItem.Value) && !objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
{
MenuItem mnuNewMenuItem = new MenuItem();
mnuNewMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
mnuNewMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
if (objOpcionRol.IdOpcion.RutaFormulario != "")
{
mnuNewMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
}
if (objOpcionRol.IdOpcion.PageNew == "1")
{
mnuNewMenuItem.Target = "_blank";
}
mnuMenuItem.ChildItems.Add(mnuNewMenuItem);
//mnuNewMenuItem.Target = "iframePrincipal"
if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
{
mnuNewMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
}
if ((mnuNewMenuItem.NavigateUrl.Trim().Length > 0))
{
mnuNewMenuItem.Selectable = true;
}
else
{
mnuNewMenuItem.Selectable = false;
}
AddMenuItem(mnuNewMenuItem, listaOpcionRol);
}
}
}
BasePage class checks if the user has access to the required page. All pages requiring authorization inherit from this BasePage class.
public class PaginaBase : System.Web.UI.Page
{
SEGU.BusinessLogic.BLOpcionRol oBLOpcionRol;
protected void Page_InitComplete(object sender, System.EventArgs e) {
string Url = this.Page.AppRelativeVirtualPath;
oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
int b = oBLOpcionRol.AutentificarUrl(Convert.ToInt32(System.Web.HttpContext.Current.Session["IdPais"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdUsuario"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdRol"]), Url);
System.Web.HttpContext.Current.Session["IdOpcion"] = b;
if( b <= 0 ){
System.Web.HttpContext.Current.Response.Redirect("~/Seguridad/Acceso.aspx");
return;
}
}
.
.
}
Finally, on Customers.aspx Page_Load event I call a function (oBLPermisoOpcionRol.ValidarPermisos) which checks which receives the Page instance as parameters and iterate its controls (ex: DdlClientType, TxtLastName,ChkIsActive) to check which ones the user can edit, enabling, disabling or hiding them.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetNodosMenu(TrvMenu, "");
if (this.TrvMenu.Nodes.Count < 1)
{
PrimerNodos(this.TrvMenu);
}
ListarModuloxAnulado(GvModulo, Convert.ToString(RblAnuladoModuloBusqueda.SelectedValue), Convert.ToInt32(0), Convert.ToInt32(DdlNroPaginaModulo.SelectedValue));
oBLPermisoOpcionRol = new SEGU.BusinessLogic.BLPermisoOpcionRol();
oBLPermisoOpcionRol.ValidarPermisos(Page, Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdOpcion"]));
}
}
public void ValidarPermisos(System.Web.UI.Page v_Page, int v_IdRol, int v_IdOpcion)
{
BusinessLogic.BLPermisoOpcionRol oBLPermisoOpcionRol = new BusinessLogic.BLPermisoOpcionRol();
List<ParametroGenerico> ArrayParam ;
ArrayParam = CargarParametros(v_IdRol, v_IdOpcion);
List<SEGU.Entities.ENPermisoOpcionRol> Lista = oBLPermisoOpcionRol.ListaxIdRolxIdOpcion(ArrayParam);
for(int Fila= 0; Fila< Lista.Count; Fila++){
bool v_Anulado= true;
if (Lista[Fila].Anulado == "1") {
v_Anulado = true;
}else if (Lista[Fila].Anulado == "0") {
v_Anulado = false;
}
bool v_ControlVisibleDisabled = true;
if (Lista[Fila].VisbleDisabled == "1") // Control Disabled
{
v_ControlVisibleDisabled = true;
}
else if (Lista[Fila].VisbleDisabled == "0") // Control Visible
{
v_ControlVisibleDisabled = false;
}
SetControls(v_Page, Lista[Fila].IdPermiso.Control, v_Anulado, v_ControlVisibleDisabled);
}
}
public void SetControls(System.Web.UI.Control parentControl, string v_Control, bool permitir, bool v_Permitir_ControlVisibleDisabled)
{
foreach(System.Web.UI.Control c in parentControl.Controls){
if( (c) is Button ){
if( ((Button)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Button)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((Button)c).Visible = false;
}
}else{
((Button)c).Visible = true;
}
}
}else if( (c) is CheckBox ){
if( ((CheckBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((CheckBox)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((CheckBox)c).Visible = false;
}
}else{
((CheckBox)c).Visible = true;
}
}
}else if( (c) is Label ){
if( ((Label)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Label)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((Label)c).Visible = false;
}
}else{
((Label)c).Visible = true;
}
}
}else if( (c) is TextBox ){
if( ((TextBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((TextBox)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((TextBox)c).Visible = false;
}
}else{
((TextBox)c).Visible = true;
}
}
}else if( (c) is GridView ){
if( ((GridView)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((GridView)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((GridView)c).Visible = false;
}
}else{
((GridView)c).Visible = true;
}
}
}else if( (c) is ImageButton ){
if( ((ImageButton)c).ID == v_Control ){
if (permitir == true)
{
if (v_Permitir_ControlVisibleDisabled == true)
{
((ImageButton)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((ImageButton)c).Visible = false;
}
}
else
{
((ImageButton)c).Visible = true;
}
}
}else if( (c) is HyperLink ){
if( ((HyperLink)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((HyperLink)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((HyperLink)c).Visible = false;
}
}else{
((HyperLink)c).Visible = true;
}
}
}else if( (c) is DropDownList ){
if( ((DropDownList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((DropDownList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((DropDownList)c).Visible = false;
}
}else{
((DropDownList)c).Visible = true;
}
}
}else if( (c) is ListBox ){
if( ((ListBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((ListBox)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((ListBox)c).Visible = false;
}
}else{
((ListBox)c).Visible= true;
}
}
}else if( (c) is DataList ){
if( ((DataList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((DataList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((DataList)c).Visible = false;
}
}else{
((DataList)c).Visible = true;
}
}
}else if( (c) is CheckBoxList ){
if( ((CheckBoxList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((CheckBoxList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((CheckBoxList)c).Visible = false;
}
}else{
((CheckBoxList)c).Visible = true;
}
}
}else if( (c) is RadioButton ){
if( ((RadioButton)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((RadioButton)c).Enabled= false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((RadioButton)c).Visible = false;
}
}else{
((RadioButton)c).Visible = true;
}
}
}else if( (c) is RadioButtonList ){
if( ((RadioButtonList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((RadioButtonList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((RadioButtonList)c).Visible = false;
}
}else{
((RadioButtonList)c).Visible = true;
}
}
}else if( (c) is Image ){
if( ((Image)c).ID == v_Control ){
if( permitir == true ){
((Image)c).Visible = false;
}else{
((Image)c).Visible = true;
}
}
}else if( (c) is Panel ){
if( ((Panel)c).ID == v_Control ){
if (permitir == true)
{
if (v_Permitir_ControlVisibleDisabled == true)
{
((Panel)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((Panel)c).Visible = false;
}
}
else
{
((Panel)c).Visible = true;
}
}
}else if( (c) is Table ){
if( ((Table)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Table)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((Table)c).Visible = false;
}
}else{
((Table)c).Visible= true;
}
}
}else if( (c) is LinkButton ){
if( ((LinkButton)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((LinkButton)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((LinkButton)c).Visible = false;
}
}else{
((LinkButton)c).Visible = true;
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlInputButton ){
if( ((System.Web.UI.HtmlControls.HtmlInputButton)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = false;
((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Add("disabled", "disabled");
}else{
((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = true;
((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Remove("disabled");
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlAnchor ){
if( ((System.Web.UI.HtmlControls.HtmlAnchor)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = false;
// CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Add("disabled", "disabled")
}else{
((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = true;
//CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Remove("disabled") '' etiqueta <a runat="server" ID="id1">
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlGenericControl ){
if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).TagName.ToUpper() == "DIV".ToUpper() ){
if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = false;
//CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Add("disabled", "disabled")
}else{
((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = true;
//CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Remove("disabled") '' etiqueta <div runat="server" ID="iddiv">
}
}
}
}
SetControls(c, v_Control, permitir, v_Permitir_ControlVisibleDisabled);
}
}
This way, I don't have to use if-then sentences to check permissions and, I can create as many roles as I want, giving them any permissions, without having to change any C# code.
You can check these posts also:
Is ASP.NET role based security a true role based access control system?
Role-based access control - should I have the permission list in the db as well or just in the code (eg enum)?
How to control access to forms fields on a ASP.Net MVC 3 view?

Calculate percentage saved between two numbers?

I have two numbers, the first, is the original price, the second, is the discounted price.
I need to work out what percentage a user saves if they purchase at the second price.
example
25, 10 = 60%
365, 165 = 55%
What I dont know is the formula to calculate this.
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
Let's say you have two numbers, 40 and 30.
30/40*100 = 75.
So 30 is 75% of 40.
40/30*100 = 133.
So 40 is 133% of 30.
The percentage increase from 30 to 40 is:
(40-30)/30 * 100 = 33%
The percentage decrease from 40 to 30 is:
(40-30)/40 * 100 = 25%.
These calculations hold true whatever your two numbers.
Original Post
((list price - actual price) / (list price)) * 100%
For example:
((25 - 10) / 25) * 100% = 60%
I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:
(1 - (oldNumber / newNumber)) * 100
So, the percentage difference from 30 to 40 is:
(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
The percentage difference from 40 to 30 is:
(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
In php, I use a function like this:
function calculatePercentage($oldFigure, $newFigure) {
if (($oldFigure != 0) && ($newFigure != 0)) {
$percentChange = (1 - $oldFigure / $newFigure) * 100;
}
else {
$percentChange = null;
}
return $percentChange;
}
The formula would be (original - discounted)/original. i.e. (365-165)/365 = 0.5479...
function calculatePercentage($oldFigure, $newFigure)
{
$percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
return round(abs($percentChange));
}
100% - discounted price / full price
If total no is: 200
and getting 50 number
then take percentage of 50 in 200 is:
(50/200)*100 = 25%
I have done the same percentage calculator for one of my app where we need to show the percentage saved if you choose a "Yearly Plan" over the "Monthly Plan". It helps you to save a specific amount of money in the given period. I have used it for the subscriptions.
Monthly paid for a year - 2028
Yearly paid one time - 1699
1699 is a 16.22% decrease of 2028.
Formula: Percentage of decrease = |2028 - 1699|/2028 = 329/2028 = 0.1622
= 16.22%
Code:
func calculatePercentage(monthly: Double, yearly: Double) -> Double {
let totalMonthlyInYear = monthly * 12
let result = ((totalMonthlyInYear-yearly)/totalMonthlyInYear)*100
print("percentage is -",result)
return result.rounded(toPlaces: 0)
}
Usage:
let savingsPercentage = self.calculatePercentage(monthly: Double( monthlyProduct.price), yearly: Double(annualProduct.price))
self.btnPlanDiscount.setTitle("Save \(Int(savingsPercentage))%",for: .normal)
The extension usage for rounding up the percentage over the Double:
extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
I have attached the image for understanding the same:
This is function with inverted option
It will return:
'change' - string that you can use for css class in your template
'result' - plain result
'formatted' - formatted result
function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){
$value = $newNumber - $oldNumber;
$change = '';
$sign = '';
$result = 0.00;
if ( $invert ) {
if ( $value > 0 ) {
// going UP
$change = 'up';
$sign = '+';
if ( $oldNumber > 0 ) {
$result = ($newNumber / $oldNumber) * 100;
} else {
$result = 100.00;
}
}elseif ( $value < 0 ) {
// going DOWN
$change = 'down';
//$value = abs($value);
$result = ($oldNumber / $newNumber) * 100;
$result = abs($result);
$sign = '-';
}else {
// no changes
}
}else{
if ( $newNumber > $oldNumber ) {
// increase
$change = 'up';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
}else{
$result = 100.00;
}
$sign = '+';
}elseif ( $oldNumber > $newNumber ) {
// decrease
$change = 'down';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
} else {
$result = 100.00;
}
$sign = '-';
}else{
// no change
}
$result = abs($result);
}
$result_formatted = number_format($result, 2);
if ( $invert ) {
if ( $change == 'up' ) {
$change = 'down';
}elseif ( $change == 'down' ) {
$change = 'up';
}else{
//
}
if ( $sign == '+' ) {
$sign = '-';
}elseif ( $sign == '-' ) {
$sign = '+';
}else{
//
}
}
if ( $format ) {
$formatted = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
} else{
$formatted = $result_formatted;
}
return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}
I think this covers this formula sufficiently,
((curr value - base value) / (curr value)) * 100%
Basically we just (in programming):
perform the calculation if both numbers are not 0.
If curr value is 0 then we return -100 % difference from the base,
if both are 0 then return 0 (we can't divide by 0)
Powershell example:
Strip any non numeric from vars and perform calculation
Function Get-PercentageSaved {
#((curr value - base value) / (curr value)) * 100%
param(
[Parameter(Mandatory = $false)][string]$CurrVal = $null,
[Parameter(Mandatory = $false)][string]$BaseVal = $null
)
$Result = $null
Try {
$CurrVal = [float]($CurrVal -replace '[^0-9.]', '')
$BaseVal = [float]($BaseVal -replace '[^0-9.]', '')
if (-Not($null -eq $CurrVal) -And (-Not($null -eq $BaseVal))) {
if ($CurrVal -eq 0) {
If ($BaseVal -eq 0) {
$Result = 0
} Else {
$Result = -100
}
}
else {
$Result = [math]::Round([float]((($CurrVal - $BaseVal) / $CurrVal) * 100),2)
}
}
}
Catch {}
Return [float]$Result
}

Resources