Woocommerce Phone Field İnput Mask - wordpress

The code below works fine, but I want no special characters to be entered including the period. In addition, the phone number like "534-055-7888", which it masks, is also shown on the admin panel in the same way. I want it to show as "5340557888" without "-" in admin panel but I couldn't.
`
add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_phone_us_format' );
function bbloomer_checkout_phone_us_format( $fields ) {
$fields['billing']['billing_phone']['placeholder'] = '123-456-7890';
$fields['billing']['billing_phone']['maxlength'] = 12; // 123-456-7890 is 12 chars long
return $fields;
}
add_action( 'woocommerce_after_checkout_form', 'bbloomer_phone_mask_us' );
function bbloomer_phone_mask_us() {
wc_enqueue_js( "
$('#billing_phone')
.keydown(function(e) {
var key = e.which || e.charCode || e.keyCode || 0;
var phone = $(this);
if (key !== 8 && key !== 9) {
if (phone.val().length === 3) {
phone.val(phone.val() + '-'); // add dash after char #3
}
if (phone.val().length === 7) {
phone.val(phone.val() + '-'); // add dash after char #7
}
}
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
" );
}
`

Related

Wrong number returns from EEPROM.get arduino

In the setup function i clear the EEPROM if a specific button is clicked.
in the loop function at the start i have this code:
if(millis() - last_sample >= 180){
sampler();
EEPROM.get(stateEEPROMAdress, stateCode);
stateCode = getState(stateCode);
EEPROM.put(stateEEPROMAdress, stateCode);
Serial.println(stateCode);
}
and a bunch of sampling code.
then at the end of the loop i have:
if(millis() - last_xbee >= 900){
EEPROM.get(packetEEPROMAdress,packetCount );
EEPROM.get(stateEEPROMAdress,stateCode);
if(!initializing || (stateCode!= 0 && stateCode != 1)){
telemetry[2] = packetCount++;}
telemetry[21] =stateCode;
EEPROM.put(packetEEPROMAdress, packetCount);
.... and printing codes...
I also at the start of the sketch i have defined :
const int packetEEPROMAdress = 0;
const int stateEEPROMAdress = packetEEPROMAdress + sizeof(int);
and this is the getState function. simple state determination from sensor values:
int getState(const int stateCode=0){
int outState;
//state 0
if(stateCode == 0 &&(fabs(verticalSpeed) < 2 || fabs(relativeAltitude) < 5)&&initializing){
outState = 0;
//true should change later to see is launch botton is on
} else
if(missionReady && !initializing && stateCode == 0){
outState = 1;
}else if(verticalSpeed > 3&&stateCode == 1){
outState = 2;
}
//else
//if(VerticalSpeed < 3 && stateCode == 2){
// stateCode = 2;
// //apogee but no code in CDR
//}
else if(verticalSpeed < 2 &&stateCode == 2){
outState = 3;
} else if((fabs(relativeAltitude - 450)< 10 || relativeAltitude<440 ) &&stateCode == 3){
outState = 4;
}else
//true should be replaced with seperation photocell is bright
if(true && stateCode == 4){
outState = 5;
}else if(relativeAltitude < 3 && fabs(verticalSpeed) < .7 && stateCode == 5 ){
outState == 6;
//activate Buzzer stop telemetry
}
return outState;
}
everything a good when state is 0 . when i send a command and states becomes 1. the after a few loops that 1 appears. the number in EEPROM becomes 8663 . is there a problem in addressing the EEPROM?
It was sth silly:)
Nothing related to EEPROM.
I didn't give a initial value to outState so large number stored in EEPROM,
Sorry if i got your time:)

Sqlite order by, AaBbCc

I have been trying to get sqlite to order a set of entries by name in the following order
AaBbCcDd......Zz
but the closest I've gotten is using COLLATE NOCASE to get a case insensitive sort.
The entries I have are
Addy|2000-01-22T16:06:14.155Z
alice|2000-01-22T16:06:20.514Z
billyRay|2000-01-22T16:06:36.175Z
Bobby|2000-01-22T16:06:26.868Z
claus|2000-01-22T16:06:52.531Z
CoffinLLC|2000-01-22T15:33:11.235Z
Default|2000-01-22T15:55:12.168Z
I have tried the following select statements in the sqlite3 command line to achieve my goal without success.
select * from t1 order by name COLLATE NOCASE asc;
select * from t1 order by name COLLATE NOCASE, name asc;
select * from t1 order by lower(name), name asc;
select * from t1 order by name, lower(name) asc;
Based on #Griddoor's initial comment, I tried some variations and the following appears to work
select * from t1 order by lower(substr(name,1,1)), name;
const CHAR_CODE_a = 'a'.charCodeAt(0); // 97
const CHAR_CODE_A = 'A'.charCodeAt(0); // 65
const CHAR_CODE_z = 'z'.charCodeAt(0); // 112
const CHAR_CODE_Z = 'Z'.charCodeAt(0); // 90
const diffLowerUpper = CHAR_CODE_a - CHAR_CODE_A;
const isLower = (charCode) => {
return CHAR_CODE_a <= charCode && charCode <= CHAR_CODE_z;
};
const isUpper = (charCode) => {
return CHAR_CODE_A <= charCode && charCode <= CHAR_CODE_Z;
};
const ORDER = {
KEEP : 1,
EXCHANGE : -1,
EQUAL : 0,
}
const A1Bigger = (isAsc) => {
// 以降序的角度考虑,A1大,那么保持即可
return isAsc ? ORDER.EXCHANGE : ORDER.KEEP;
};
const A2Bigger = (isAsc) => {
// 以降序的角度考虑,A2大,那么需要跟A1交换位置
return isAsc ? ORDER.KEEP : ORDER.EXCHANGE;
};
/**
* 比较 A2 字符串与 A1 字符串在第index位谁更大
* 这里的排序规则为: a < A < b < B < c < C 与OfficeExcel保持一致
* #param A2
* #param A1
* #param isAsc
* #param index
*/
const excelStringCompare = (A2, A1, isAsc, index = 0) => {
if(A2 === A1) {
return ORDER.EQUAL
}
const charCodeA1 = A1.charCodeAt(index), charCodeA2 = A2.charCodeAt(index)
// 两个字串相等情况以及处理,会有NaN一定是有一个长度大于另一个,而charCodeAt(index)等于NaN的就说明他的长度更短
if(isNaN(charCodeA1)) {
return A2Bigger(isAsc);
} else if(isNaN(charCodeA2)) {
return A1Bigger(isAsc);
}
// 都是小写或都是大写
if ((isLower(charCodeA1) && isLower(charCodeA2)) || (isUpper(charCodeA1) && isUpper(charCodeA2))) {
if (charCodeA2 < charCodeA1) {
return A1Bigger(isAsc);
}
if (charCodeA2 > charCodeA1) {
return A2Bigger(isAsc);
}
// 当两个字符串这个位相等的时候再比较下个位
return excelStringCompare(A2, A1, isAsc, index + 1 )
}
// A1 小写 A2 大写
else if (isLower(charCodeA1) && isUpper(charCodeA2)) {
// a - A
if (charCodeA1 - charCodeA2 === diffLowerUpper) {
return A1Bigger(isAsc);
} else {
// c - (a - A) < D 即 (c - a = 2) < (D - A = 3)
if (charCodeA1 - diffLowerUpper < charCodeA2) {
return A2Bigger(isAsc);
} else {
return A1Bigger(isAsc);
}
}
}
// A1 大写 A2 小写
else {
// A - a === - (a - A)
if (charCodeA1 - charCodeA2 === -diffLowerUpper) {
return A2Bigger(isAsc);
} else {
// C + (a - A) < d 即 (C - A = 2) < (d - a = 3)
if (charCodeA1 + diffLowerUpper < charCodeA2) {
return A2Bigger(isAsc);
} else {
return A1Bigger(isAsc);
}
}
}
};
const isAsc = true;// 升降序
let strArr = ['a','Ab', 'b', 'aB', 'A', 'B', 'ab', 'AB', 'c', 'D', 'd', 'C']
strArr.sort((a, b) => {
return excelStringCompare(a, b, isAsc)
})
console.log(strArr)

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